java实现Elasticsearch跳页查询
时间: 2023-10-05 19:04:41 浏览: 107
elasticsearch聚合后分页
4星 · 用户满意度95%
1. 首先,需要在Java项目中引入Elasticsearch的Java API依赖:
```
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.12.0</version>
</dependency>
```
2. 创建Elasticsearch客户端连接:
```
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http")));
```
3. 创建查询请求:
```
SearchRequest searchRequest = new SearchRequest("index_name");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.from(pageNumber * pageSize);
sourceBuilder.size(pageSize);
sourceBuilder.query(QueryBuilders.matchAllQuery());
searchRequest.source(sourceBuilder);
```
其中,`pageNumber`为要查询的页码,`pageSize`为每页的大小。
4. 执行查询请求:
```
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
```
5. 处理查询结果:
```
SearchHits hits = searchResponse.getHits();
for (SearchHit hit : hits) {
// 处理查询结果
}
```
完整代码示例:
```
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http")));
int pageNumber = 1;
int pageSize = 10;
SearchRequest searchRequest = new SearchRequest("index_name");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.from(pageNumber * pageSize);
sourceBuilder.size(pageSize);
sourceBuilder.query(QueryBuilders.matchAllQuery());
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = searchResponse.getHits();
for (SearchHit hit : hits) {
// 处理查询结果
}
client.close();
```
阅读全文