AI Hints
Home›Elasticsearch Tutorial›Sub-aggregations, Cardinality, top_hits
Elasticsearch · Lesson 76 of 120

Sub-aggregations

Numbers inside buckets.

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

How much revenue does each channel bring in? That's a bucket per channel, with a sum inside each bucket. Aggregations inside aggregations are called sub aggregations.

  • Per channel
  • Revenue in each
  • Aggs inside aggs

Revenue per channel

The terms aggregation makes a bucket per channel. Inside it, another aggs block adds a sum of total to each bucket. Run it. Web brings in the most revenue, then the app, then the stores.

Dev Tools Consoletext
GET orders/_search?filter_path=aggregations.channels.buckets.key,aggregations.channels.buckets.revenue
{
  "size": 0,
  "aggs": {
    "channels": {
      "terms": { "field": "channel" },
      "aggs": { "revenue": { "sum": { "field": "total" } } }
    }
  }
}
Output
{
  "aggregations": {
    "channels": {
      "buckets": [
        {"key": "web", "revenue": {"value": 242898.17}},
        {"key": "app", "revenue": {"value": 147917.82}},
        {"key": "store", "revenue": {"value": 89971.04}}
      ]
    }
  }
}
Also uses _load
orders

Sort buckets by a metric

Order can sort buckets by a sub aggregation. Here, categories sorted by their revenue, highest first. Size three keeps the top three. Run it. Tents earn the most.

Dev Tools Consoletext
GET orders/_search?filter_path=aggregations.top.buckets.key,aggregations.top.buckets.revenue
{
  "size": 0,
  "aggs": { "top": {
    "terms": { "field": "category", "size": 3,
               "order": { "revenue": "desc" } },
    "aggs": { "revenue": { "sum": { "field": "total" } } } } }
}
Output
{
  "aggregations": {
    "top": {
      "buckets": [
        {"key": "Tents", "revenue": {"value": 164396.92}},
        {"key": "Jackets", "revenue": {"value": 72686.27}},
        {"key": "Sleeping Bags", "revenue": {"value": 64157.77}}
      ]
    }
  }
}
Also uses _load
orders

Summary

Sub aggregations put metrics or more buckets inside each bucket, and order can sort buckets by them. Next, counting unique values.

Key takeaways
  • Nested aggs
  • Sum per bucket
  • order by metric
Next up: cardinality — how many unique