不同键上的弹性搜索聚合

时间:2016-08-30 13:16:25

标签: elasticsearch aggregation

我想通过字段中的不同键聚合我的文档"类别"。 这是两个文件:

      "date": 1470271301,
      "categories": {
        "1": [blabla],
        "2": [blala]
      }


      "date": 144343545,
      "categories": {
        "1": [blabla],
        "2": [coco]
        "3": [rat, saouth]
      }

类别映射:

"categories" : {
    "properties" : {
        "1" : {
            "type" : "long"

我希望得到这样的东西:

 "buckets" : [ {
    "key" : "1",
    "doc_count" : 2
  }, {
    "key" : "2",
    "doc_count" : 2
    {
    "key" : "3",
    "doc_count" : 1
  }

有没有一种很好的方法可以在不改变文档映射的情况下执行此操作?

1 个答案:

答案 0 :(得分:3)

可以使用元字段_field_names来实现此目的。

如下例所示,在此处运行聚合将为您提供文档计数。

示例:

put test/test/1 
{
    "date": 1470271301,
      "categories": {
        "1": ["blabla"],
        "2": ["blala"]
      }
}
put test/test/2 
{
   "date": 144343545,
      "categories": {
        "1": ["blabla"],
        "2": ["coco"],
        "3": ["rat", "saouth"]
      }
}

POST test/_search
{
   "size": 0,
   "aggs": {
      "field_documents": {
         "terms": {
            "field": "_field_names",
            "include" : "categories.*",
            "size": 0
         }
      }
   }
}

结果:

  "aggregations": {
      "field_documents": {
         "doc_count_error_upper_bound": 0,
         "sum_other_doc_count": 0,
         "buckets": [
            {
               "key": "categories",
               "doc_count": 2
            },
            {
               "key": "categories.1",
               "doc_count": 2
            },
            {
               "key": "categories.2",
               "doc_count": 2
            },
            {
               "key": "categories.3",
               "doc_count": 1
            }
         ]
      }
   }