ElasticSearch: Alle Dokumente im Index iterieren / scrollen
English
Deutsch
In ElasticSearch, you can use the Scroll API to scroll through all documents in an entire index.
In Python kannst du so scrollen:
es_scroll_iterate.py
def es_iterate_all_documents(es, index, pagesize=250, scroll_timeout="1m", **kwargs):
"""
Hilfsfunktion, um ALLE Werte aus einem einzelnen Index zu iterieren
Yields all the documents.
"""
is_first = True
while True:
# Scrollen zum nächsten
if is_first: # Scroll initialisieren
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"]
# Stoppen, wenn keine Docs mehr da sind
if not hits:
break
# Jeden Eintrag zurückgeben
yield from (hit['_source'] for hit in hits)Diese Funktion wird jedes im Index gefundene Dokument yield zurückgeben.
Verwendungsbeispiel für Index my_index:
minimal_argparse_example.py
es = Elasticsearch([{"host": "localhost"}])
for entry in es_iterate_all_documents(es, 'my_index'):
print(entry) # Gibt das Dokument aus, wie es in der DB gespeichert istCheck 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