嵌套对象上的 Elasticsearch 聚合

Elasticsearch aggregation on nested objects

我有一个包含以下映射的文档:

{
  "some_doc_name": {
    "mappings": {
      "_doc": {
        "properties": {
          "stages": {
            "properties": {
              "name": {
               "type": "text"
              },
              "durationMillis": {
                "type": "long"
              }
            }
          }
        }
      }
    }
  }
}

我想要一个像这样的聚合:"The average duration of the stages which name contains the SCM token"

我试过类似的方法:

{
  "aggs": {
    "scm_stage": {
      "filter": {
        "bool": {
          "should": [{
            "match_phrase": {
              "stages.name": "SCM"
            }
          }]
        }  
      },
      "aggs" : {
        "avg_duration": { 
          "avg": { 
            "field": "stages.durationMillis"
          }
        }
      }
    }
  }
}

但这是给我所有文档的所有阶段的平均值,这些文档至少包含一个带有 SCM 令牌的阶段。关于如何正确进行此聚合的任何建议?

val

的帮助下回答我自己的问题

我的映射文件缺少 "type": "nested", 类似的东西:

...
"stages": {
  "type": "nested",
  "properties": {
    "id": {
    "type": "keyword",
    "ignore_above": 256
  },
  ...

然后我可以让我的聚合与这样的东西一起工作:

{
  "size": 0,
  "query": {
    "nested": {
      "path": "stages",
      "query": {
        "match": {
          "stages.name": "scm"
        }
      }
    }
  },
  "aggs": {
    "stages": {
      "nested": {
        "path": "stages"
      },
      "aggs": {
        "stages-filter": {
          "filter": {
            "terms": {
              "stages.name": [
                "scm"
              ]
            }
          },
          "aggs": {
            "avg_duration": {
              "avg": {
                "field": "stages.durationMillis"
              }
            }
          }
        }
      }
    }
  }
}