A date histogram aggregation groups documents into time-based buckets. Use it to count books released each year, weekly product sales, or hourly server threat attempts. section 13.3.1
Configure the date field and choose either a calendar interval or a fixed interval. Calendar intervals support year, quarter, month, week, day, hour, minute, second, and millisecond. section 13.3.1
Listing 13.11 A date_histogram query
GET books/_search
{
"size":0,
"aggs": {
"release_year_histogram": {
"date_histogram": { #1
"field": "release_date", #2
"calendar_interval": "year" #3
}
}
}
}
Run this REST request to group books by release year while returning aggregation results instead of search hits. section 13.3.1
Books released by year
The result exposes each bucket through key_as_string and reports its document count: 2020 contains five books, 2021 contains six, and 2022 contains three. section 13.3.1
Daily sales with cumulative totals
Nest a sum aggregation inside daily date buckets, then apply cumulative_sum to the bucketed sales. If daily sales are 23 and 40, the second cumulative total is 63. section 13.5.5
Listing 13.22 Cumulative sales (sum) of cappuccinos sold daily
GET coffee_sales/_search { "size": 0, "aggs": { "sales_by_coffee": { "date_histogram": { "field": "date", "calendar_interval": "1d" }, "aggs": { "cappuccino_sales": { "sum": { "field": "sales.cappuccino" } }, "total_cappuccinos": { "cumulative_sum": { #1 "buckets_path": "cappuccino_sales" } } } } } } #1 Parent aggregation that calculates the cumulative total of cappuccino sales
Inspect a complete daily coffee-sales aggregation that combines date_histogram, a nested sum, and a parent cumulative_sum pipeline aggregation. section 13.5.5
