Java

java怎么查询es数据

小亿
182
2023-09-14 15:34:37
栏目: 编程语言

要查询Elasticsearch(ES)数据,您可以使用Java的Elasticsearch REST客户端或Java的Elasticsearch高级客户端。

使用Elasticsearch REST客户端:

  1. 添加Elasticsearch REST客户端的依赖。例如,使用Maven添加以下依赖:
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>7.12.1</version>
</dependency>
  1. 创建Elasticsearch REST客户端实例:
RestClient restClient = RestClient.builder(
new HttpHost("localhost", 9200, "http")).build();
  1. 创建一个搜索请求并执行查询:
Request request = new Request("GET", "/your-index/_search");
request.setJsonEntity("{\"query\": {\"match_all\": {}}}");
Response response = restClient.performRequest(request);
  1. 处理查询结果:
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println(responseBody);

使用Elasticsearch高级客户端:

  1. 添加Elasticsearch高级客户端的依赖。例如,使用Maven添加以下依赖:
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.12.1</version>
</dependency>
  1. 创建Elasticsearch高级客户端实例:
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
  1. 创建一个搜索请求并执行查询:
SearchRequest searchRequest = new SearchRequest("your-index");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
  1. 处理查询结果:
SearchHit[] hits = searchResponse.getHits().getHits();
for (SearchHit hit : hits) {
String sourceAsString = hit.getSourceAsString();
System.out.println(sourceAsString);
}

这是查询ES数据的基本示例。您可以根据自己的需求进行进一步的查询和结果处理。

0
看了该问题的人还看了