java怎么查询es数据

1047
2023/9/21 15:34:37
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

要查询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数据的基本示例。您可以根据自己的需求进行进一步的查询和结果处理。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: 使用java mail发邮件报错怎么解决