Elasticsearch:在文档中聚合并对文档进行排序

时间:2016-06-27 07:24:35

标签: elasticsearch

我有一个Elasticsearch索引,其中包含JSON文档,如下所示:

{ "category": "cat001", "items": [{ "item": "item001", "count": 5}, { "item": "item005", "count": 3}]}
{ "category": "cat002", "items": [{ "item": "item002", "count": 4}, { "item": "item001", "count": 3}]}
{ "category": "cat003", "items": [{ "item": "item003", "count": 5}, { "item": "item001", "count": 2}]}

我想添加每个类别的所有计数,并根据每个类别中的计数总和对类别进行排序。这可能吗?如果是这样,怎么样?谢谢您的帮助。

1 个答案:

答案 0 :(得分:0)

使用以下查询:

{
 "size" : 0,
 "aggs": {
  "group_by_category": {
      "terms": {
          "field" : "category",
          "order": {
           "sum_of_items": "desc"
        }
      },
      "aggs" : {
       "sum_of_items" : {
           "sum" : {
               "field" : "items.count"
            }
          }
       }
     }
  }
}