elasticsearch-Rest-Client

蔺沛
2023-12-01

java操作es

springboot整合

1、依赖。版本需要与es一致

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.4.2</version>
</dependency>

2、配置类

@Configuration
public class ElasticSearchConfig {
    public static final RequestOptions COMMON_OPTIONS; //RequestOptions配置项,参考官网,根据需要可以添加es的请求头信息(如安全头)

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

    @Bean
    public RestHighLevelClient esRestClient() {

        RestClientBuilder builder = null;
        // 可以指定多个es
        builder = RestClient.builder(new HttpHost("192.168.1.22", 9200, "http"));

        RestHighLevelClient client = new RestHighLevelClient(builder);
        return client;
    }
}

3、测试

/**
 * 给es存储数据
 */
@Test
public void test01() throws IOException {
    // 设置索引
    IndexRequest indexRequest = new IndexRequest ("users");
    indexRequest.id("1");
  
    //准备数据
    Map<String,Object> user = new HashMap<>();
    user.put("name","goku");
    user.put("age",15);
    String jsonStringUser = JSON.toJSONString(user);
    indexRequest.source(jsonStringUser, XContentType.JSON);

    //执行
    IndexResponse index = client.index(indexRequest, ElasticSearchConfig.COMMON_OPTIONS);
    System.out.println(index);
}

使用

api文档地址

Search API (_search)

GET band/_search
{
  "query": {
    "match": {
      "address": "mill"
    }
  }
}
/**
 * SearchRequest 查询
 * @throws IOException
 */
@Test
public void test02() throws IOException {
    // 1 创建检索请求
    SearchRequest searchRequest = new SearchRequest();
    // 指定索引
    searchRequest.indices("band");
    // 构造检索条件 DSL
    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
    /*
    sourceBuilder.query(); 匹配查询
    sourceBuilder.from(); 分页查询 from 起始,size 尺寸
    sourceBuilder.size();
    sourceBuilder.aggregation(); 聚合
    */
    sourceBuilder.query(QueryBuilders.matchQuery("address","mill"));
    System.out.println(sourceBuilder.toString());
    searchRequest.source(sourceBuilder);

    // 2 执行检索
    SearchResponse response = client.search(searchRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
    // 3 分析响应结果
    System.out.println(response.toString());
}
 类似资料: