Elasticsearch two level sort in aggregation list

2019-06-28 01:55发布

Currently I am sorting aggregations by document score, so most relevant items come first in aggregation list like below:

{
            'aggs' : {
                'guilds' : {
                    'terms' : {
                        'field' : 'guilds.title.original',
                        'order' : [{'max_score' : 'desc'}],
                        'aggs' : {
                            'max_score' : {
                                'script' : 'doc.score'
                            }
                        }
                    }
                }
            }
        }

I want to add another sort option to the order terms order array in my JSON. but when I do that like this :

{
        'order' : [{'max_score' : 'desc'}, {"_count" : "desc"},
    }

The second sort does not work. For example when all of the scores are equal it then should sort based on query but it does not work.

2条回答
Fickle 薄情
2楼-- · 2019-06-28 02:26

I don't know how your 'aggs' is even working because I tried it and I had parsing errors in three places: "order" is not allowed to have that array structure, your second "aggs" should be placed outside the first "terms" aggs and, finally, the "max_score" aggs should have had a "max" type of "aggs". In my case, to make it work (and it does actually order properly), it should look like this:

  "aggs": {
    "guilds": {
      "terms": {
        "field": "guilds.title.original",
        "order": {
          "max_score": "desc", 
          "_count": "desc"
        }
      },
      "aggs": {
        "max_score": {
          "max": {
            "script": "doc.score"
          }
        }
      }
    }
  }
查看更多
家丑人穷心不美
3楼-- · 2019-06-28 02:45

As a correction to Andrei's answer ... to order aggregations by multiple criteria, you MUST create an array as shown in Terms Aggregation: Order and you MUST be using ElasticSearch 1.5 or later.

So, for Andrei's answer, the correction is: "order" : [ { "max_score": "desc" }, { "_count": "desc" } ]

As Andrei has it, ES will not complain but it will ONLY use the last item listed in the "order" element.

查看更多
登录 后发表回答