Elasticsearch 中查询结果分页实现的java代码
时间: 2024-01-14 10:42:41 浏览: 88
Java实现分页查询
在 Elasticsearch 中,分页查询可以通过设置 `from` 和 `size` 参数来实现。具体实现步骤如下:
1. 创建 Elasticsearch 客户端和搜索请求对象 `SearchRequest`。
```java
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
SearchRequest searchRequest = new SearchRequest("index_name");
```
2. 设置查询条件和分页参数。
```java
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchQuery("field_name", "search_text"));
searchSourceBuilder.from(0);
searchSourceBuilder.size(10);
searchRequest.source(searchSourceBuilder);
```
上述代码中,`from` 参数表示结果集的起始位置,`size` 参数表示每页显示的结果数。
3. 执行搜索请求并处理结果。
```java
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = searchResponse.getHits();
SearchHit[] searchHits = hits.getHits();
for (SearchHit hit : searchHits) {
// 处理每个搜索结果
}
client.close();
```
完整代码示例:
```java
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
SearchRequest searchRequest = new SearchRequest("index_name");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchQuery("field_name", "search_text"));
searchSourceBuilder.from(0);
searchSourceBuilder.size(10);
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = searchResponse.getHits();
SearchHit[] searchHits = hits.getHits();
for (SearchHit hit : searchHits) {
// 处理每个搜索结果
}
client.close();
```
阅读全文