如何在elasticsearch中做两个嵌套聚合?

How to do two nested aggregations in elasticsearch?

城市和家庭类型是以下文档映射中的两个嵌套对象:

"mappings" : {
  "home_index_doc" : {
    "properties" : {
      "city" : {
        "type" : "nested",
        "properties" : {
          "country" : {
            "type" : "nested",
            "properties" : {
              "name" : {
                "type" : "text"
              }
            }
          },
          "name" : {
            "type" : "keyword"
          }
        }
      },
      "home_type" : {
        "type" : "nested",
        "properties" : {
          "name" : {
            "type" : "keyword"
          }
        }
      },
      ...
    }
  }
}

我正在尝试进行以下聚合: 拿走所有现有文件并显示每个城市的所有 home_types。

我想它看起来应该类似于:

"aggregations": {
  "all_cities": {
    "buckets": [
      {
        "key": "Tokyo",
         "doc_count": 12,
         "home_types": {
            "buckets": [
               {
                  "key": "apartment", 
                  "doc_count": 5
               },
               {
                  "key": "house",
                  "doc_count": 12
               }
            ]
         }
      },
      {
        "key": "New York",
         "doc_count": 1,
         "home_types": {
            "buckets": [
               {
                  "key": "house", 
                  "doc_count": 1
               }
            ]
         }
      }
    ]
  }
}

在尝试了 gazzilion 方法和组合之后,我已经用 Kibana 做到了:

GET home-index/home_index_doc/_search
{
  "size": 0,
  "aggs": {
    "all_cities": {
     "nested": {
         "path": "city"
      },
      "aggs": {
        "city_name": {
          "terms": {
            "field": "city.name"
          }
        }
      }
    },
    "aggs": {
      "all_home_types": {
        "nested": {
          "path": "home_type"
        },
        "aggs": {
          "home_type_name": {
            "terms": {
              "field": "home_type.name"
            }
          }
        }
      }
    }
  }
}

我得到以下异常:

    "type": "unknown_named_object_exception",
    "reason": "Unknown BaseAggregationBuilder [all_home_types]",

您需要使用 reverse_nested 才能跳出 city 嵌套类型回到根级别并为 home_type 嵌套进行另一个 nested 聚合类型。基本上是这样的:

{
  "size": 0,
  "aggs": {
    "all_cities": {
      "nested": {
        "path": "city"
      },
      "aggs": {
        "city_name": {
          "terms": {
            "field": "city.name"
          },
          "aggs": {
            "by_home_types": {
              "reverse_nested": {},
              "aggs": {
                "all_home_types": {
                  "nested": {
                    "path": "home_type"
                  },
                  "aggs": {
                    "home_type_name": {
                      "terms": {
                        "field": "home_type.name"
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}