首页 > 解决方案 > ElasticSearch:条件总和

问题描述

我有包含数量列的记录,可以是负数也可以是正数。我想计算值为正的总量。

我知道我可以使用 来计算总和elastic.NewSumAggregation().Field("quantity"),但我不确定如何仅包含正数行。

任何机构都可以提供帮助吗?谢谢

标签: goelasticsearch

解决方案


添加工作示例

索引示例文档

{
    "quantity": 10
}

{
    "quantity": -10
}

{
    "quantity": 25
}

{
    "quantity": -25
}

搜索查询

{
    "query": {
        "range": {
            "quantity": {. // filter only for positive quantity.
                "gte": 0
            }
        }
    },
    "aggs": {
        "quantity": {
            "sum": {
                "field": "quantity"
            }
        }
    }
}

和搜索结果

 "hits": [
            {
                "_index": "65188985",
                "_type": "_doc",
                "_id": "1",
                "_score": 1.0,
                "_source": {
                    "quantity": 10
                }
            },
            {
                "_index": "65188985",
                "_type": "_doc",
                "_id": "4",
                "_score": 1.0,
                "_source": {
                    "quantity": 25
                }
            }
        ]
    },
    "aggregations": { // note this aggregation part, which is sum of 10 and 25.
        "quantity": {
            "value": 35.0
        }
    }

如果您只想提取聚合部分,请给出size=0查询部分。

{
    "size":0,
    "query": {
        "range": {
            "quantity": {
                "gte": 0
            }
        }
    },
    "aggs": {
        "quantity": {
            "sum": {
                "field": "quantity"
            }
        }
    }
}

以上将输出以下响应

 "aggregations": {
        "quantity": {
            "value": 35.0
        }
    }

推荐阅读