AI Hints
Home›Elasticsearch Tutorial›Metrics and Statistics
Elasticsearch · Lesson 72 of 120

Aggregating a Search

Numbers for the matches.

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

Aggregations work on whatever the query matches. Search for tents, and the aggregations describe only tents. That's how a search page shows counts for the current results.

  • Query first
  • Then aggregate
  • Only the matches

Query plus aggregations

The query matches orders from Canada. The aggregations then count those orders by channel, and sum their revenue. Run it. Every number describes Canadian orders only.

Dev Tools Consoletext
GET orders/_search?filter_path=hits.total.value,aggregations
{
  "size": 0,
  "query": { "term": { "country": "CA" } },
  "aggs": {
    "by_channel": { "terms": { "field": "channel" } },
    "revenue":    { "sum": { "field": "total" } }
  }
}
Output
{
  "hits": {"total": {"value": 374}},
  "aggregations": {
    "by_channel": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {"key": "web", "doc_count": 182},
        {"key": "app", "doc_count": 116},
        {"key": "store", "doc_count": 76}
      ]
    },
    "revenue": {"value": 102309.1}
  }
}
Also uses _load
orders

Query scope

The query decides which documents are aggregated. Size zero skips the hits, when you only need numbers. Hits and aggregations can come back together, in one request. And the global aggregation ignores the query, when you need totals for everything.

keyvalue
Querysets the scope
size: 0numbers only
Togetherhits + aggs
globalignore the query

Summary

Aggregations describe only the documents the query matches. One request can return hits and numbers together. Next, grouping numbers into ranges.

Key takeaways
  • Query scope
  • size: 0
  • One request
Next up: range Aggregation — price bands