Sorting after aggregation in Elasticsearch

2019-02-05 03:57发布

I have docs with this structure:

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

I want to sort on 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 obtain buckets not sorted, but I want buckets sorted by "a2" value. How I can do this? Thank you!

1条回答
霸刀☆藐视天下
2楼-- · 2019-02-05 04:28

You almost had it. You just need to add an order property to your a1 terms aggregations, like this:

GET myindex/_search
{
  "size":0,
  "aggs": {
    "a1": {
      "terms": { 
        "field": "FIELD1",
        "size":0,
        "order": {"a2": "desc"}      <--- add this
      },
      "aggs":{
        "a2":{
          "sum":{
            "field":"FIELD2.SUBFIELD"
          }
        }
      }
    }
  }
}
查看更多
登录 后发表回答