嵌套字段中的嵌套聚合?

Nested aggregation in nested field?

我是 elasticsearch 的新手,对聚合了解不多,但我有这个 ES6 映射:

{
    "mappings": {
        "test": {
            "properties": {
                "id": {
                    "type": "integer"
                }
                "countries": {
                    "type": "nested",
                    "properties": {
                        "global_id": {
                            "type": "keyword"
                        },
                        "name": {
                            "type": "text",
                            "fields": {
                                "raw": {
                                    "type": "keyword"
                                }
                            }
                        }
                    }
                },
                "areas": {
                    "type": "nested",
                    "properties": {
                        "global_id": {
                            "type": "keyword"
                        },
                        "name": {
                            "type": "text",
                            "fields": {
                                "raw": {
                                    "type": "keyword"
                                }
                            }
                        },
                        "parent_global_id": {
                            "type": "keyword"
                        }
                    }
                }
            }
        }
    }
}

如何获取按 areas 分组的所有文档,然后按 countries 分组。此外,必须完整返回文档,而不仅仅是嵌套文档。这可能吗?

1) 聚合_搜索查询:

首先按区域聚合,路径嵌套。然后reverse到根文档,嵌套agg到country。

{
  "size": 0,
  "aggs": {
    "agg_areas": {
      "nested": {
        "path": "areas"
      },
      "aggs": {
        "areas_name": {
          "terms": {
            "field": "areas.name"
          },
          "aggs": {
            "agg_reverse": {
              "reverse_nested": {},
              "aggs": {
                "agg_countries": {
                  "nested": {
                    "path": "countries"
                  },
                  "aggs": {
                    "countries_name": {
                      "terms": {
                        "field": "countries.name"
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

2) 检索文档:

在您的聚合中添加一个 tophits: https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-top-hits-aggregation.html

top_hits 速度很慢,因此您必须阅读文档并根据您的上下文调整大小和排序。

...
"terms": {
            "field": "areas.name"
          },
    "aggregations": {
                    "hits": {
                        "top_hits": { "size": 100}
                    }
                },
    ...