Elasticsearch - 在嵌套字段上聚合,然后在嵌套外部的字段上聚合

时间:2017-10-05 13:54:40

标签: elasticsearch elasticsearch-aggregation

我有这个映射:

{
    "event": {
        "properties": {
            "visitor": {
                "type": "keyword"
            },
            "location": {
                "type": "nested",
                "properties": {
                    "country": {
                        "type": "keyword"
                    },
                    "region": {
                        "type": "keyword"
                    },
                    "city": {
                        "type": "keyword"
                    }
                }
            }
        }
    }
}

这两个聚合按预期工作:

{
   "size": 0,
   "aggs": {
      "location": {
         "nested": {
            "path": "location"
         },
         "aggs": {
            "by_country": {
               "terms": {
                  "field": "location.country"
               }
            }
         }
      }
   }
}

{
   "size": 0,
   "aggs": {
      "visitor_count": {
         "cardinality": {
            "field": "visitor"
         }
      }
   }
}

但是当我尝试将它们组合起来时,国家/地区聚合工作正常,但访客数量都等于0,这是错误的。

{
   "size": 0,
   "aggs": {
      "location": {
         "nested": {
            "path": "location"
         },
         "aggs": {
            "by_country": {
               "terms": {
                  "field": "location.country"
               },
               "aggs": {
                  "visitor_count": {
                     "cardinality": {
                        "field": "visitor"
                     }
                  }
               }
            }
         }
      }
   }
}

有人可以告诉我如何实现我想要做的事情吗? 我想问题是visitor字段不是嵌套location字段的一部分,但我无法找到解决方法。 (当然,实际的映射更复杂,我真的想避免更改它)

1 个答案:

答案 0 :(得分:0)

好的,结果是神奇的关键字是“reverse_nested”。这段代码对我有用:

{
   "size": 0,
   "aggs": {
      "location": {
         "nested": {
            "path": "location"
         },
         "aggs": {
            "by_country": {
               "terms": {
                  "field": "location.country"
               },
               "aggs": {
                  "reverse": {
                     "reverse_nested": {},
                     "aggs": {
                        "visitor_count": {
                           "cardinality": {
                              "field": "visitor"
                           }
                        }
                     }
                  }
               }
            }
         }
      }
   }
}