嵌套字段中的嵌套聚合?

时间:2020-01-06 14:54:06

标签: elasticsearch elasticsearch-6

我是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 个答案:

答案 0 :(得分:1)

1)聚合_search查询:

首先按区域进行汇总,并嵌套路径。然后反转到根文档,然后将agg嵌套到国家/地区。

{
  "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)检索文档:

在汇总中添加热门新闻: 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}
                    }
                },
    ...