ElasticSearch - 前几天的总和

时间:2014-09-22 16:47:17

标签: elasticsearch sum aggregation

我需要按天(恰好在这一天)和当天的总价值(这一天之前的所有值的总和,包括今天的值)总结所有值。

我的代码:

curl -XGET http://localhost:9200/tester/test/_search?pretty=true -d '
{
    "size": 0,
    "aggs" : {
        "articles_over_time" : {
            "date_histogram" : {
                "field" : "date",
                "interval" : "month"
            },
               "aggs": {
                  "value": {
                     "sum": {
                        "field": "my.value"
                     }
                  }
            }
        }
    }
}
'

输出:

{
  "took" : 7,
  "timed_out" : false,
  "_shards" : {...},
  "hits" : {...},
  "aggregations" : {
    "articles_over_time" : {
      "buckets" : [ {
        "key_as_string" : "2014-02-01T00:00:00.000Z",
        "key" : 1391212800000,
        "doc_count" : 36,
        "value" : {
          "value" : 84607.0
        }
      }, {
        "key_as_string" : "2014-03-01T00:00:00.000Z",
        "key" : 1393632000000,
        "doc_count" : 79,
        "value" : {
          "value" : 268928.0
        }
      }, 
      ... ]
    }
  }
}

此代码为我提供了第一个 - 每天汇总所有值(恰好在这一天) 我该怎么办第二个 - 今天的总价值(这一天之前所有价值的总和,包括这一天的价值)

我需要什么:

{
  "took" : 7,
  "timed_out" : false,
  "_shards" : {...},
  "hits" : {...},
  "aggregations" : {
    "articles_over_time" : {
      "buckets" : [ {
        "key_as_string" : "2014-02-01T00:00:00.000Z",
        "key" : 1391212800000,
        "doc_count" : 36,
        "value" : {
          "value" : 84607.0
        },
        "total" : {
          "value" : 84607.0
        },
      }, {
        "key_as_string" : "2014-03-01T00:00:00.000Z",
        "key" : 1393632000000,
        "doc_count" : 79,
        "value" : {
          "value" : 268928.0
        },
        "total" : {
          "value" : 353535.0 /// 84607.0 + 268928.0
        }
      }, 
      ... ]
    }
  }
}

1 个答案:

答案 0 :(得分:0)

这是因为您的第二个聚合嵌套在“articles_over_time”部分吗?

以下是否有帮助?如果您改为:

curl -XGET http://localhost:9200/tester/test/_search?pretty=true -d '
{
    "size": 0,
    "aggs" : {
        "articles_over_time" : {
            "date_histogram" : {
                "field" : "date",
                "interval" : "month"
            },
            "aggs": {
                "value": {
                    "sum": {
                        "field": "my.value"
                    }
                }
            }
        }
    }
} 

要:

curl -XGET http://localhost:9200/tester/test/_search?pretty=true -d '
{
    "size": 0,
    "aggs" : {
        "articles_over_time" : {
            "date_histogram" : {
                "field" : "date",
                "interval" : "month"
            }
        },
        "value": {
            "sum": {
                "field": "my.value"
            }
        }
    }
}