如何在 Python 中对来自 Elasticsearch DSL 的结果进行分页

How to paginate results from Elasticsearch DSL in Python

我正在使用 Elasticsearch DSL,我想对结果进行分页。为此,我需要知道搜索结果的总数。我应该怎么做最好?

我是否执行一次搜索,然后执行两次,一次通常用于 .hits.total,另一次用于项目切片?像这样:

response = Link.search().filter("term", run_id=run_id)
total = response.execute().hits.total
links = response[start:end].execute()

试试这个:

dsl = Link.search().filter("term", run_id=run_id)
response = dsl[start:end].execute()
links = response.hits.hits
total = response.hits.total

...只命中 ElasticSearch 一次。

官方文档:https://elasticsearch-dsl.readthedocs.io/en/latest/search_dsl.html#pagination