| endpoint | search |
|---|---|
| lang | python |
| es_version | 9.3 |
| client | elasticsearch==9.3.0 |
Use client.search() to find documents matching a query.
response = client.search(
index="products",
query={"match": {"category": "electronics"}},
sort=[{"price": "asc"}],
)
print(f"Found {response['hits']['total']['value']} products")
for hit in response["hits"]["hits"]:
doc = hit["_source"]
print(f" {doc['name']} — ${doc['price']}")Use from_ and size to paginate through results:
page = 0
page_size = 10
response = client.search(
index="products",
query={"match_all": {}},
from_=page * page_size,
size=page_size,
sort=[{"price": "desc"}],
)For deep pagination beyond 10,000 results, use search_after with
a point-in-time instead.
Use aggs to compute summary statistics alongside search results.
Set size=0 when you only need the aggregation, not the documents:
response = client.search(
index="products",
size=0,
aggs={
"by_category": {
"terms": {"field": "category.keyword"},
"aggs": {
"avg_price": {"avg": {"field": "price"}},
},
},
},
)
for bucket in response["aggregations"]["by_category"]["buckets"]:
print(f" {bucket['key']}: {bucket['doc_count']} products, "
f"avg ${bucket['avg_price']['value']:.2f}")