网上关于Spring-Data-Elasticsearch的Scroll API资料有点少,今天我也遇到了这个困难,现在解决了,本着人人为我,我为人人的想法,整理于此,供遇到同样困难的同学参考
Exception[Result window is too large, from + size must be less than or equal to: [10000] but was [58000]. See the scroll api for a more efficient way to request large data sets. This limit can be set by changing the [index.max_result_window] index level parameter.]
可以看出,异常信息提示我们请求大数据量的情况下使用Scroll API。
在网上搜索后,发现博客,总结于此,供参考
参考博客1:springBoot集成es查询,使用ElasticsearchTemplate执行滚动查询
参考博客2:Spring集成elasticSearch,使用elasticTemplate的scroll查询分页拉取全量数据
从这两篇博客可以看出,针对此问题,我们就是使用ElasticsearchTemplate类的 startScroll 方法,它有几个不同的重载,我这里选择最简单的一个。
还有两个方法,一个是continueScroll方法,一个是clearScroll方法。
下面附上我的测试代码,也是参考上面两篇博客里的
@Test
public void testScroll() {
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withIndices("linux_log-2020-03-13")//索引名
.withTypes("_doc")//类型名
.withQuery(QueryBuilders.termQuery("host.hostname", "server45"))//查询条件,这里简单使用term查询
.withPageable(PageRequest.of(3, 10))//从0页开始查,每页10个结果
//.withFields("message")//ES里该index内存的文档,可能存了很多我们不关心的字段,全返回没必要,所以指定有用的字段
.build();
ScrolledPage<LinuxLog> scroll = elasticsearchTemplate.startScroll(3000, searchQuery, LinuxLog.class);
for (LinuxLog dto : scroll) {
System.out.println(dto);
}
System.out.println("查询总命中数:" + scroll.getTotalElements());
/*while (scroll.hasContent()) {
for (LinuxLog dto : scroll.getContent()) {
//Do your work here
System.out.println(dto);
}
//取下一页,scrollId在es服务器上可能会发生变化,需要用最新的。发起continueScroll请求会重新刷新快照保留时间
scroll = elasticsearchTemplate.continueScroll(scroll.getScrollId(), 3000, LinuxLog.class);
}*/
//及时释放es服务器资源
elasticsearchTemplate.clearScroll(scroll.getScrollId());
}
运行结果