0
0
Elasticsearchquery~5 mins

Cardinality aggregation in Elasticsearch

Choose your learning style9 modes available
Introduction

Cardinality aggregation helps count how many unique values exist in a group. It tells you the number of different items, not just the total.

You want to know how many unique users visited your website.
You need to count distinct product IDs sold in a store.
You want to find out how many different countries your customers come from.
You want to count unique IP addresses accessing a server.
You want to know how many unique tags are used in blog posts.
Syntax
Elasticsearch
{
  "aggs": {
    "unique_count": {
      "cardinality": {
        "field": "field_name"
      }
    }
  }
}

Replace field_name with the name of the field you want to count unique values for.

The result will give you the count of distinct values in that field.

Examples
Counts unique user IDs in the data.
Elasticsearch
{
  "aggs": {
    "unique_users": {
      "cardinality": {
        "field": "user_id"
      }
    }
  }
}
Counts unique product IDs using the keyword field for exact matches.
Elasticsearch
{
  "aggs": {
    "unique_products": {
      "cardinality": {
        "field": "product_id.keyword"
      }
    }
  }
}
Sample Program

This query counts how many unique countries appear in the country field. The "size": 0 means we don't want actual documents, just the aggregation result.

Elasticsearch
{
  "size": 0,
  "aggs": {
    "unique_countries": {
      "cardinality": {
        "field": "country.keyword"
      }
    }
  }
}
OutputSuccess
Important Notes

Cardinality aggregation uses an approximation algorithm, so the count might be slightly off but is very fast.

Use the .keyword field for text fields to count exact unique values.

You can combine cardinality with other aggregations to get more insights.

Summary

Cardinality aggregation counts unique values in a field.

It is useful to find distinct items like users, products, or countries.

The count is approximate but efficient for large data.