7

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  
halfer
  • 19,824
  • 17
  • 99
  • 186
ehsan shirzadi
  • 4,709
  • 16
  • 69
  • 112
  • Pro-tip: a number of your Elasticsearch questions here do not seem to feature much in the way of research. This may be a tag in which helpers do not mind offering free labour, but it is worth noting that on Stack Overflow as a whole, prior effort goes a long way. It is appreciated by readers, and may encourage more people to help you. – halfer Dec 23 '17 at 23:05

2 Answers2

7

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"
      }
    }
  }
}
Val
  • 207,596
  • 13
  • 358
  • 360
2

To receive day count of the past 10 days, per day you can POST the following query:

{
  "query": {
    "range": {
      "read_date": {
        "gte": "now-11d/d",
        "lte": "now-1d/d"
      }
    }
  },

    "aggs" : {
        "byDay" : {
            "date_histogram" : {
                "field" : "read_date",
                "calendar_interval" : "1d",
                "format" : "yyyy-MM-dd" 
            }
        }
    }
}

To the following Url: http://localhost:9200/Index_Name/Index_Type/_search?size=0

Setting size to 0 avoids executing the fetch phase of the search making the request more efficient. See this elastic documentation for more information.

Mark
  • 343
  • 3
  • 11