ElasticSearch测试保存和复杂查询(Java版本)

本文展示了如何使用Java与ElasticSearch进行交互,包括保存数据到'users'索引并验证,以及执行复杂的搜索查询,返回包含'account_number', 'balance', 'firstname', 'lastname'等字段的搜索结果,并对'age'和'balance'进行聚合分析。" 99463454,8708223,Eclipse安装与使用及String类详解,"['Eclipse', 'Java', '字符串处理']
摘要由CSDN通过智能技术生成

1.根据ES版本引入相应版本的依赖

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>${elasticsearch.version}</version>
</dependency>

2.配置相应配置类

import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticSearchConfig {

    public static final RequestOptions COMMON_OPTIONS;
    static {
        RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
        COMMON_OPTIONS = builder.build();
    }

    @Bean
    public RestHighLevelClient esRestClient(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("192.168.56.10", 9200, "http")));
        return  client;
    }
}

3.测试保存

3.1先创建一个User类

@Data
class User{
    private String name;
    private Integer age;
    private String gender;
}

3.2进行测试

@Autowired
private RestHighLevelClient highLevelClient;
@Test
//添加,更新
public void indexData() throws IOException {
    IndexRequest indexRequest = new IndexRequest("users");
    indexRequest.id("1");
    //indexRequest.source("name","xs","age",15,"gender","male");
    User user = new User();
    user.setAge(12);
    user.setGender("male");
    user.setName("xs");
    String json = JSON.toJSONString(user);
    indexRequest.source(json, XContentType.JSON);
    IndexResponse index = highLevelClient.index(indexRequest, ElasticSearchConfig.COMMON_OPTIONS);
    System.out.println("index="+index);
}

输出得到:index=IndexResponse[index=users,type=_doc,id=1,version=2,result=updated,seqNo=1,primaryTerm=1,shards={"total":2,"successful":1,"failed":0}]

使用Kibana进行搜索:

GET users/_search

发现保存成功:

{
  "took" : 200,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 1.0,

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值