Bird
Raised Fist0
Elasticsearchquery~10 mins

Cardinality aggregation in Elasticsearch - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Cardinality aggregation
Start Query
↓
Search Documents
↓
Extract Field Values
↓
Count Unique Values
↓
Return Cardinality Result
↓
End
The query searches documents, extracts values of a field, counts unique values, and returns the count.
Execution Sample
Elasticsearch
{
  "aggs": {
    "unique_users": {
      "cardinality": { "field": "user_id" }
    }
  }
}
This aggregation counts the number of unique user_id values in the documents.
Execution Table
StepActionField Values ExtractedUnique Values CountedResult
1Start query execution---
2Search documents matching criteria[user_id: 1, 2, 1, 3, 2]--
3Extract user_id field values[1, 2, 1, 3, 2]--
4Count unique values-3 (values: 1, 2, 3)-
5Return cardinality result--3
💡 All documents processed, unique user_id count computed as 3
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
field_values-[1, 2, 1, 3, 2][1, 2, 1, 3, 2][1, 2, 3][1, 2, 3]
unique_count---33
Key Moments - 2 Insights
Why does the count of unique values ignore repeated user_id values?
Because cardinality aggregation counts only distinct values, duplicates like user_id 1 and 2 are counted once, as shown in step 4 of the execution_table.
What happens if the field has missing values in some documents?
Documents without the field are ignored in counting unique values, so only existing field values contribute to the cardinality, as implied in step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 4, how many unique user_id values are counted?
A3
B5
C2
D4
💡 Hint
Check the 'Unique Values Counted' column at step 4 in the execution_table.
At which step are the field values extracted from documents?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the 'Action' column describing extraction in the execution_table.
If a document has no user_id field, how does it affect the unique count?
AIt increases the unique count by 1
BIt decreases the unique count by 1
CIt does not affect the unique count
DIt causes an error
💡 Hint
Refer to the key_moments explanation about missing field values.
Concept Snapshot
Cardinality aggregation counts unique values of a field.
Syntax: { "aggs": { "name": { "cardinality": { "field": "fieldname" } } } }
It returns the count of distinct values.
Duplicates are counted once.
Missing fields are ignored.
Full Transcript
Cardinality aggregation in Elasticsearch counts the number of unique values for a specified field. The process starts by executing a query to find documents. Then, it extracts the values of the chosen field from these documents. Next, it counts how many distinct values appear, ignoring duplicates. Finally, it returns this count as the result. For example, if user_id values are [1, 2, 1, 3, 2], the unique count is 3 because only values 1, 2, and 3 are distinct. Documents missing the field do not affect the count. This aggregation helps find how many different values exist in a dataset.

Practice

(1/5)
1.

What does the cardinality aggregation in Elasticsearch do?

easy
A. Calculates the sum of values in a field
B. Sorts documents by a field
C. Finds the average value of a field
D. Counts the number of unique values in a field

Solution

  1. Step 1: Understand the purpose of cardinality aggregation

    Cardinality aggregation is designed to count unique values in a specified field.
  2. Step 2: Compare with other aggregations

    Sum and average aggregations calculate totals and averages, not unique counts. Sorting is unrelated.
  3. Final Answer:

    Counts the number of unique values in a field -> Option D
  4. Quick Check:

    Cardinality = Unique count [OK]
Hint: Cardinality = count unique values fast [OK]
Common Mistakes:
  • Confusing cardinality with sum or average
  • Thinking it returns exact counts always
  • Mixing it with sorting or filtering
2.

Which of the following is the correct syntax to define a cardinality aggregation on the field user_id in Elasticsearch?

{
  "aggs": {
    "unique_users": {
      "cardinality": {
        "field": "user_id"
      }
    }
  }
}
easy
A. { "aggs": { "unique_users": { "cardinality": { "field": "user_id" } } } }
B. { "aggs": { "unique_users": { "terms": { "field": "user_id" } } } }
C. { "aggs": { "unique_users": { "sum": { "field": "user_id" } } } }
D. { "aggs": { "unique_users": { "avg": { "field": "user_id" } } } }

Solution

  1. Step 1: Identify the aggregation type for unique counts

    The cardinality aggregation is used to count unique values, so the key must be "cardinality".
  2. Step 2: Check the field name and structure

    The field is correctly specified as "user_id" inside the cardinality object.
  3. Final Answer:

    { "aggs": { "unique_users": { "cardinality": { "field": "user_id" } } } } -> Option A
  4. Quick Check:

    Correct syntax uses "cardinality" with "field" [OK]
Hint: Cardinality uses "cardinality" key with "field" [OK]
Common Mistakes:
  • Using terms aggregation instead of cardinality
  • Using sum or avg aggregations for unique counts
  • Incorrect JSON structure or missing braces
3.

Given the following Elasticsearch aggregation query:

{
  "aggs": {
    "unique_countries": {
      "cardinality": {
        "field": "country"
      }
    }
  }
}

If the indexed documents have countries: ["US", "US", "FR", "DE", "FR", "JP"], what is the expected approximate output value for unique_countries?

medium
A. 3
B. 4
C. 5
D. 6

Solution

  1. Step 1: Identify unique countries in the list

    The countries are US, FR, DE, JP. Counting unique values gives 4.
  2. Step 2: Understand cardinality output

    Cardinality aggregation returns approximate unique counts, which should be 4 here.
  3. Final Answer:

    4 -> Option B
  4. Quick Check:

    Unique countries count = 4 [OK]
Hint: Count distinct values in the field for cardinality [OK]
Common Mistakes:
  • Counting duplicates as unique
  • Confusing total documents with unique count
  • Expecting exact count always (approximate)
4.

Identify the error in this cardinality aggregation query:

{
  "aggs": {
    "unique_users": {
      "cardinality": {
        "field_name": "user_id"
      }
    }
  }
}
medium
A. Aggregation name cannot be "unique_users"
B. Missing closing brace for "aggs"
C. "field_name" should be "field"
D. Cardinality aggregation requires a "size" parameter

Solution

  1. Step 1: Check the field parameter name

    The correct key for specifying the field is "field", not "field_name".
  2. Step 2: Verify JSON structure and parameters

    The braces are correctly closed, aggregation name is valid, and "size" is not required for cardinality.
  3. Final Answer:

    "field_name" should be "field" -> Option C
  4. Quick Check:

    Use "field" key for cardinality field [OK]
Hint: Use "field", not "field_name" in cardinality [OK]
Common Mistakes:
  • Using wrong key "field_name" instead of "field"
  • Adding unnecessary parameters like "size"
  • Misnaming aggregation or missing braces
5.

You want to find the approximate number of unique products sold in each category using Elasticsearch. Which aggregation setup correctly combines terms and cardinality aggregations?

{
  "aggs": {
    "by_category": {
      "terms": { "field": "category" },
      "aggs": {
        "unique_products": {
          "cardinality": { "field": "product_id" }
        }
      }
    }
  }
}
hard
A. This setup groups by category and counts unique products per category
B. This setup counts unique categories per product
C. This setup sums product_id values per category
D. This setup finds average product_id per category

Solution

  1. Step 1: Understand the terms aggregation

    "terms" groups documents by unique values in "category" field.
  2. Step 2: Understand the nested cardinality aggregation

    Inside each category bucket, cardinality counts unique "product_id" values.
  3. Final Answer:

    This setup groups by category and counts unique products per category -> Option A
  4. Quick Check:

    Terms + cardinality = unique counts per group [OK]
Hint: Nest cardinality inside terms to count unique per group [OK]
Common Mistakes:
  • Confusing aggregation order or nesting
  • Using cardinality on category instead of product_id
  • Expecting sum or average instead of unique count
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard