| endpoint | async_search |
|---|---|
| lang | python |
| es_version | 9.3 |
| client | elasticsearch==9.3.0 |
Use client.async_search.submit() to start a search that runs in
the background. This is useful for long-running queries that would
otherwise time out:
response = client.async_search.submit(
index="products",
query={"match_all": {}},
wait_for_completion_timeout="0s",
)
search_id = response["id"]
print(f"Search submitted: {search_id[:20]}...")Check the status of an async search, then retrieve the results once complete:
import time
while True:
status = client.async_search.status(id=search_id)
if not status["is_running"]:
break
time.sleep(0.5)
result = client.async_search.get(id=search_id)
for hit in result["response"]["hits"]["hits"]:
print(f" {hit['_source']['name']}")Always delete the async search when done to free server resources. Use try/finally to ensure cleanup even if processing fails:
response = client.async_search.submit(
index="products",
query={"match": {"category": "electronics"}},
wait_for_completion_timeout="0s",
)
search_id = response["id"]
try:
result = client.async_search.get(
id=search_id,
wait_for_completion_timeout="10s",
)
for hit in result["response"]["hits"]["hits"]:
print(hit["_source"]["name"])
finally:
client.async_search.delete(id=search_id)