问题
How can I dynamically calculate the average of unique values in elasticsearch?
{ "price" : 10000, "color" : "red" }
{ "price" : 20000, "color" : "red" }
{ "price" : 30000, "color" : "green" }
{ "price" : 15000, "color" : "blue" }
{ "price" : 12000, "color" : "green" }
{ "price" : 20000, "color" : "red" }
{ "price" : 80000, "color" : "red" }
{ "price" : 25000, "color" : "blue" }
In the above data, how can I get the unique values of the "color" field and then the averages for each of the unique "color" fields?
回答1:
Using a terms aggregation to figure out the unique color values and then an avg sub-aggregation would do the trick:
{
"aggs": {
"colors": {
"terms": {
"field": "color"
},
"aggs": {
"average": {
"avg": {
"field": "price"
}
}
}
}
}
}
回答2:
Using Aggregration,you can get your answer:
curl -XGET 'localhost:9200/demo/post/_search?pretty=true' -d
'{
"aggs": {
"aggs_color": {
"terms": {
"field": "color"
},
"aggs": {
"aggs_avg": {
"avg": {
"field": "price"
}
}
}
}
}
}
来源:https://stackoverflow.com/questions/35480358/elasticsearch-calculate-average-of-unique-values