首页 > 解决方案 > 嵌套对象上的 Elasticsearch 聚合

问题描述

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

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

我想要一个聚合,比如:“名称包含 SCM 令牌的阶段的平均持续时间”

我试过类似的东西:

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

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

标签: elasticsearchelasticsearch-aggregation

解决方案


在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"
              }
            }
          }
        }
      }
    }
  }
}

推荐阅读