AI Hints
Home›Elasticsearch Tutorial›Better Ranking and Aggregations
Elasticsearch · Lesson 69 of 120

terms Aggregation

Count by value.

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

The left side of a shop page lists brands with counts. TrailCo, twelve. Ridgeline, ten. Those numbers come from a terms aggregation.

  • Brand list
  • With counts
  • terms agg

Products per brand

A terms aggregation on brand makes one bucket per brand, with a document count. Run it. Six buckets, sorted by count, biggest first.

Dev Tools Consoletext
GET products/_search?filter_path=aggregations
{
  "size": 0,
  "aggs": {
    "brands": { "terms": { "field": "brand" } }
  }
}
Output
{
  "aggregations": {
    "brands": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {"key": "TrailCo", "doc_count": 12},
        {"key": "Ridgeline", "doc_count": 10},
        {"key": "Summit", "doc_count": 9},
        {"key": "Alpina", "doc_count": 6},
        {"key": "Granite", "doc_count": 6},
        {"key": "NorthPeak", "doc_count": 6}
      ]
    }
  }
}
Also uses _load
catalog

terms options

Size sets how many buckets, ten by default. Order can sort by count, or by key. Terms works on keyword and number fields, not text. And counts on a big, multi shard index can be slightly approximate.

keyvalue
sizenumber of buckets (10)
orderby _count or _key
Fieldskeyword, numbers
Accuracyapproximate on many shards

Summary

The terms aggregation makes one bucket per value, with a count, perfect for facet lists. Next, metric aggregations.

Key takeaways
  • terms
  • Buckets
  • doc_count
Next up: Metric Aggregations — sum, avg, min, max