其他分享
首页 > 其他分享> > ElasticSearch中通过Scroll查询所有数据

ElasticSearch中通过Scroll查询所有数据

作者:互联网

ElasticSearch中通过Scroll查询所有数据

SearchRequest request = new SearchRequest(index);
//设置超时时间
request.scroll(TimeValue.timeValueMillis(1L));
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//单次查询的量
sourceBuilder.size(1000);
request.source(sourceBuilder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
String scrollId = response.getScrollId();
for (SearchHit hit : response.getHits().getHits()) {
    System.out.println(hit.getSourceAsString());
}

while (true) {
    SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId);
    scrollRequest.scroll(TimeValue.timeValueMillis(1L));
    SearchResponse scrollResponse = client.scroll(scrollRequest, RequestOptions.DEFAULT);
    SearchHit[] hits = scrollResponse.getHits().getHits();
    if (hits != null && hits.length > 0) {
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsString());
        }
    }else {
        break;
    }
}

ClearScrollRequest scrollRequest = new ClearScrollRequest();
scrollRequest.addScrollId(scrollId);
ClearScrollResponse scrollResponse = client.clearScroll(scrollRequest, RequestOptions.DEFAULT);
System.out.println(scrollResponse.status());

标签:hits,hit,getHits,查询,scrollResponse,ElasticSearch,new,Scroll,scrollRequest
来源: https://www.cnblogs.com/pinked/p/13936893.html