0
0
Elasticsearchquery~5 mins

Date histogram in Elasticsearch

Choose your learning style9 modes available
Introduction

A date histogram groups data by time intervals, like days or months. It helps you see trends over time.

You want to count how many events happened each day.
You need to analyze sales totals by month.
You want to track website visits per hour.
You want to compare data grouped by weeks.
You want to visualize time-based data in charts.
Syntax
Elasticsearch
{
  "aggs": {
    "group_by_date": {
      "date_histogram": {
        "field": "date_field",
        "calendar_interval": "interval",
        "format": "date_format"
      }
    }
  }
}

field is the date field in your data.

calendar_interval sets the time bucket, like day, week, or month.

Examples
Groups sales by each month.
Elasticsearch
{
  "aggs": {
    "sales_per_month": {
      "date_histogram": {
        "field": "sale_date",
        "calendar_interval": "month"
      }
    }
  }
}
Groups website visits by day and formats the date.
Elasticsearch
{
  "aggs": {
    "visits_per_day": {
      "date_histogram": {
        "field": "visit_time",
        "calendar_interval": "day",
        "format": "yyyy-MM-dd"
      }
    }
  }
}
Sample Program

This query counts logins grouped by each week, showing the start date of the week.

Elasticsearch
{
  "size": 0,
  "aggs": {
    "logins_per_week": {
      "date_histogram": {
        "field": "login_date",
        "calendar_interval": "week",
        "format": "yyyy-MM-dd"
      }
    }
  }
}
OutputSuccess
Important Notes

Use calendar_interval for natural time units like day, week, month.

You can also use fixed_interval for exact time spans like 30d (30 days).

The format option helps display dates in a readable way.

Summary

Date histogram groups data by time intervals.

Use it to analyze trends over days, weeks, or months.

Set the date field and interval to get time-based buckets.