Search code examples
elasticsearchelasticsearch-5

Elasticsearch count in groups by date range


I have documents like this:

{
body: 'some text',
read_date: '2017-12-22T10:19:40.223000'
}

Is there a way to query count of documents published in last 10 days group by date? For example:

2017-12-22, 150  
2017-12-21, 79  
2017-12-20, 111  
2017-12-19, 27  
2017-12-18, 100  

Solution

  • Yes, you can easily achieve that using a date_histogram aggregation, like this:

    {
      "query": {
        "range": {
          "read_date": {
            "gte": "now-10d"
          }
        }
      },
      "aggs": {
        "byday": {
          "date_histogram": {
            "field": "read_date",
            "interval": "day"
          }
        }
      }
    }