面试题答案
一键面试使用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)
- 引入依赖:
<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>
- 代码示例:
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
请求获取所有索引(通过通配符*
),最后遍历响应获取每个索引的名称和设置信息。