elasticsearch实战---分页查询问题(完美解决)

8,342 阅读2分钟

0.背景

公司系统为偏后台系统,展示效果多为列表展示,列表展示中大数据量的展示多使用分页进行查询。

elasticsearch版本:6.3.2

java client版本:rest-high-level-client 6.3.2

问题:1.9W+数据分页查询后,查询结果总条数没有问题(即为1.9W+),当查看后几页数据时,发现没有数据并后台报错。

截图如下:

图1 总条数为19521条,共1953页

图2 转到最后一页,没有数据,后台报错

后台错误信息如下:

{"error":{"root_cause":[{"type":"query_phase_execution_exception","reason":"Result window is
too large, from + size must be less than or equal to: [10000] but was [19530]. 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 setting."}],"type":"search_phase_execution_exception",
"reason":"all shards
failed","phase":"query","grouped":true,
"failed_shards":[{"shard":0,"index":"dragon-dev","node":"ln1Y4mW3S2mHDpqMBrcURQ","reason":{"type":"query_phase_execution_exception",
"reason":"Result window is too large, from + size must be less than or equal to: [10000] but was [19530]. 
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 setting."}}]},"status":500}

1.解决方案

在上述后台错误信息中可以清楚的看到错误原因:

Result window is too large, from + size must be less than or equal to: [10000] but was [19530]:意思为查询的结果总数太大为19530,大于了10000的限制。

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 setting:提供了解决方案,意思为查看scroll的方法解决大数据量请求,也可以通过修改index.max_result_window参数改变限制的大小。

本文主要通过修改index.max_result_window参数快速解决问题。

2.说干就干

在elasticsearch系列的博客中提到,es分页是通过将from+size数量的数据加载到内存中,即我点击1953页,每页展示10条,es就会将19530条数据放入内存。弊端清晰可见,如果数据量过大将会十分占用内存,因此es默认限制了分页查询的最大数量为10000条

如何修改分页查询最大数即index.max_result_window参数?

其实非常简单,在setting中配置即可。(可以在创建索引时设置,也可以在索引建立完毕之后设置)

PUT /索引名称/_settings
{ "index" : { "max_result_window" : 10000000}}

操作上述脚本,将最大展示数量改为1000W条。

3.总结

由于es分页查询的限制导致数据不能展示的问题,可以通过修改配置参数,或者使用scroll api的方式(推荐)进行解决。本文就不探讨如何使用scroll api进行改进,可以自行查阅官网示例。祝君好运。