AI Hints
Home›Elasticsearch Tutorial›Searching and Errors in Python
Elasticsearch · Lesson 92 of 120

Aggregations in Python

Numbers for your app.

⏱ 2 min read▶ Video at 1:26:24🎓 Free
Watch this lesson in the Elasticsearch courseWatch on YouTube ↗Full Elasticsearch course

Trailhead's weekly report email needs revenue per country. Aggregations work from Python just like searching, through the aggs argument.

  • Weekly report
  • Revenue per country
  • aggs=

Revenue per country

Size zero skips the hits. Aggs has a terms bucket per country, with a sum inside. We loop over the buckets and print a small report. Run it. Revenue for each country, ready for the email.

report.pypython
from elasticsearch import Elasticsearch

es = Elasticsearch("http://localhost:9200")

resp = es.search(index="orders", size=0, aggs={
    "countries": {
        "terms": {"field": "country"},
        "aggs": {"revenue": {"sum": {"field": "total"}}}}})

for b in resp["aggregations"]["countries"]["buckets"]:
    print(f'{b["key"]}: {b["doc_count"]:>4} orders  ${b["revenue"]["value"]:>10,.2f}')
Output
US: 1109 orders  $252,452.77
CA:  374 orders  $102,309.10
AU:  180 orders  $ 46,883.16
UK:  175 orders  $ 39,879.40
DE:  162 orders  $ 39,262.60
Also uses _load
orders

Reading aggregation results

Results are under aggregations, by the name you chose. Bucket aggregations have a buckets list. Each bucket has a key, a doc count and your sub aggregations. Metrics have a value.

keyvalue
aggregationsby your name
bucketslist of dicts
key, doc_countper bucket
valuefor metrics

Summary

Aggregations in Python use the aggs argument, and you read buckets and values from the response. Next, handling errors and retries.

Key takeaways
  • aggs=
  • buckets
  • value
Next up: Errors and Retries — when things go wrong