封装类:传参1 esClient 传参2 自定义searchSourceBuilder 传参3 索引名(可直接复制粘贴使用)
public static List<Map<String, Object>> getEsResultData(RestHighLevelClient esClient, SearchSourceBuilder searchSourceBuilder, String index_name) throws IOException {
// 1、创建searchRequest
SearchRequest searchRequest = new SearchRequest(index_name);
// 2、指定scroll信息
searchRequest.scroll(TimeValue.timeValueMinutes(5L));
// 开始查询数据
searchRequest.source(searchSourceBuilder);
//4、获取返回结果scrollId,source
SearchResponse searchResponse = esClient.search(searchRequest, RequestOptions.DEFAULT); //通过发送初始搜索请求来初始化搜索上下文
String scrollId = searchResponse.getScrollId();
SearchHit[] searchHits = searchResponse.getHits().getHits();
List<Map<String, Object>> result = new ArrayList<>();
for (SearchHit hit : searchHits) {
result.add(hit.getSourceAsMap());
}
// 查询出来之后我们要获取他的id
// 然后利用他的id去查询他的下一页
while (searchHits.length > 0) {
//5、循环 - 创建 SearchScrollRequest 创建一个新的搜索滚动请求,保存最后返回的滚动标识符和滚动间隔
// 获取 scrollId 去查询下一页
SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId);
//6、指定scrollId的生存时间
scrollRequest.scroll(TimeValue.timeValueMinutes(1L));
//7、执行查询获取返回结果
SearchResponse scrollResp = esClient.scroll(scrollRequest, RequestOptions.DEFAULT);
//8、判断是否查询到了数据,输出
SearchHit[] hits = scrollResp.getHits().getHits();
//循环输出下一页
if (hits != null && hits.length > 0) {
for (SearchHit hit : hits) {
result.add(hit.getSourceAsMap());
}
} else {
//9、判断没有查询到数据,退出循环
break;
}
}
//查完之后我们把存进缓存的id给删除 完成滚动后,清除滚动上下文
//10、创建ClearScrollRequest
ClearScrollRequest clearScrollRequest = new ClearScrollRequest();
//11、指定scrollId
clearScrollRequest.addScrollId(scrollId);
//12、删除scrollId
esClient.clearScroll(clearScrollRequest, RequestOptions.DEFAULT);
return result;
}
标签:hit,scrollId,自定义,searchRequest,封装,查询,esClient,scroll,es
From: https://blog.csdn.net/m0_64393858/article/details/144064294