Problem:
Give code to demo Sum, Avg, Min, Max, Count and Cardinality metric aggregations.
Solution Summary:
We can use the metric aggregations sum, avg, min, max, value_count and cardinality.
Prerequisites:
Set up accounts index from accounts.json as explained in the link.
Solution Steps:
Case 1 - Sum Aggregation
GET accounts/_search
{
"aggregations" : {
"balance_total" : {
"sum" : {
"field":"balance"
}
}
},
"size": 0
}
Note:
-
Added size = 0 to see only aggregation data. Otherwise documents equal to the size (10 by default) will be returned along with aggregation result.
-
"balance_total" is just an arbitraty name and ES uses the same in the response as well.
-
Average aggregation (avg) is similar; just replace "sum" with "avg".
-
We may also use "aggs" instead of "aggregations".
Response:
{
"took": 4,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 1000,
"max_score": 0,
"hits": []
},
"aggregations": {
"balance_total": {
"value": 25714837
}
}
}
Case 2 - Sum, Avg, Min, Max in single request
GET accounts/_search
{
"aggregations" : {
"balance_total" : {
"sum" : {
"field":"balance"
}
},
"balance_average" : {
"avg" : {
"field":"balance"
}
},
"balance_min" : {
"min" : {
"field":"balance"
}
},
"balance_max" : {
"max" : {
"field":"balance"
}
}
},
"size": 0
}
Response will have:
...
"aggregations": {
"balance_min": {
"value": 1011
},
"balance_max": {
"value": 49989
},
"balance_average": {
"value": 25714.837
},
"balance_total": {
"value": 25714837
}
}
Case 3 - Total number of accounts using value_count
GET accounts/_search
{
"aggregations" : {
"total_count" : {
"value_count" : {
"field":"_id"
}
}
},
"size": 0
}
Case 4 - Total number of unique states
GET accounts/_search
{
"aggregations" : {
"state_cardinality" : {
"cardinality" : {
"field":"state.keyword"
}
}
},
"size": 0
}
Note: Cardinality aggregation may return approximate results. However, you can increase the accuracy by sacrificing some performance.
Recent comments