首页 > 解决方案 > 如何使用偏移+限制> 1000的ES查询

问题描述

我为我的客户端公开了一个 API,我使用 ES 来获取特定时间范围的数据。这个数字是记录远远超过 100 万。现在,我必须提供另一个功能,我给他们偏移量和限制,客户端可以从偏移量中获取记录数(限制)。

我的 ES 查询形成如下

{"from":10000,"size":2001,"timeout":"60s","query":{"bool":{"must":[{"terms":{"tollId":["59850"],"boost":1.0}},{"range":{"updatedAt":{"from":"2020-08-15T00:00:00.000Z","to":null,"include_lower":true,"include_upper":true,"boost":1.0}}},{"range":{"updatedAt":{"from":null,"to":"2020-12-15T22:08:21.000Z","include_lower":true,"include_upper":true,"boost":1.0}}}],"adjust_pure_negative":true,"boost":1.0}},"sort":[{"updatedAt":{"order":"desc"}}]}

当我在 Elastic Search 上执行此操作时,我得到

"failed_shards": [
{
  "shard": 0,
  "index": "companydatabase",
  "node": "vQU6NjSVRK6dKNLsWkfqEw",
  "reason": {
  "type": "query_phase_execution_exception",
  "reason": "Result window is too large, from + size must be less than or equal to: [10000] but was [12001]. 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 API 来获取记录,但是当我必须从某个偏移量到某个限制获取记录时,我不能使用 scroll Api。

我错过了什么吗?有没有办法解决这个问题,或者我每次都必须获取所有记录(文档)并过滤结果?

标签: elasticsearch

解决方案


您只需要将索引设置更新max_result_window为更高的设置,默认为10000. 因此,例如,如果您的 from + size 小于 10000 它会正常工作,那么您需要更改max_result_window该索引的任何内容:

curl -XPUT "http://localhost:4200/the_index/_settings" -d '{ "index" : { "max_result_window" : 500000 } }' -H "Content-Type: application/json"

![在此处输入图像描述

显然使用 ES 的滚动 API 将使这个更有效的替代方案来提高它。


推荐阅读