elasticsearch aggregations by user defined group -
let's have these data in es.
| key | value | |:-----------|------------:| | | 1| | | 2| | b | 2| | c | 3| | d | 4| | e | 5| | e | 5| | f | 6|
i use
{ "from": 0, "size": 0, "query": { "filtered" : { "query" : { "match_all" : {} }, "filter" : { "bool" : { "must" : [ {"terms": {"key": ["a", "b", "c", "d", "e", "f"]}} ] } } } }, "aggs" : { "sum_value" : { "terms" : { "field" : "key" }, "aggs" : { "sum_value" : { "sum" : { "field" : "value" } } } } } }
to sum of same key, results this:
"sum_uv": { "doc_count_error_upper_bound": 0, "sum_other_doc_count": 0, "buckets": [ { "key": "a", "doc_count": 2, "sum_value": { "value": 3 } } .... ] }
but now, want sum elements in same group, example, have mapping data, tells me group information:
group1 = [a, b, c] group2 = [d, e, f] .....
i think need nested aggregation purpose, have no idea this.
the result this:
sum_group1 = 8 sum_group2 = 20 ......
thanks in advance!
there @ least 2 ways of doing this:
- if groups fixed, can add group name each document , aggregate first on group, on values.
- if want more dynamic approach, can use filter + regexp group results. see example here: https://www.elastic.co/blog/quick-tips-regex-filter-buckets
two examples using filters:
1
{ "size": 0, "aggs": { "groups": { "filters": { "filters": { "group1": { "terms": { "key": [ "a","b","c" ] } }, "group2": { "terms": { "key": [ "d","e","f" ] } } } }, "aggs": { "groupsum": { "sum": { "field": "key" } } } } } }
2
{ "size": 0, "query": { "match_all": { } }, "aggs": { "group1": { "filter": { "terms": { "key": [ "a", "b", "c" ] } }, "aggs": { "group1sum": { "sum": { "field": "value" } } } }, "group2": { "filter": { "terms": { "key": [ "d", "e", "f" ] } }, "aggs": { "group2sum": { "sum": { "field": "value" } } } } } }
Comments
Post a Comment