Elasticsearch Scroll分页检索案例分享
Elasticsearch Scroll分页检索案例分享
1.准备工作
参考文档《》导入和配置es客户端bboss
2.定义scroll检索dsl
3.Scroll检索代码
public void testScroll(){
ClientInterface clientUtil = ElasticSearchHelper.getConfigRestClientUtil("esmapper/scroll.xml");
//scroll分页检索,将检索结果映射为Map对象,也可以映射为自定义的实体对象
ESDatas<Map> response = clientUtil.searchList("agentstat-*/_search?scroll=1m",
"scrollQuery",//对于dsl脚本名称,在esmapper/scroll.xml文件中配置
Map.class);
List<Map> datas = response.getDatas();//第一页数据
List<String > scrollIds = new ArrayList<>();//用于记录每次scroll的scrollid,便于检索完毕后清除
long totalSize = response.getTotalSize();//总记录数
if(scrollId != null)
scrollIds.add(scrollId);
System.out.println("scrollId:"+scrollId);
if(datas != null && datas.size() > 0) {//每页1000条记录,通过迭代scrollid,遍历scroll分页结果
do {
response = clientUtil.searchScroll("1m",scrollId,Map.class);
scrollId = response.getScrollId();//每页的scrollid
if(scrollId != null)
scrollIds.add(scrollId);
datas = response.getDatas();//每页的纪录数
if(datas == null || datas.size() == 0){
break;
}
//查询并打印存在于es服务器上的scroll上下文信息
String scrolls = clientUtil.executeHttp("_nodes/stats/indices/search", ClientUtil.HTTP_GET);
System.out.println(scrolls);
//清除scroll上下文信息,虽然说超过1分钟后,scrollid会自动失效,
//但是手动删除不用的scrollid,是一个好习惯
if(scrollIds.size() > 0) {
scrolls = clientUtil.deleteScrolls(scrollIds);
System.out.println(scrolls);
}
//清理完毕后查看scroll上下文信息
scrolls = clientUtil.executeHttp("_nodes/stats/indices/search", ClientUtil.HTTP_GET);
4.Scroll案例项目地址和代码文件
项目地址:
https://gitee.com/bboss/elasticsearchdemo/blob/master/src/test/resources/esmapper/scroll.xml