【问题标题】:Elasticsearch - Aggregate on nested field, then on field outside the nestingElasticsearch - 在嵌套字段上聚合,然后在嵌套之外的字段上聚合
【发布时间】:2017-10-05 23:08:21
【问题描述】:

我有这个映射:

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

【问题讨论】:

    标签: elasticsearch elasticsearch-aggregation


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2023-04-03
      • 2017-09-13
      • 2015-07-30
      • 2020-12-21
      • 2018-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-01
      相关资源
      最近更新 更多