ElasticSearch:如何迭代/滚动遍历索引中的所有文档
在 ElasticSearch 中,你可以使用 Scroll API 滚动遍历整个索引中的所有文档。
在 Python 中你可以像这样滚动:
es_scroll_iterate.py
def es_iterate_all_documents(es, index, pagesize=250, scroll_timeout="1m", **kwargs):
"""
辅助函数:迭代单个索引中的所有值
生成所有文档。
"""
is_first = True
while True:
# 滚动下一个
if is_first: # 初始化滚动
result = es.search(index=index, scroll="1m", **kwargs, body={
"size": pagesize
})
is_first = False
else:
result = es.scroll(body={
"scroll_id": scroll_id,
"scroll": scroll_timeout
})
scroll_id = result["_scroll_id"]
hits = result["hits"]["hits"]
# 没有更多文档时停止
if not hits:
break
# 生成每个条目
yield from (hit['_source'] for hit in hits)此函数将 yield 索引中遇到的每个文档。
索引 my_index 的用法示例:
minimal_argparse_example.py
es = Elasticsearch([{"host": "localhost"}])
for entry in es_iterate_all_documents(es, 'my_index'):
print(entry) # 打印存储在数据库中的文档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