当前位置:   article > 正文

Elasticsearch 7.16.x Java 开发之项目搭建_co.elastic.clients.elasticsearch-java 封装

co.elastic.clients.elasticsearch-java 封装

Elasticsearch 7.16.x Java 开发之项目搭建

一、背景概述

公司升级 ES 库版本,从 5.x 升至 7.16,然后就有了今天的故事…

二、Java Rest Client

  • Java Low Level Rest Client:低级别客户端,允许通过 HTTP 请求与 ES 集群进行通信,封装度低但无视 ES 版本。
  • Java High Level Rest Client:高级别客户端,基于低级别客户端封装。

Java Low Level Rest Client

官网地址:Java Low Level REST Client

相关依赖

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-client</artifactId>
    <version>7.16.2</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5

代码示例

public RestClient getClient() {
    // ES 连接信息
    HttpHost[] hosts = {new HttpHost("localhost", 9200, "http")};
    // 如果有密码,设置身份认证
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elasticsearch", "123456"));
    // 创建 LOW-LEVEL-CLIENT 连接
    return RestClient.builder(hosts)
            .setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder
                    // 统一设置 REQUEST 请求,也可以分别设置每个 REQUEST 请求,见方法 getSpecialRequest()
                    .setConnectTimeout(6000)
                    .setSocketTimeout(6000)
            )
            .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder
                    // 设置身份认证
                    .setDefaultCredentialsProvider(credentialsProvider)
                    // 设置线程数
                    .setDefaultIOReactorConfig(IOReactorConfig.custom().setIoThreadCount(6).build())
            )
            .build();
}

/**
 * 单独设置 REQUEST 请求
 */
public Request getSpecialRequest(Request request) {
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(6000)
            .setSocketTimeout(6000).build();
    RequestOptions options = RequestOptions.DEFAULT.toBuilder().setRequestConfig(requestConfig).build();
    request.setOptions(options);
    return request;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

测试一下~

/**
 * @param myIndex 索引库库名
 */
public void test(String myIndex) {
    RestClient lowLevelClient = getClient();
    Request request = new Request("POST", "/" + myIndex + "/_search");
    request.setEntity(new StringEntity("{'query':{'match':{'title':'ES'}}}", StandardCharsets.UTF_8));
    Response response = lowLevelClient.performRequest(request);
    HttpEntity entity = response.getEntity();
    String result = EntityUtils.toString(entity, StandardCharsets.UTF_8);
    return JSON.parseObject(result);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

Java High Level Rest Client

官网地址:Elasticsearch Java API Client

相关依赖

<dependency>
    <groupId>co.elastic.clients</groupId>
    <artifactId>elasticsearch-java</artifactId>
    <version>7.16.2</version>
</dependency>
<!-- 这个依赖官方文档给的是 2.12.3,但我 Class/Method Not Found -->
<!-- 大胆猜测一下,官方写错了~ -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.11.2</version>
</dependency>
<!-- 大胆猜测一下,官方写错了~ -->
<!-- 这个依赖官方文档给的是 2.12.3,但我 Class/Method Not Found -->
<!-- 这个依赖官方文档没写,Class/Method Not Found 的同志可以加上这个试试 -->
<dependency>
    <groupId>jakarta.json</groupId>
    <artifactId>jakarta.json-api</artifactId>
    <version>2.0.1</version>
</dependency>
<!-- 这个依赖官方文档没写,Class/Method Not Found 的同志可以加上这个试试  -->
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

另外,如果项目本身是 Spring Boot 项目,需额外注意,Spring 是否声明了其他版本的 ES,Spring Data也是整了 ES 的,别问我为什么不用,问就是那个版本太低不好使。我在这个坑里躺了 N 久…闻者伤心见者流泪…

<properties>
    <elasticsearch.version>7.16.2</elasticsearch.version>
</properties>
  • 1
  • 2
  • 3

代码示例

public ElasticsearchClient getClient() {
    // ES 连接信息
    HttpHost[] hosts = {new HttpHost("localhost", 9200, "http")};
    // 如果有密码,设置身份认证
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "123456"));
    // 创建 LOW-LEVEL-CLIENT 连接
    RestClient lowLevelClient = RestClient.builder(hosts)
            // 设置身份认证
            .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder
                    .setDefaultCredentialsProvider(credentialsProvider))
            .build();
    ElasticsearchTransport transport = new RestClientTransport(lowLevelClient, new JacksonJsonpMapper());
    ElasticsearchClient client = new ElasticsearchClient(transport);
    return client;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

测试一下~

/**
 * @param myIndex 索引库库名
 */
public void test(String myIndex) {
    ElasticsearchClient highLevelClient = getClient();
    SearchResponse<MyEntity> search = highLevelClient.search(searchRequest -> searchRequest
                    .index(myIndex)
                    .query(query -> query.term(term -> term.field("title").value(value -> value.stringValue("ES")))),
            MyEntity.class);
    for (Hit<MyEntity> hit : search.hits().hits()) {
        log.info(hit.source().toString());
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

到此结束~~~

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/462604
推荐阅读
相关标签
  

闽ICP备14008679号