用
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
