Spring-Data-Elasticsearch查询数据量过大报错,Result window is too large,使用Scroll API解决

网上关于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());
   }

运行结果
在这里插入图片描述

Over~

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值