MST
星途 面试题库

面试题:ElasticSearch集群索引信息列出方法之基础应用

在ElasticSearch集群中,已知集群健康状态良好,如何使用ElasticSearch的API列出所有索引的名称及其基本设置信息(如索引的分片数、副本数)?请分别说明使用REST API和Java客户端的实现方式。
32.0万 热度难度
数据库ElasticSearch

知识考点

AI 面试

面试题答案

一键面试

使用REST API

通过发送GET请求到/_cat/indices?v端点,可以获取所有索引的简要信息,包括索引名、分片数、副本数等。示例如下:

curl -X GET "localhost:9200/_cat/indices?v"

如果需要更详细的设置信息,可以针对每个索引发送GET请求到/{index_name}/_settings端点。例如,假设索引名为my_index

curl -X GET "localhost:9200/my_index/_settings"

要获取所有索引的详细设置,可以使用通配符*

curl -X GET "localhost:9200/*/_settings"

使用Java客户端(以Elasticsearch 7.x为例,使用High Level REST Client)

  1. 引入依赖:
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.17.0</version>
</dependency>
<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>7.17.0</version>
</dependency>
  1. 代码示例:
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexResponse;
import java.io.IOException;

public class ElasticsearchIndexSettings {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http")));

        GetIndexRequest request = new GetIndexRequest("*");
        GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);

        for (String index : response.getIndices()) {
            System.out.println("Index: " + index);
            System.out.println("Settings: " + response.getSettings(index));
        }

        client.close();
    }
}

上述Java代码通过High Level REST Client获取所有索引及其设置信息。首先创建RestHighLevelClient连接到Elasticsearch集群,然后使用GetIndexRequest请求获取所有索引(通过通配符*),最后遍历响应获取每个索引的名称和设置信息。