How to Use Sum Aggregation in Elasticsearch
Use the
sum aggregation in Elasticsearch to calculate the total sum of a numeric field across matching documents. It is defined inside the aggs section of your query with the field name specified. The result returns the sum value for that field.Syntax
The sum aggregation is placed inside the aggs part of your Elasticsearch query. You specify the field you want to sum up. The basic structure looks like this:
aggs: The container for aggregations.sum: The aggregation type to calculate the total.field: The numeric field to sum.
json
{
"aggs": {
"total_sum": {
"sum": {
"field": "numeric_field"
}
}
}
}Example
This example shows how to sum the values of the price field in documents that match a query. It returns the total price.
json
{
"query": {
"match_all": {}
},
"aggs": {
"total_price": {
"sum": {
"field": "price"
}
}
}
}Output
{
"aggregations": {
"total_price": {
"value": 12345.67
}
}
}
Common Pitfalls
Common mistakes when using sum aggregation include:
- Using a non-numeric field, which causes errors or zero results.
- Not specifying the
fieldinside thesumaggregation. - Expecting sum aggregation to filter documents; it only sums over matched documents from the query.
Always ensure the field is numeric and exists in your documents.
json
{
"aggs": {
"wrong_sum": {
"sum": {
"field": "non_numeric_field"
}
}
}
}
// Correct usage:
{
"aggs": {
"correct_sum": {
"sum": {
"field": "numeric_field"
}
}
}
}Quick Reference
Use this quick guide to remember sum aggregation basics:
| Concept | Description |
|---|---|
| aggs | Container for all aggregations |
| sum | Aggregation type to calculate total sum |
| field | Numeric field to sum over |
| query | Filters documents before aggregation |
| value | Result key holding the sum |
Key Takeaways
Sum aggregation calculates the total of a numeric field across matched documents.
Always specify the numeric field inside the sum aggregation's field parameter.
Sum aggregation works on documents filtered by the query part of your request.
Using non-numeric fields in sum aggregation leads to errors or zero results.
The sum result is found under the aggregations key in the response.