admin管理员组

文章数量:1530019

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

前提条件

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

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

代码

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

IndexOperations.java

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.mapping.TypeMapping;
import co.elastic.clients.elasticsearch.indices.CreateIndexRequest;
import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
import co.elastic.clients.json.JsonpMapper;
import jakarta.json.Json;
import jakarta.json.stream.JsonParser;

import java.io.IOException;
import java.io.StringReader;

public class IndexOperations {
    private final ElasticsearchClient client;
    public IndexOperations(ElasticsearchClient client)
        { this.client = client; }

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

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

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

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

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

    // Create an index with mappings defined
    public void putMapping(String index, String mappings) throws IOException {
        JsonpMapper mapper = client._transport().jsonpMapper();
        JsonParser parser = Json.createParser(new StringReader(mappings));
        CreateIndexRequest request_create =  new CreateIndexRequest.Builder()
                .index(index)
                .mappings(TypeMapping._DESERIALIZER.deserialize(parser, mapper))
                .build();
        CreateIndexResponse response_create = client.indices().create(request_create);
    }
}

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

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

ElasticsearchJava.java

       try {
            makeConnection_truststore();
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }

        IndexOperations io = new IndexOperations(client);

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

        io.createIndex(INDEX_NAME);
        Thread.sleep(1000);
        io.closeIndex(INDEX_NAME);
        io.openIndex(INDEX_NAME);
        io.deleteIndex(INDEX_NAME);

        String mappings = "{\n" +
                "  \"properties\" : {\n" +
                "    \"id\" : {\n" +
                "      \"type\" : \"keyword\" \n" +
                "    },\n"+
                "    \"name\" : {\n" +
                "      \"type\" : \"text\",\n" +
                "      \"fields\" : {\n" +
                "        \"keyword\" : {\n" +
                "          \"type\" : \"keyword\",\n" +
                "          \"ignore_above\" : 256 \n" +
                "        }\n" +
                "      } \n" +
                "    }, \n" +
                "    \"price\" : { \n" +
                "      \"type\" : \"long\" \n" +
                "     } \n" +
                "  }\n" +
                "}\n";

        io.putMapping("test1", mappings);

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

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

GET test1/_mapping

上面的命令显示:

{
  "test1": {
    "mappings": {
      "properties": {
        "id": {
          "type": "keyword"
        },
        "name": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        },
        "price": {
          "type": "long"
        }
      }
    }
  }
}

本文标签: 客户端索引JavaElasticsearchStack