Elasticsearch:在 Java 客户端应用中管理索引 - Elastic Stack 8.x

1,386 阅读3分钟

管理索引是客户端应用常用的一些动作,比如我们创建,删除,打开 及关闭索引等操作。在今天的文章中,我将描述如何在 Java 客户端应用中对索引进行管理。

前提条件

我们需要阅读之前的文章 “Elasticsearch:在 Java 客户端中使用 truststore 来创建 HTTPS 连接”。在那篇文章中,我们详述了如何在 Java 客户端应用中和 Elasticsearch 建立连接。在这里就不再累述了。

为了方便大家的阅读,我创建了如下的一个 github 仓库:GitHub - liu-xiao-guo/elasticsearchjava-manage-index

代码

在代码中我创建了如下的一个 class:

IndexOperations.java

`

1.  import co.elastic.clients.elasticsearch.ElasticsearchClient;
2.  import co.elastic.clients.elasticsearch._types.mapping.TypeMapping;
3.  import co.elastic.clients.elasticsearch.indices.CreateIndexRequest;
4.  import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
5.  import co.elastic.clients.json.JsonpMapper;
6.  import jakarta.json.Json;
7.  import jakarta.json.stream.JsonParser;

9.  import java.io.IOException;
10.  import java.io.StringReader;

12.  public class IndexOperations {
13.      private final ElasticsearchClient client;
14.      public IndexOperations(ElasticsearchClient client)
15.          { this.client = client; }

17.      // Check whether an index exists or not
18.      public boolean checkIndexExists(String name) throws IOException {
19.          return client.indices().exists(c -> c.index(name)).value();
20.      }

22.      // Create an index if it does not exist
23.      public void createIndex(String name) throws IOException {
24.          client.indices().create(c -> c.index(name));
25.      }

27.      // Delete an index if it exists
28.      public void deleteIndex(String name) throws IOException {
29.          client.indices().delete(c -> c.index(name));
30.      }

32.      // Close an index
33.      public void closeIndex(String name) throws IOException {
34.          client.indices().close(c -> c.index(name));
35.      }

37.      // Open an index
38.      public void openIndex(String name) throws IOException {
39.          client.indices().open(c -> c.index(name));
40.      }

42.      // Create an index with mappings defined
43.      public void putMapping(String index, String mappings) throws IOException {
44.          JsonpMapper mapper = client._transport().jsonpMapper();
45.          JsonParser parser = Json.createParser(new StringReader(mappings));
46.          CreateIndexRequest request_create =  new CreateIndexRequest.Builder()
47.                  .index(index)
48.                  .mappings(TypeMapping._DESERIALIZER.deserialize(parser, mapper))
49.                  .build();
50.          CreateIndexResponse response_create = client.indices().create(request_create);
51.      }
52.  }

`![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)

通过这个 class 的使用,我们可以对一个索引进行 create,delete,open,close 及检查是否存在。关于使用 mapping 来创建索引,更多的信息可以参考文章 “Elasticsearch:在 Java 应用中创建 mappings,批量写入及更新 - Java client 8.x”。

在代码中,我们需要修改相应的部分创建 ElasticsearchClient 实例。我们使用如下的代码来示例化 IndexOperations:

ElasticsearchJava.java

 1.         try {
2.              makeConnection_truststore();
3.          } catch (CertificateException e) {
4.              e.printStackTrace();
5.          } catch (NoSuchAlgorithmException e) {
6.              e.printStackTrace();
7.          } catch (KeyStoreException e) {
8.              e.printStackTrace();
9.          } catch (KeyManagementException e) {
10.              e.printStackTrace();
11.          }

13.          IndexOperations io = new IndexOperations(client);

我们可以使用如下的代码来对索引的操作进行测试:

 `1.          io.createIndex(INDEX_NAME);
2.          Thread.sleep(1000);
3.          io.closeIndex(INDEX_NAME);
4.          io.openIndex(INDEX_NAME);
5.          io.deleteIndex(INDEX_NAME);

7.          String mappings = "{\n" +
8.                  "  \"properties\" : {\n" +
9.                  "    \"id\" : {\n" +
10.                  "      \"type\" : \"keyword\" \n" +
11.                  "    },\n"+
12.                  "    \"name\" : {\n" +
13.                  "      \"type\" : \"text\",\n" +
14.                  "      \"fields\" : {\n" +
15.                  "        \"keyword\" : {\n" +
16.                  "          \"type\" : \"keyword\",\n" +
17.                  "          \"ignore_above\" : 256 \n" +
18.                  "        }\n" +
19.                  "      } \n" +
20.                  "    }, \n" +
21.                  "    \"price\" : { \n" +
22.                  "      \"type\" : \"long\" \n" +
23.                  "     } \n" +
24.                  "  }\n" +
25.                  "}\n";

27.          io.putMapping("test1", mappings);`![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)

我们在代码中放置了 1 秒的延迟(Thread.wait(1000)) 以防止对索引的快速操作,因为它们的分片分配是异步的,并且它们需要几毫秒才能准备好。 最佳实践是不使用类似的 hack,而是在执行进一步操作之前轮询索引的状态,并且仅在它变为绿色时执行这些操作。

在上面的代码的最后部分,我们使用 io 来创建一个具有 mappings 的索引。执行完后,我们可以使用如下的命令来查看:

GET test1/_mapping

上面的命令显示:

`

1.  {
2.    "test1": {
3.      "mappings": {
4.        "properties": {
5.          "id": {
6.            "type": "keyword"
7.          },
8.          "name": {
9.            "type": "text",
10.            "fields": {
11.              "keyword": {
12.                "type": "keyword",
13.                "ignore_above": 256
14.              }
15.            }
16.          },
17.          "price": {
18.            "type": "long"
19.          }
20.        }
21.      }
22.    }
23.  }

`![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)