ES 根据查询条件求和sum

最简单的查询求和,类似于SQL: select sum(XX) from table where ;

不需要group by. 也就不需要TermsAggregationBuilder

dsl:

GET /index/base_info/_search 
{
  "aggs": {
    "query_amount": {
      "sum": {
        "field": "num"
      }
    }
  },
  "query": {
      "match": {
     "Id": "abc123"
   }
  }
}

highlevel:

transportClient.prepareSearch()
                .setIndices(Index())
                .setTypes(Type())
                .setQuery(queryBuilder)
                .addAggregation(AggregationBuilders.sum("myNum").field("num"))
                .setFetchSource(false);

        SearchResponse searchResponse = requestBuilder.get();
        Sum num = searchResponse.getAggregations().get("myNum");
        return  num.getValue();

这里的querybuilder就是正常的业务查询设置参数那种。

补充下官网的:文档

Sum Aggregation

single-value metrics aggregation that sums up numeric values that are extracted from the aggregated documents. These values can be extracted either from specific numeric fields in the documents, or be generated by a provided script.

Assuming the data consists of documents representing sales records we can sum the sale price of all hats with:

POST /sales/_search?size=0
{
    "query" : {
        "constant_score" : {
            "filter" : {
                "match" : { "type" : "hat" }
            }
        }
    },
    "aggs" : {
        "hat_prices" : { "sum" : { "field" : "price" } }
    }
}

Copy as cURLView in Console 

Resulting in:

{
    ...
    "aggregations": {
        "hat_prices": {
           "value": 450.0
        }
    }
}

The name of the aggregation (hat_prices above) also serves as the key by which the aggregation result can be retrieved from the returned response.

 

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值