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

cardinality

How many unique.

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

How many different products sold at least once this year? Not how many orders, but how many unique products. The cardinality aggregation counts distinct values.

  • Not orders
  • Unique products
  • cardinality

Unique products sold

Cardinality on product ID counts distinct products. We also count distinct countries. Run it. Forty nine different products were sold, to customers in five countries.

Dev Tools Consoletext
GET orders/_search?filter_path=aggregations
{
  "size": 0,
  "aggs": {
    "products_sold": { "cardinality": { "field": "product_id" } },
    "countries":     { "cardinality": { "field": "country" } }
  }
}
Output
{
  "aggregations": {
    "products_sold": {"value": 49},
    "countries": {"value": 5}
  }
}
Also uses _load
orders

About cardinality

Cardinality is approximate, using an algorithm called hyper log log. It's exact for small numbers, and very close for millions. Precision threshold trades memory for accuracy. It's how dashboards show unique visitors.

keyvalue
Countsdistinct values
MethodHyperLogLog++
Accuracyexact when small
Useunique users, products

Summary

Cardinality counts distinct values, fast and nearly exact. Next, showing the top documents inside each bucket.

Key takeaways
  • cardinality
  • Distinct
  • Approximate
Next up: top_hits — best documents per bucket