用java代码写一个elasticsearch分页查询
时间: 2023-05-28 20:07:05 浏览: 219
以下是Java代码示例:
```java
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import java.util.ArrayList;
import java.util.List;
public class ElasticsearchPageQuery {
public List<String> searchByPage(Client client, String index, String type, int pageNo, int pageSize) {
List<String> results = new ArrayList<>();
SearchResponse response = client.prepareSearch(index).setTypes(type)
.setSource(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()))
.setFrom((pageNo - 1) * pageSize).setSize(pageSize).setScroll(new TimeValue(60000)).get();
SearchHits hits = response.getHits();
long totalHits = hits.getTotalHits();
for (SearchHit hit : hits) {
results.add(hit.getSourceAsString());
}
return results;
}
}
```
此代码使用Elasticsearch Java API执行分页查询。它使用`SearchSourceBuilder`来构建查询,并将结果从响应中提取到一个列表中。分页查询是通过设置`setFrom`和`setSize`来实现的。`setScroll`方法用于保留滚动上下文以便获取更多结果。
阅读全文