最简单的查询求和,类似于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
A 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.