ElasticSearch:如何使用 Python 迭代索引中的所有文档(最多 10000 个文档)
重要提示: 此简单方法仅适用于最多约 10000 个文档。推荐使用我们基于滚动的解决方案:请参见ElasticSearch:如何迭代/滚动遍历索引中的所有文档
使用此辅助函数迭代索引中的所有文档
es_iterate_all_docs.py
def es_iterate_all_documents(es, index, pagesize=250, **kwargs):
"""
辅助函数:迭代所有值
生成所有文档。
"""
offset = 0
while True:
result = es.search(index=index, **kwargs, body={
"size": pagesize,
"from": offset
})
hits = result["hits"]["hits"]
# 没有更多文档时停止
if not hits:
break
# 生成每个条目
yield from (hit['_source'] for hit in hits)
# 从那里继续
offset += pagesize用法示例:
es_iterate_usage.py
for entry in es_iterate_all_documents(es, 'my_index'):
print(entry) # 打印存储在数据库中的文档工作原理
你可以使用类似这样的查询迭代 ElasticSearch 索引中的所有文档
es_query_pagination.json
{
"size": 250,
"from": 0
}并在每次迭代后将 "from" 增加 "size"。
Check out similar posts by category:
Databases, ElasticSearch, Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow