ElasticSearch Facets / Aggregations sorting / ordering

595 views Asked by At

Does anyone know how to order aggregation / facet buckets from a range into a predictable order i/e the order they were added to the facet in?

Currently the 1.4 branch (and possibly older branches) order the buckets by "doc_count" which is not predictable. I want to be able to output the buckets in a pre-defined order.

1

There are 1 answers

3
Prabin Meitei On

A simple way could be to order them at at your end on the response from Elasticsearch. Another way could be order by term (key of the aggregation).

Update:

If you are using date range aggregation with query like below then the result will be automatically in the chronological order of "3 days ago", "yesterday", "today" irrespective of doc_count.

 {
   "aggs" : {
       "timerange" : {
           "date_range" : {
               "field" : "day",
               "keyed" : true,
               "ranges" : [
                {
                    "key": "today",
                    "from": "now/d"
                }
                ,
                {
                    "key": "yesterday",
                    "from": "now-1d/d",
                    "to": "now/d"
                },
                {
                    "key": "3 days ago",
                    "from": "now-3d/d",
                    "to": "now-2d/d"
                }
              ]
          }
      }
  }
}

If you are interested in daily data then a Date histogram will be more convenient.