Sort after aggregation in Elasticsearch

I have documents with this structure:

{
    FIELD1:string,
    FIELD2:
        [ {SUBFIELD:number}, {SUBFIELD:number}...]
}

I want to sort the result of the sum of numbers in FIELD2.SUBFIELDs:

GET myindex/_search
{
  "size":0,
  "aggs": {
    "a1": {
      "terms": { 
        "field": "FIELD1",
        "size":0
      },
      "aggs":{
        "a2":{
          "sum":{
            "field":"FIELD2.SUBFIELD"
          }
        }
      }
    }
  }
}

If I do this, I get buckets that are not sorted, but I want the sorts to be sorted by the value "a2". How can i do this? Thank!

+4
source share
1 answer

You almost had it. You just need to add the orderproperty to your aggregates of terms a1, for example:

GET myindex/_search
{
  "size":0,
  "aggs": {
    "a1": {
      "terms": { 
        "field": "FIELD1",
        "size":0,
        "order": {"a2": "desc"}      <--- add this
      },
      "aggs":{
        "a2":{
          "sum":{
            "field":"FIELD2.SUBFIELD"
          }
        }
      }
    }
  }
}
+15
source

All Articles