Aggregations: Analyzing Your Data

6 min read

Course: Elasticsearch

Topic: Aggregations: Analyzing Your Data

Imagine you are managing the database for a massive global e-commerce platform. Every second, hundreds of orders are placed. In your Elasticsearch cluster, you have millions of documents representing individual purchases.

If your boss walks in and asks, "What was our total revenue yesterday?" and you hand them a USB drive containing 4 million individual JSON receipts, you are going to get fired. Your boss does not want to read documents; your boss wants a summary. You need a way to group those receipts by day, calculate the total sums, and find out the most popular product categories.

This is exactly what Aggregations do.


1. Introduction to Aggregations: Metrics vs. Buckets

The Problem: Standard search queries in Elasticsearch (match, term, etc.) return individual documents. They are designed to answer the question, "Which documents match my search?" But they cannot answer analytical questions like "How many?", "What is the average?", or "What are the top categories?"

The Concept: Aggregations are a framework in Elasticsearch that collects, groups, and extracts statistics from your documents based on a search query. While standard queries find the needle in the haystack, aggregations look at the whole haystack and tell you how big it is, what it weighs, and what percentage of it is actually hay.

Under the hood, Elasticsearch reads the matching documents and feeds their values into data structures that keep running totals, averages, or grouped lists in memory, returning only the final computed result.

In industry practice, aggregations are divided into two main families that you will use 99% of the time: Metrics and Buckets.

  • Metric Aggregations: Think of this as the math. These calculate values like sums, averages, minimums, and maximums based on numerical fields.
  • Bucket Aggregations: Think of this as the sorting bins. These group documents into distinct categories or time ranges. Instead of calculating a number, they create "buckets" and put matching documents inside them.

Let's look at how to use them.


2. Metric Aggregations: Calculating Sums, Averages, and Stats

The Problem: You have filtered your data down to the sales of "Laptop Computers", but you need to know the Average Order Value (AOV) and the total revenue.

The Concept: Metric aggregations compute metrics over a set of documents. They extract numerical values from specific fields in your documents and perform mathematical operations on them.

Industry Standard Practice:
When writing an aggregation query, you usually set "size": 0 in the main request body. Why? Because you only want the analytical results, not the actual 10,000 raw documents. Saving network bandwidth is crucial in production.

Here is how you calculate the total revenue (sum) and average price (avg) of your sales.

json
GET /sales/_search
{
  "size": 0, 
  "query": {
    "match": {
      "category": "Laptops"
    }
  },
  "aggs": {
    "total_revenue": {
      "sum": {
        "field": "price"
      }
    },
    "average_price": {
      "avg": {
        "field": "price"
      }
    }
  }
}

The stats Aggregation (The Industry Cheat Code):
Often, you don't just want the average. You want the minimum, maximum, average, and total sum all at once. Instead of writing four separate aggregations, you should use the stats aggregation. This is highly utilized in production dashboards.

json
GET /sales/_search
{
  "size": 0,
  "aggs": {
    "price_statistics": {
      "stats": {
        "field": "price"
      }
    }
  }
}

The Response:

json
{
  "...": "...",
  "aggregations": {
    "price_statistics": {
      "count": 1450,
      "min": 299.99,
      "max": 3499.99,
      "avg": 1250.50,
      "sum": 1813225.0
    }
  }
}

Boom. You just processed 1,450 documents and returned exactly what the business team needed in milliseconds.


3. Bucket Aggregations: Grouping Data with Terms and Date Histograms

The Problem: Knowing your total revenue is great, but now the marketing team wants to know which product categories are selling the most, and they want to see the daily sales volume for the past month.

The Concept: Bucket aggregations do not calculate mathematical values. Instead, they create "buckets" based on field values or time ranges, and they count how many documents fall into each bucket.

There are many types of bucket aggregations, but the industry revolves heavily around two: Terms (grouping by string/keyword) and Date Histogram (grouping by time).

A. The terms Aggregation

The terms aggregation dynamically creates a bucket for every unique term it finds in a specific field.

Important Note: You should almost always run terms aggregations on keyword fields, NOT text fields. text fields are analyzed (split into individual words), so grouping by a text field called "category" might split "Gaming Laptops" into two buckets: "Gaming" and "Laptops". A keyword field keeps the exact string intact.

json
GET /sales/_search
{
  "size": 0,
  "aggs": {
    "popular_categories": {
      "terms": {
        "field": "category.keyword",
        "size": 10 
      }
    }
  }
}

Notice "size": 10 inside the aggregation. This tells Elasticsearch to only return the top 10 buckets with the most documents. If you have 10,000 unique categories, you don't want to crash your application trying to load them all.

B. The date_histogram Aggregation

If you are dealing with logs or sales data, time is everything. A date_histogram creates buckets for specific time intervals (e.g., every day, every month).

In modern Elasticsearch (8.x+), you use calendar_interval (for calendar-aware intervals like months and days) or fixed_interval (for exact blocks of time like 30 days or 90 minutes).

json
GET /sales/_search
{
  "size": 0,
  "aggs": {
    "daily_sales_volume": {
      "date_histogram": {
        "field": "purchase_date",
        "calendar_interval": "day"
      }
    }
  }
}

This returns a list of buckets, one for each day, alongside the doc_count (how many sales happened that day). This is exactly how tools like Kibana build those beautiful line charts.


4. Nesting Aggregations for Deep Data Insights

The Problem: You have the daily sales volume (Bucket), and you know how to get the total revenue (Metric). But what if you want the total revenue per day?

The Concept: Aggregations can be nested. You can place a Metric aggregation inside a Bucket aggregation. Elasticsearch will first group the documents into buckets, and then compute the metric for the specific documents inside each individual bucket.

Think of it like sorting your receipts by month (Bucket), and then using a calculator on each pile separately (Metric).

Let's combine our date_histogram bucket with our sum metric to get daily revenue.

json
GET /sales/_search
{
  "size": 0,
  "aggs": {
    "sales_over_time": {
      "date_histogram": {
        "field": "purchase_date",
        "calendar_interval": "day"
      },
      "aggs": {
        "daily_revenue": {
          "sum": {
            "field": "price"
          }
        }
      }
    }
  }
}

The Response:

json
{
  "aggregations": {
    "sales_over_time": {
      "buckets": [
        {
          "key_as_string": "2026-02-23T00:00:00.000Z",
          "key": 1771804800000,
          "doc_count": 250,
          "daily_revenue": {
            "value": 45000.50
          }
        },
        {
          "key_as_string": "2026-02-24T00:00:00.000Z",
          "key": 1771891200000,
          "doc_count": 310,
          "daily_revenue": {
            "value": 62000.00
          }
        }
      ]
    }
  }
}

Industry Practice Check:
Can you nest buckets inside buckets? Absolutely. You can group by Day, and inside each Day bucket, group by Category, and inside each Category bucket, calculate the Average Price.
A word of caution: Nesting too deeply causes the number of buckets to multiply exponentially. If you nest a 100-item terms aggregation inside a 100-item date histogram inside another 100-item terms aggregation, you are asking the server to hold 1,000,000 buckets in memory. Your Elasticsearch cluster will sweat, wheeze, and eventually throw an OutOfMemory error. Stick to 2 or 3 levels of nesting max in production!


References & Extra Reading

Challenge

You are an analyst tasked with creating a quarterly performance report for an e-commerce company. Your goal is to construct a single Elasticsearch query against the quarterly_reports index to analyze monthly sales performance broken down by product category.

Requirements:

  1. Your query should not retrieve any source documents. Only the aggregation results should be returned.
  2. Create a primary aggregation named sales_over_time. This should be a date_histogram that groups documents from the sale_date field into monthly buckets.
  3. Within each monthly bucket, you need to nest a sub-aggregation named top_categories. This should be a terms aggregation that identifies the top 5 product categories based on document count. Target the product_category.keyword field for this.
  4. Finally, within each of the top category buckets, nest a final aggregation named revenue_metrics. This should be a stats aggregation on the revenue field to calculate the count, min, max, average, and sum of revenue for that specific category in that specific month.

Expected result

Your final query should be a JSON object with a size key set to 0 and an aggs object. The aggs object contains a date_histogram aggregation named sales_over_time on the sale_date field with a calendar_interval of month. Nested inside sales_over_time is another aggs object containing a terms aggregation named top_categories on the product_category.keyword field with a size of 5. Nested within top_categories is the final aggs object, containing a stats aggregation named revenue_metrics on the revenue field.

json
GET /quarterly_reports/_search
{
  "size": 0,
  "aggs": {
    "sales_over_time": {
      "date_histogram": {
        "field": "sale_date",
        "calendar_interval": "month"
      },
      "aggs": {
        "top_categories": {
          "terms": {
            "field": "product_category.keyword",
            "size": 5
          },
          "aggs": {
            "revenue_metrics": {
              "stats": {
                "field": "revenue"
              }
            }
          }
        }
      }
    }
  }
}
json

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.