andre vitalni
andre vitalni

Reputation: 71

Dates not sorted for date histogram in elasticsearch

Im firing a query, only with date_histogram aggregation like below

{
  "aggs": {
    "mentionsAnalytics": {
      "date_histogram": {
        "field": "created_at",
        "interval": "day"
      }
    }
  }

Now the response Im getting is not sorted according to date. Following is my response

"aggregations": {
"mentionsAnalytics": {
"buckets": [
{
"key_as_string": "2014-10-17T00:00:00.000Z",
"key": 1413504000000,
"doc_count": 2
}
,
{
"key_as_string": "2015-09-07T00:00:00.000Z",
"key": 1441584000000,
"doc_count": 2
}
,
{
"key_as_string": "2015-09-29T00:00:00.000Z",
"key": 1443484800000,
"doc_count": 2
}
,
{
"key_as_string": "2015-11-09T00:00:00.000Z",
"key": 1447027200000,
"doc_count": 4
}
]
}
}

As you can see, the dates are occuring in random order. Can I make it sorted,by modifying any parameters inside the date_histogram aggregation. I dont prefer to give a sort query, as a seperate query. Is that possible?

Upvotes: 3

Views: 4821

Answers (1)

Mohammed Hashim
Mohammed Hashim

Reputation: 191

 {
  "aggs": {
    "mentionsAnalytics": {
      "date_histogram": {
        "field": "created_at",
        "interval": "day",
        "order": {
           "_key": "desc"
        }
      }
    }
  }

The field to be sorted on from the aggregation response should be given inside order and the type of sorting

Upvotes: 11

Related Questions