Elasticsearch - 使用带有has_child的过滤器对嵌套文档进行聚合

时间:2015-07-29 13:21:09

标签: elasticsearch

我的索引文档看起来有点像这样;

- a - Parent doc
 \- b - Nested doc (0 to many relation to a)
 \- c - Child doc (0 to many relation to a)
 \- d - Child doc (0 to many relation to a)

a和b中的信息是"从不"改变。 c和d中的信息经常被改变,父子关系似乎是一个完美的匹配。

在b上执行聚合工作正常。过滤/查询使用c / d也可以正常工作。当我尝试结合" has_child"过滤器c / d和b的嵌套聚合返回没有聚合。在_hits下,返回正确数量的父文档(总计)。

有没有办法执行这种类型的聚合,或者这是一个限制?

/someindex/a/_search
{
   "size": 0,
   "filter": {
     "has_child": {
       "type": "c",
       "filter": {
          "term": { "someFieldInC": 123}
         }
       }
     }
   }, 
  "aggregations" : {
     "details": {
        "nested": {
           "path": "b" 
         },
         "aggregations" : {
           "details-filter" : {
              "filter" : {
                 "query" : {
                    "term": {"b.someFieldInB": 123}
                 }
              },
              "aggregations" : {
                "some_count" : { 
                   "terms" : { 
                      "field" : "b.someCountFieldInB"
                   } 
                }
             }
           }
        }
     }
   }
}

给予

{
  "took":22,
  "timed_out":false,
  "_shards": {
     "total":5,
     "successful":5,
     "failed":0
  },
  "hits":{
     "total":20134,
     "max_score":0.0,
     "hits":[]
  }
}

2 个答案:

答案 0 :(得分:0)

您需要告诉您的过滤器它也在导航嵌套文档。修改您的请求如下:

  "aggregations" : {
     "details": {
        "nested": {
           "path": "b" 
         },
         "aggregations" : {
           "details-filter" : {
              "filter" : {
                 "nested": {
                    "path": "b",
                     "filter": {
                         "query" : {
                            "term": {"b.someFieldInB": 123}
                         }
                     }
                 }
              },
              "aggregations" : {
                "some_count" : { 
                   "terms" : { 
                      "field" : "b.someCountFieldInB"
                   } 
                }
             }
           }
        }
     }

答案 1 :(得分:0)

经过一番挖掘后,我找到了回答。

在我的嵌套聚合之前,只需将子过滤器移动到顶部的聚合中;

"aggregations" : {
   "childfilter" : { 
      "filter": {
         "has_child": {
            "type": "c",
            "query": {
               "match": {"someFieldInC": 123}
             }
         }
    },
    "aggregations" : {
       "details": {
          "nested": {
   . . . .