0
0
Elasticsearchquery~30 mins

Cardinality aggregation in Elasticsearch - Mini Project: Build & Apply

Choose your learning style9 modes available
Cardinality Aggregation in Elasticsearch
📖 Scenario: You work for an online store that wants to know how many unique customers have placed orders.
🎯 Goal: Build an Elasticsearch query using cardinality aggregation to find the count of unique customer IDs from the orders data.
📋 What You'll Learn
Create an Elasticsearch index named orders with sample order documents
Add a variable for the field name to aggregate on
Write a cardinality aggregation query using the field variable
Print the unique count of customers from the aggregation result
💡 Why This Matters
🌍 Real World
Counting unique customers helps businesses understand how many different people buy their products.
💼 Career
Knowing how to use cardinality aggregation is useful for data analysts and backend developers working with Elasticsearch.
Progress0 / 4 steps
1
Create the orders index with sample data
Create an Elasticsearch index called orders with these exact documents: {"order_id": 1, "customer_id": "C1"}, {"order_id": 2, "customer_id": "C2"}, {"order_id": 3, "customer_id": "C1"}, {"order_id": 4, "customer_id": "C3"}.
Elasticsearch
Need a hint?

Use PUT /orders/_doc/{id} to add each document with the exact fields and values.

2
Set the field name for aggregation
Create a variable called field_name and set it to the string "customer_id".
Elasticsearch
Need a hint?

Just assign the string "customer_id" to the variable field_name.

3
Write the cardinality aggregation query
Write an Elasticsearch query using cardinality aggregation on the field stored in field_name. Use the aggregation name unique_customers.
Elasticsearch
Need a hint?

Use "aggs": { "unique_customers": { "cardinality": { "field": field_name }}} inside the query.

4
Print the unique customer count from the aggregation result
Print the unique customer count from the aggregation result using print(result['aggregations']['unique_customers']['value']).
Elasticsearch
Need a hint?

Use the print statement to show the value inside result['aggregations']['unique_customers']['value'].