springBoot集成es使用ElasticsearchTemplate执行滚动查询
使用Elasticsearch查询大量数据时基本的分页查询就会报错,这种情况下可以使用scroll(滚动)查询
直接上代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
queryBuilder.must(QueryBuilders.termQuery("status", 1)); 假设查询状态为1的
SearchQuery searchQuery = new NativeSearchQueryBuilder() .withIndices("test_index") .withTypes("test") .withQuery(queryBuilder) .withPageable(PageRequest.of(0, 1000)) .build();
ScrolledPage<TestEntity> scroll = (ScrolledPage<TestEntity>) elasticsearchTemplate.startScroll(3000, searchQuery, TestEntity.class);
while (scroll.hasContent()) { List<TestEntity> content = scroll.getContent(); scroll = (ScrolledPage<TestEntity>) elasticsearchTemplate.continueScroll(scroll.getScrollId(), 3000, EstateInfoEntity.class); }
elasticsearchTemplate.clearScroll(scroll.getScrollId());
|