嵌套对象上的Elasticsearch聚合

时间:2019-01-18 15:31:48

标签: elasticsearch elasticsearch-aggregation

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

{
  "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令牌的一个阶段的所有文档的所有阶段的平均值。关于如何正确实现此聚合的任何建议?

1 个答案:

答案 0 :(得分:0)

借助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"
              }
            }
          }
        }
      }
    }
  }
}
相关问题