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

Elasticsearch - Aggregate on nested field, then on field outside the nesting

我有这个映射:

{
    "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 字段的一部分,但我找不到解决方法。 (当然,实际映射比较复杂,我真的很想避免更改)

好的,原来神奇的关键字是 "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"
                           }
                        }
                     }
                  }
               }
            }
         }
      }
   }
}