什么是使用Elasticsearch进行分页的最佳方法?目前,我正在开发一个使用Python后端和Elasticsearch的API,我的索引没有太多数据,因此我们默认在前端使用JavaScript进行分页(到目前为止,我们没有任何问题)。我想知道对于更大的索引,处理分页的最佳方法是什么:
- 滚动API - 切片滚动 -
- 滚动API - 切片滚动 -
search_after
search_after
from
/size
参数。然而,这种方式只适用于前1万个搜索结果。search_after
。scroll
API。
search_after
不是自由跳转到随机页面的解决方案,而是可以并行滚动多个查询。它与scroll
API非常相似,但与之不同的是,search_after
参数是无状态的,它总是针对搜索器的最新版本进行解析。因此,在遍历过程中,排序顺序可能会根据索引的更新和删除而发生变化。
因此,它将允许您在成本为一些可能的不一致性的情况下分页超过10k。
index.max_result_window
设置为10k作为硬限制,以避免内存不足的情况:
index.max_result_window
用于搜索此索引的
from
+size
的最大值。默认为10000. 搜索请求需要与from
+size
成比例的堆内存和时间,这会限制该内存。
Sliced scroll只是普通滚动的更快速的方法:它允许并行下载文档集合。切片只是滚动查询输出中的文档子集。
response_array = []
response = ElkConfigClient.search index: "index_name",
body: {
query: {
bool: {
must: [
"search_query"
]
}
}
},
scroll: '1h',
size: 1000
scroll_id = response["_scroll_id"]
s_id = scroll_id
#iterate the response
response["hits"]["hits"].each do |response|
response_array.push(response)
end
while (true)
next_response = ElkConfigClient.scroll(scroll_id: s_id, scroll: '1h')
next_scroll_id = next_response["_scroll_id"]
s_id = next_scroll_id
break if next_response["hits"]["hits"].length == 0
next_response["hits"]["hits"].each do |response|
response_array.push(response)
end
response_array
end