Date Histogram Aggregation
The date histogram aggregation groups date values into buckets of a fixed time interval. Let’s group products by the month they were sold.
Query:
GET /products/_search
{
"size": 0,
"aggs": {
"sales_by_month": {
"date_histogram": {
"field": "sold_date",
"calendar_interval": "month"
}
}
}
}
Output:
{
"aggregations": {
"sales_by_month": {
"buckets": [
{
"key_as_string": "2023-01-01T00:00:00.000Z",
"key": 1672531200000,
"doc_count": 5
},
{
"key_as_string": "2023-02-01T00:00:00.000Z",
"key": 1675209600000,
"doc_count": 3
},
{
"key_as_string": "2023-03-01T00:00:00.000Z",
"key": 1677628800000,
"doc_count": 2
}
]
}
}
}
In this example, products are grouped by the month they were sold, and the number of products sold each month is counted.
Bucket Aggregation in Elasticsearch
Elasticsearch is a robust tool not only for full-text search but also for data analytics. One of the core features that make Elasticsearch powerful is its aggregation framework, particularly bucket aggregations. Bucket aggregations allow you to group documents into buckets based on certain criteria, making it easier to analyze and summarize your data.
This article will explain what bucket aggregations are, how they work, and provide detailed examples to help you understand their usage.