Elasticsearch:从 Java High Level Rest Client 切换到新的 Java API Client

作者:David Pilato

我经常在讨论中看到与 Java API 客户端使用相关的问题。 为此,我在 2019 年启动了一个 GitHub 存储库,以提供一些实际有效的代码示例并回答社区提出的问题。

从那时起,高级 Rest 客户端 (High Level Rest Cliet - HLRC) 已被弃用,并且新的 Java API 客户端已发布。

为了继续回答问题,我最近需要将存储库升级到这个新客户端。 尽管它在幕后使用相同的低级 Rest 客户端,并且已经提供了升级文档,但升级它并不是一件小事。

我发现分享为此必须执行的所有步骤很有趣。 如果你 "只是寻找" 进行升级的拉取请求,请查看:

这篇博文将详细介绍你在这些拉取请求中可以看到的一些主要步骤。

Java 高级 Rest 客户端 (High Level Rest Client)

我们从一个具有以下特征的项目开始

注意:大家在这里对于 7.17.16 的选择可能有点糊涂。我们需要记住的一点是上一个大的版本的最后一个版本和下一个大的版本的第一个是兼容的。

客户端依赖项是:

xml 复制代码
1.  <!-- Elasticsearch HLRC -->
2.  <dependency>
3.    <groupId>org.elasticsearch.client</groupId>
4.    <artifactId>elasticsearch-rest-high-level-client</artifactId>
5.    <version>7.17.16</version>
6.  </dependency>

8.  <!-- Jackson for json serialization/deserialization -->
9.  <dependency>
10.      <groupId>com.fasterxml.jackson.core</groupId>
11.      <artifactId>jackson-core</artifactId>
12.      <version>2.15.0</version>
13.  </dependency>
14.  <dependency>
15.      <groupId>com.fasterxml.jackson.core</groupId>
16.      <artifactId>jackson-databind</artifactId>
17.      <version>2.15.0</version>
18.  </dependency>

我们正在检查本地 Elasticsearch 实例是否正在 http://localhost:9200 上运行。 如果没有,我们将启动测试容器:

ini 复制代码
1.  @BeforeAll
2.  static void startOptionallyTestcontainers() {
3.    client = getClient("http://localhost:9200");
4.    if (client == null) {
5.      container = new ElasticsearchContainer(
6.          DockerImageName.parse("docker.elastic.co/elasticsearch/elasticsearch")
7.                  .withTag("7.17.16"))
8.          .withPassword("changeme");
9.      container.start();
10.      client = getClient(container.getHttpHostAddress());
11.      assumeNotNull(client);
12.    }
13.  }

为了构建客户端(RestHighLevelClient),我们使用:

java 复制代码
1.  static private RestHighLevelClient getClient(String elasticsearchServiceAddress) {
2.    try {
3.      final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
4.      credentialsProvider.setCredentials(AuthScope.ANY,
5.          new UsernamePasswordCredentials("elastic", "changeme"));

7.      // Create the low-level client
8.      RestClientBuilder restClient = RestClient.builder(HttpHost.create(elasticsearchServiceAddress))
9.          .setHttpClientConfigCallback(hcb -> hcb.setDefaultCredentialsProvider(credentialsProvider));

11.      // Create the high-level client
12.      RestHighLevelClient client = new RestHighLevelClient(restClient);

14.      MainResponse info = client.info(RequestOptions.DEFAULT);
15.      logger.info("Connected to a cluster running version {} at {}.", info.getVersion().getNumber(), elasticsearchServiceAddress);
16.      return client;
17.    } catch (Exception e) {
18.      logger.info("No cluster is running yet at {}.", elasticsearchServiceAddress);
19.      return null;
20.    }
21.  }

你可能已经注意到,我们正在尝试调用 GET / 端点来确保客户端在开始测试之前确实已连接:

ini 复制代码
MainResponse info = client.info(RequestOptions.DEFAULT);

然后,我们可以开始运行测试,如下例所示:

less 复制代码
1.  @Test
2.  void searchData() throws IOException {
3.    try {
4.      // Delete the index if exist
5.      client.indices().delete(new DeleteIndexRequest("search-data"), RequestOptions.DEFAULT);
6.    } catch (ElasticsearchStatusException ignored) { }
7.    // Index a document
8.    client.index(new IndexRequest("search-data").id("1").source("{\"foo\":\"bar\"}", XContentType.JSON), RequestOptions.DEFAULT);
9.    // Refresh the index
10.    client.indices().refresh(new RefreshRequest("search-data"), RequestOptions.DEFAULT);
11.    // Search for documents
12.    SearchResponse response = client.search(new SearchRequest("search-data").source(
13.        new SearchSourceBuilder().query(
14.            QueryBuilders.matchQuery("foo", "bar")
15.        )
16.    ), RequestOptions.DEFAULT);
17.    logger.info("response.getHits().totalHits = {}", response.getHits().getTotalHits().value);
18.  }

所以如果我们想将此代码升级到 8.11.3,我们需要:

  • 使用相同的 7.17.16 版本将代码升级到新的 Elasticsearch Java API Client
  • 将服务器和客户端都升级到 8.11.3

另一个非常好的策略是先升级服务器,然后升级客户端。 它要求你设置 HLRC 的兼容模式:

scss 复制代码
1.  RestHighLevelClient esClient = new RestHighLevelClientBuilder(restClient)
2.      .setApiCompatibilityMode(true)
3.      .build()

我选择分两步进行,以便我们更好地控制升级过程并避免混合问题。 升级的第一步是最大的一步。 第二个要轻得多,主要区别在于 Elasticsearch 现在默认受到保护(密码和 SSL 自签名证书)。

在本文的其余部分中,我有时会将 "old" Java 代码作为注释,以便你可以轻松比较最重要部分的更改。

新的 Elasticsearch Java API 客户端

所以我们需要修改 pom.xml:

xml 复制代码
1.  <!-- Elasticsearch HLRC -->
2.  <dependency>
3.    <groupId>org.elasticsearch.client</groupId>
4.    <artifactId>elasticsearch-rest-high-level-client</artifactId>
5.    <version>7.17.16</version>
6.  </dependency>

到:

xml 复制代码
1.  <!-- Elasticsearch Java API Client -->
2.  <dependency>
3.    <groupId>co.elastic.clients</groupId>
4.    <artifactId>elasticsearch-java</artifactId>
5.    <version>7.17.16</version>
6.  </dependency>

容易,对吧?

嗯,没那么容易。 。 。 因为现在我们的项目不再编译了。 因此,让我们进行必要的调整。 首先,我们需要更改创建 ElasticsearchClient 而不是 RestHighLevelClient 的方式:

java 复制代码
1.  static private ElasticsearchClient getClient(String elasticsearchServiceAddress) {
2.    try {
3.      final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
4.      credentialsProvider.setCredentials(AuthScope.ANY,
5.          new UsernamePasswordCredentials("elastic", "changeme"));

7.      // Create the low-level client
8.      // Before:
9.      // RestClientBuilder restClient = RestClient.builder(HttpHost.create(elasticsearchServiceAddress))
10.      //     .setHttpClientConfigCallback(hcb -> hcb.setDefaultCredentialsProvider(credentialsProvider));
11.      // After:
12.      RestClient restClient = RestClient.builder(HttpHost.create(elasticsearchServiceAddress))
13.          .setHttpClientConfigCallback(hcb -> hcb.setDefaultCredentialsProvider(credentialsProvider))
14.          .build();

16.      // Create the transport with a Jackson mapper
17.      ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());

19.      // And create the API client
20.      // Before:
21.      // RestHighLevelClient client = new RestHighLevelClient(restClient);
22.      // After:
23.      ElasticsearchClient client = new ElasticsearchClient(transport);

25.      // Before:
26.      // MainResponse info = client.info(RequestOptions.DEFAULT);
27.      // After:
28.      InfoResponse info = client.info();

30.      // Before:
31.      // logger.info("Connected to a cluster running version {} at {}.", info.getVersion().getNumber(), elasticsearchServiceAddress);
32.      // After:
33.      logger.info("Connected to a cluster running version {} at {}.", info.version().number(), elasticsearchServiceAddress);
34.      return client;
35.    } catch (Exception e) {
36.      logger.info("No cluster is running yet at {}.", elasticsearchServiceAddress);
37.      return null;
38.    }
39.  }

主要的变化是我们现在在 RestClient(低级别)和 ElasticsearchClient 之间有一个 ElasticsearchTransport 类。 此类负责 JSON 编码和解码。 这包括应用程序类的序列化和反序列化,以前必须手动完成,现在由 JacksonJsonpMapper 处理。

另请注意,请求选项是在客户端上设置的。 我们不再需要通过任何 API 来传递 RequestOptions.DEFAULT,这里是 info API (GET /):

ini 复制代码
InfoResponse info = client.info();

"getters" 也被简化了很多。 因此,我们现在调用 info.version().number(),而不是调用 info.getVersion().getNumber()。 不再需要获取前缀!

使用新客户端

让我们将之前看到的 searchData() 方法切换到新客户端。 现在删除索引是:

css 复制代码
1.  try {
2.      // Before:
3.      // client.indices().delete(new DeleteIndexRequest("search-data"), RequestOptions.DEFAULT);
4.      // After:
5.      client.indices().delete(dir -> dir.index("search-data"));
6.  } catch (/* ElasticsearchStatusException */ ElasticsearchException ignored) { }

在这段代码中我们可以看到什么?

  • 我们现在大量使用 lambda 表达式,它采用构建器对象作为参数。 它需要在思想上切换到这种新的设计模式。 但这实际上是超级智能的,就像你的 IDE 一样,你只需要自动完成即可准确查看选项,而无需导入任何类或只需提前知道类名称。 经过一些练习,它成为使用客户端的超级优雅的方式。 如果你更喜欢使用构建器对象,它们仍然可用,因为这是这些 lambda 表达式在幕后使用的内容。 但是,它使代码变得更加冗长,因此你确实应该尝试使用 lambda。
  • dir 在这里是删除索引请求构建器。 我们只需要使用 index("search-data") 定义我们想要删除的索引。
  • ElasticsearchStatusException 更改为 ElasticsearchException。

要索引单个 JSON 文档,我们现在执行以下操作:

css 复制代码
1.  // Before:
2.  // client.index(new IndexRequest("search-data").id("1").source("{\"foo\":\"bar\"}", XContentType.JSON), RequestOptions.DEFAULT);
3.  // After:
4.  client.index(ir -> ir.index("search-data").id("1").withJson(new StringReader("{\"foo\":\"bar\"}")));

与我们之前看到的一样,lambdas (ir) 的使用正在帮助我们创建索引请求。 这里我们只需要定义索引名称 (index("search-data")) 和 id (id("1")) 并使用 withJson(new StringReader("{"foo":\ "bar"}"))。

refresh API 调用现在非常简单:

css 复制代码
1.  // Before:
2.  // client.indices().refresh(new RefreshRequest("search-data"), RequestOptions.DEFAULT);
3.  // After:
4.  client.indices().refresh(rr -> rr.index("search-data"));

搜索是另一场野兽。 一开始看起来很复杂,但通过一些实践你会发现生成代码是多么容易:

css 复制代码
1.  // Before:
2.  // SearchResponse response = client.search(new SearchRequest("search-data").source(
3.  //   new SearchSourceBuilder().query(
4.  //     QueryBuilders.matchQuery("foo", "bar")
5.  //   )
6.  // ), RequestOptions.DEFAULT);
7.  // After:
8.  SearchResponse<Void> response = client.search(sr -> sr
9.      .index("search-data")
10.      .query(q -> q
11.        .match(mq -> mq
12.          .field("foo")
13.            .query("bar"))),
14.    Void.class);

lambda 表达式参数是构建器:

  • sr 是 SearchRequest 构建器。
  • q 是查询构建器。
  • mq 是 MatchQuery 构建器。

如果你仔细查看代码,你可能会发现它非常接近我们所知的 json 搜索请求:

markdown 复制代码
1.  {
2.    "query": {
3.      "match": {
4.        "foo": {
5.          "query": "bar"
6.        }
7.      }
8.    }
9.  }

这实际上是我一步步编码的方式:

kotlin 复制代码
client.search(sr -> sr, Void.class);

我将 Void 定义为我想要返回的 bean,这意味着我不关心解码 _source JSON 字段,因为我只想访问响应对象。

然后我想定义要在其中搜索数据的索引:

kotlin 复制代码
client.search(sr -> sr.index("search-data"), Void.class);

因为我想提供一个查询,所以我基本上是这样写的:

markdown 复制代码
1.  client.search(sr -> sr
2.      .index("search-data")
3.      .query(q -> q),
4.    Void.class);

我的 IDE 现在可以帮助我找到我想要使用的查询:

我想使用匹配查询:

markdown 复制代码
1.  client.search(sr -> sr
2.      .index("search-data")
3.      .query(q -> q
4.        .match(mq -> mq)),
5.    Void.class);

我只需定义要搜索的 field (foo) 和要应用的 query (bar):

less 复制代码
1.  client.search(sr -> sr
2.      .index("search-data")
3.      .query(q -> q
4.        .match(mq -> mq
5.          .field("foo")
6.            .query("bar"))),
7.    Void.class);

我现在可以要求 IDE 从结果中生成一个字段,并且我可以进行完整的调用:

less 复制代码
1.  SearchResponse<Void> response = client.search(sr -> sr
2.      .index("search-data")
3.      .query(q -> q
4.        .match(mq -> mq
5.          .field("foo")
6.            .query("bar"))),
7.    Void.class);

我可以从响应对象中读取 hits 总数:

css 复制代码
1.  // Before:
2.  // logger.info("response.getHits().totalHits = {}", response.getHits().getTotalHits().value);
3.  // After:
4.  logger.info("response.hits.total.value = {}", response.hits().total().value());

Exists API

让我们看看如何将调用切换到 exists API:

arduino 复制代码
1.  // Before:
2.  boolean exists1 = client.exists(new GetRequest("test", "1"), RequestOptions.DEFAULT);
3.  boolean exists2 = client.exists(new GetRequest("test", "2"), RequestOptions.DEFAULT);

现在可以变成:

ini 复制代码
1.  // After:
2.  boolean exists1 = client.exists(gr -> gr.index("exist").id("1")).value();
3.  boolean exists2 = client.exists(gr -> gr.index("exist").id("2")).value();

Bulk API

要批量对 Elasticsearch 进行索引/删除/更新操作,你绝对应该使用 Bulk API:

less 复制代码
1.  BinaryData data = BinaryData.of("{\"foo\":\"bar\"}".getBytes(StandardCharsets.UTF_8), ContentType.APPLICATION_JSON);
2.  BulkResponse response = client.bulk(br -> {
3.    br.index("bulk");
4.    for (int i = 0; i < 1000; i++) {
5.      br.operations(o -> o.index(ir -> ir.document(data)));
6.    }
7.    return br;
8.  });
9.  logger.info("bulk executed in {} ms {} errors", response.errors() ? "with" : "without", response.ingestTook());
10.  if (response.errors()) {
11.    response.items().stream().filter(p -> p.error() != null)
12.        .forEach(item -> logger.error("Error {} for id {}", item.error().reason(), item.id()));
13.  }

请注意,该操作也可以是 DeleteRequest:

less 复制代码
br.operations(o -> o.delete(dr -> dr.id("1")));

BulkProcessor 到 BulkIngester 助手

我一直很喜欢的 HLRC 功能之一是 BulkProcessor。 它就像 "一劳永逸 "的功能,当你想要使用批量(bulk API)发送大量文档时,该功能非常有用。

正如我们之前所看到的,我们需要手动等待数组被填充,然后准备批量请求。

有了BulkProcessor,事情就容易多了。 你只需添加索引/删除/更新操作,BulkProcessor 将在你达到阈值时自动创建批量请求:

  • 文件数量
  • 全局有效载荷的大小
  • 给定的时间范围
java 复制代码
1.  // Before:
2.  BulkProcessor bulkProcessor = BulkProcessor.builder(
3.      (request, bulkListener) -> client.bulkAsync(request, RequestOptions.DEFAULT, bulkListener),
4.      new BulkProcessor.Listener() {
5.        @Override public void beforeBulk(long executionId, BulkRequest request) {
6.          logger.debug("going to execute bulk of {} requests", request.numberOfActions());
7.        }
8.        @Override public void afterBulk(long executionId, BulkRequest request, BulkResponse response) { 
9.          logger.debug("bulk executed {} failures", response.hasFailures() ? "with" : "without");
10.        }
11.        @Override public void afterBulk(long executionId, BulkRequest request, Throwable failure) { 
12.          logger.warn("error while executing bulk", failure);
13.        }
14.      })
15.      .setBulkActions(10)
16.      .setBulkSize(new ByteSizeValue(1L, ByteSizeUnit.MB))
17.      .setFlushInterval(TimeValue.timeValueSeconds(5L))
18.      .build();

让我们将该部分移至新的 BulkIngester 以注入我们的 Person 对象:

css 复制代码
1.  // After:
2.  BulkIngester<Person> ingester = BulkIngester.of(b -> b
3.    .client(client)
4.    .maxOperations(10_000)
5.    .maxSize(1_000_000)
6.    .flushInterval(5, TimeUnit.SECONDS));

更具可读性,对吧? 这里的要点之一是你不再被迫提供 listener,尽管我相信这仍然是正确处理错误的良好实践。 如果你想提供一个 listener,只需执行以下操作:

java 复制代码
1.  // After:
2.  BulkIngester<Person> ingester = BulkIngester.of(b -> b
3.    .client(client)
4.    .maxOperations(10_000)
5.    .maxSize(1_000_000)
6.    .flushInterval(5, TimeUnit.SECONDS))
7.    .listener(new BulkListener<Person>() {
8.        @Override public void beforeBulk(long executionId, BulkRequest request, List<Person> persons) {
9.            logger.debug("going to execute bulk of {} requests", request.operations().size());
10.        }
11.        @Override public void afterBulk(long executionId, BulkRequest request, List<Person> persons, BulkResponse response) {
12.            logger.debug("bulk executed {} errors", response.errors() ? "with" : "without");
13.        }
14.        @Override public void afterBulk(long executionId, BulkRequest request, List<Person> persons, Throwable failure) {
15.            logger.warn("error while executing bulk", failure);
16.        }
17.    });

每当你需要在代码中添加一些请求到 BulkProcessor 时:

javascript 复制代码
1.  // Before:
2.  void index(Person person) {
3.    String json = mapper.writeValueAsString(person);
4.    bulkProcessor.add(new IndexRequest("bulk").source(json, XContentType.JSON));
5.  }

现在变成了:

markdown 复制代码
1.  // After:
2.  void index(Person person) {
3.    ingester.add(bo -> bo.index(io -> io
4.      .index("bulk")
5.      .document(person)));
6.  }

如果你想发送原始 json 字符串,你应该使用 Void 类型这样做:

ini 复制代码
BulkIngester<Void> ingester = BulkIngester.of(b -> b.client(client).maxOperations(10));
javascript 复制代码
1.  void index(String json) {
2.    BinaryData data = BinaryData.of(json.getBytes(StandardCharsets.UTF_8), ContentType.APPLICATION_JSON);
3.    ingester.add(bo -> bo.index(io -> io.index("bulk").document(data)));
4.  }

当你的应用程序退出时,你需要确保关闭 BulkProcessor,这将导致挂起的操作之前被刷新,这样你就不会丢失任何文档:

css 复制代码
1.  // Before:
2.  bulkProcessor.close();

现在很容易转换成:

css 复制代码
1.  // After:
2.  ingester.close();

当然,当使用 try-with-resources 模式时,你可以省略 close() 调用,因为 BulkIngester 是 AutoCloseable 的:

less 复制代码
1.  try (BulkIngester<Void> ingester = BulkIngester.of(b -> b
2.    .client(client)
3.    .maxOperations(10_000)
4.    .maxSize(1_000_000)
5.    .flushInterval(5, TimeUnit.SECONDS)
6.  )) {
7.      BinaryData data = BinaryData.of("{\"foo\":\"bar\"}".getBytes(StandardCharsets.UTF_8), ContentType.APPLICATION_JSON);
8.      for (int i = 0; i < 1000; i++) {
9.          ingester.add(bo -> bo.index(io -> io.index("bulk").document(data)));
10.      }
11.  }

好处

我们已经在 BulkIngester 部分中触及了这一点,但新 Java API 客户端添加的重要功能之一是你现在可以提供 Java Bean,而不是手动执行序列化/反序列化。 这在编码方面可以节省时间。

因此,要索引 Person 对象,我们可以这样做:

less 复制代码
1.  void index(Person person) {
2.    client.index(ir -> ir.index("person").id(person.getId()).document(person));
3.  }

以我的愚见,力量来自于搜索。 我们现在可以直接读取我们的实体:

less 复制代码
1.  client.search(sr -> sr.index("search-data"), Person.class);
2.  SearchResponse<Person> response = client.search(sr -> sr.index("search-data"), Person.class);
3.  for (Hit<Person> hit : response.hits().hits()) {
4.    logger.info("Person _id = {}, id = {}, name = {}", 
5.      hit.id(),                 // Elasticsearch _id metadata
6.      hit.source().getId(),     // Person id
7.      hit.source().getName());  // Person name
8.  }

这里的 source() 方法可以直接访问 Person 实例。 你不再需要自己反序列化 json _source 字段。

更多阅读:

原文:Switching from the Java High Level Rest Client to the new Java API Client | Elastic Blog

相关推荐
alfiy1 小时前
Elasticsearch学习笔记(六)使用集群令牌将新加点加入集群
笔记·学习·elasticsearch
帅气的人1231 小时前
使用 docker-compose 启动 es 集群 + kibana
elasticsearch·docker
漫无目的行走的月亮2 小时前
比较Elasticsearch和Hadoop
hadoop·elasticsearch
hengzhepa10 小时前
ElasticSearch备考 -- Async search
大数据·学习·elasticsearch·搜索引擎·es
bubble小拾17 小时前
ElasticSearch高级功能详解与读写性能调优
大数据·elasticsearch·搜索引擎
不能放弃治疗18 小时前
重生之我们在ES顶端相遇第 18 章 - Script 使用(进阶)
elasticsearch
hengzhepa19 小时前
ElasticSearch备考 -- Search across cluster
学习·elasticsearch·搜索引擎·全文检索·es
Elastic 中国社区官方博客21 小时前
Elasticsearch:使用 LLM 实现传统搜索自动化
大数据·人工智能·elasticsearch·搜索引擎·ai·自动化·全文检索
慕雪华年1 天前
【WSL】wsl中ubuntu无法通过useradd添加用户
linux·ubuntu·elasticsearch
Elastic 中国社区官方博客1 天前
使用 Vertex AI Gemini 模型和 Elasticsearch Playground 快速创建 RAG 应用程序
大数据·人工智能·elasticsearch·搜索引擎·全文检索