我认为您需要
reverse_nested聚合,因为您希望基于嵌套值进行聚合,但实际上是在计算ROOT文档,而不是嵌套文档
{ "query": { "bool": { "must": [ { "term": { "last_name": "smith" } } ] } }, "aggs": { "location": { "nested": { "path": "location" }, "aggs": { "state": { "terms": { "field": "location.state", "size": 10 }, "aggs": { "top_reverse_nested": { "reverse_nested": {} } } } } } }}结果,您将看到类似以下的内容:
"aggregations": { "location": { "doc_count": 6, "state": { "doc_count_error_upper_bound": 0, "sum_other_doc_count": 0, "buckets": [ { "key": "ny", "doc_count": 4, "top_reverse_nested": { "doc_count": 2 } }, { "key": "ca", "doc_count": 2, "top_reverse_nested": { "doc_count": 2 } } ] } } }而您正在寻找的
top_reverse_nested部分内容。这里要指出的一点是:如果我没有记错的
"doc_count":6是NESTED文档计数,那么不要以为您正在计算根文档而对这些数字感到困惑,因为计数是嵌套的。因此,对于具有三个匹配的嵌套文档的文档,计数为3,而不是1。



