Elasticsearch总结存储桶

时间:2016-11-03 13:19:53

标签: elasticsearch buckets

我有以下请求,该请求将返回状态为“已接受”,“已下达”或已关闭的所有文档的计数。

{
  "size": 0,
  "query": {
    "bool": {
      "must": [
        {
          "query_string": {
            "query": "*",
            "analyze_wildcard": true
          }
        }
      ],
      "must_not": []
    }
  },
  "aggs": {
    "slices": {
      "terms": {
        "field": "status.raw",
        "include": {
          "pattern": "Accepted|Released|Closed"
        }
      }
    }
  }
}

在我的情况下,回复是:

 "buckets": [
        {
          "key": "Closed",
          "doc_count": 2216
        },
        {
          "key": "Accepted",
          "doc_count": 8
        },
        {
          "key": "Released",
          "doc_count": 6
        }
      ]

现在我想将它们全部添加到一个字段中。 我尝试使用管道聚合,甚至尝试了以下sum_bucket(显然只适用于多桶):

"total":{
    "sum_bucket":{
        "buckets_path": "slices"
    }
}

任何人都可以帮我解决这个问题吗?

3 个答案:

答案 0 :(得分:2)

使用sum_bucket和您已经存在的聚合:

  "aggs": {
    "slices": {
      "terms": {
        "field": "status.raw",
        "include": {
          "pattern": "Accepted|Released|Closed"
        }
      }
    },
    "sum_total": {
      "sum_bucket": {
        "buckets_path": "slices._count"
      }
    }
  }

答案 1 :(得分:1)

我要做的是改用filters aggregation来定义你需要的所有桶,如下所示:

{
  "size": 0,
  "query": {
    "bool": {
      "must": [
        {
          "query_string": {
            "query": "*",
            "analyze_wildcard": true
          }
        }
      ],
      "must_not": []
    }
  },
  "aggs": {
    "slices": {
      "filters": {
        "filters": {
          "accepted": {
            "term": {
              "status.raw": "Accepted"
            }
          },
          "released": {
            "term": {
              "status.raw": "Released"
            }
          },
          "closed": {
            "term": {
              "status.raw": "Closed"
            }
          },
          "total": {
            "terms": {
              "status.raw": [
                "Accepted",
                "Released",
                "Closed"
              ]
            }
          }
        }
      }
    }
  }
}

答案 2 :(得分:0)

您可以使用value_count子聚合添加计数,然后使用sum_bucket pipeline aggregation

{
  "aggs": {
    "unique_status": {
      "terms": {
        "field": "status.raw",
        "include": "Accepted|Released|Closed"
      },
      "aggs": {
        "count": {
          "value_count": {
            "field": "status.raw"
          }
        }
      }
    },
    "sum_status": {
      "sum_bucket": {
        "buckets_path": "unique_status>count"
      }
    }
  },
  "size": 0
}