You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Elasticsearch按日期统计累计文档数的实现方案咨询

实现Elasticsearch按日期累计统计文档数

我在Elasticsearch中有多个按日期命名的索引(如login-2015.12.23),示例数据如下:

{"index":{"_index":"login-2015.12.23","_type":"logs"}}
{"uid":"1","register_time":"2015-12-23T12:00:00Z","login_time":"2015-12-23T12:00:00Z"}
{"index":{"_index":"login-2015.12.23","_type":"logs"}}
{"uid":"2","register_time":"2015-12-23T12:00:00Z","login_time":"2015-12-23T12:00:00Z"}
{"index":{"_index":"login-2015.12.24","_type":"logs"}}
{"uid":"1","register_time":"2015-12-23T12:00:00Z","login_time":"2015-12-24T12:00:00Z"}
{"index":{"_index":"login-2015.12.25","_type":"logs"}}
{"uid":"1","register_time":"2015-12-23T12:00:00Z","login_time":"2015-12-25T12:00:00Z"}

其中login-2015.12.23有2条文档,login-2015.12.24有1条,login-2015.12.25有1条。我需要按日期统计当日及之前所有日期的累计文档数,期望结果如下:

{
"hits" : {
    "total" : 4,
    "max_score" : 1.0,
    "hits" : []
  },
  "aggregations" : {
    "group_by_date" : {
      "buckets" : [
        {
          "key_as_string" : "2015-12-23T12:00:00Z",
          "key" : 1450852800000,
          "doc_count" : 2,
          "cumulative_doc_count": {
            "value": 2
          }
        },
        {
          "key_as_string" : "2015-12-24T12:00:00Z",
          "key" : 1450939200000,
          "doc_count" : 1,
          "cumulative_doc_count": {
            "value": 3
          }
        },
        {
          "key_as_string" : "2015-12-25T12:00:00Z",
          "key" : 1451025600000,
          "doc_count" : 1,
          "cumulative_doc_count": {
            "value": 4
          }
        }
      ]
    }
}

即统计2015-12-24时需包含2015-12-23和当日的文档总数。我尝试过使用scripted_metric聚合,但该聚合仅能在当前桶内迭代文档,无法跨桶处理所有数据,现寻求解决方案。


解决方案:使用cumulative_sum聚合

Elasticsearch内置的cumulative_sum聚合专门用于实现跨桶的累计求和,无需自定义脚本,高效且简洁。以下是具体的查询语句:

{
  "query": {"match_all": {}},
  "size": 0,
  "index": "login-*", 
  "aggs": {
    "group_by_date": {
      "date_histogram": {
        "field": "login_time", 
        "calendar_interval": "day", 
        "format": "yyyy-MM-dd'T'HH:mm:ssZ",
        "order": {
          "_key": "asc" 
        }
      },
      "aggs": {
        "cumulative_doc_count": {
          "cumulative_sum": {
            "buckets_path": "_count" 
          }
        }
      }
    }
  }
}

说明

  1. date_histogram聚合会按指定的日期字段(如login_time)将文档按天分组,每个桶自带doc_count字段,表示当日的文档数量。
  2. cumulative_sum聚合通过buckets_path: "_count"引用每个桶的当日文档数,自动累加前面所有桶的数值,得到截止到当日的累计总数。
  3. 查询时指定index: "login-*"可以匹配所有按日期命名的登录索引,无需逐个指定索引名。

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 22:15:27