用
from + size翻到很后面,报result window is too large。根因是from + size的和不能超过index.max_result_window(默认 10000)——这是from/size深度分页的硬上限;要翻到 10000 条之后,得改用search_after或scroll。
Issue & Env(案发现场与环境)
- 业务场景:搜索结果要翻到第 5000 页(size=20,from=99980),
from + size超过 10000,直接报错。 - 环境:OpenSearch 3.x(Docker latest),索引
movies。 - 关键区分:
from/size适合浅分页(前 10000 条内);超过就要换search_after。
StackTrace(报错原文)
{
"error" : {
"type" : "search_phase_execution_exception",
"reason" : "Result window is too large, from + size must be less than or equal to: [10000] but was [10020]. See the scroll api for a more efficient way to request large data sets."
}
}
Reproduce(复现代码)
# from + size = 10020 > 10000 → 报错
curl -sk -u admin:Devfix@2026 -X GET "https://localhost:9200/movies/_search?pretty" \
-H "Content-Type: application/json" \
-d '{ "from": 10000, "size": 20 }'
判定标准:返回 from + size must be less than or equal to: [10000] 错误。
Root Cause(根因分析)
from/size 的深度分页有硬上限
index.max_result_window(默认 10000)限制了 from + size 的最大值。原因在于 from/size 的实现:它要从每个分片里取出 from + size 条、再合并排序、最后丢弃前面的 from 条。from 越大,每个分片要临时加载、排序的文档越多,内存和 CPU 代价线性飙升。10000 是引擎默认的安全线,防「翻第 10 万页」这种操作拖垮集群。
突破上限靠 search_after / scroll
官方推荐:实时用户翻页用 search_after(游标式,不受 10000 限制),全量导出用 scroll。两者都不靠「跳过前 N 条」的实现,所以没有这个上限。
The Fix(解决方案)
第一步:深翻页改用 search_after
先排序,再用上一页最后一条的 sort 值做游标:
# 第一页
curl -sk -u admin:Devfix@2026 -X GET "https://localhost:9200/movies/_search?pretty" \
-H "Content-Type: application/json" \
-d '{ "size": 20, "sort": [ { "year": "asc" }, { "id": "asc" } ] }'
# 下一页:search_after 用上一页最后一条的 sort 值
curl -sk -u admin:Devfix@2026 -X GET "https://localhost:9200/movies/_search?pretty" \
-H "Content-Type: application/json" \
-d '{ "size": 20, "sort": [ { "year": "asc" }, { "id": "asc" } ], "search_after": [ 2015, "5" ] }'
第二步:调大上限(不推荐,治标不治本)
真要暂时放宽,可改索引设置,但代价是深翻页越来越慢:
curl -sk -u admin:Devfix@2026 -X PUT "https://localhost:9200/movies/_settings?pretty" \
-H "Content-Type: application/json" \
-d '{ "index.max_result_window": 50000 }'
注意事项
- 调大
max_result_window是治标,深翻页内存/CPU 会随from线性涨。 search_after只能一页页前进,不能跳页。- 完整用法见 从零跑通 OpenSearch 深分页。
References(参考来源)
- Paginate results — OpenSearch 官方文档opensearch-docs
