聚合初体验
GET /cars/transactions/_search
{
"size" : 0, //设置此处可以提高查询速度
"aggs" : { //aggregations相同效果
"popular_colors" : { //自定义聚合名称
"terms" : {
"field" : "color"
}
}
}
}
得到的结果:
{
...
"hits": {
"hits": []
},
"aggregations": {
"popular_colors": { //自定义的名称
"buckets": [
{
"key": "red",
"doc_count": 4 //聚合的数量
},
{
"key": "blue",
"doc_count": 2
},
{
"key": "green",
"doc_count": 2
}
]
}
}
}
添加度量指标
例如想查看汽车的平均价格
GET /cars/transactions/_search
{
"size" : 0,
"aggs": {
"colors": {
"terms": {
"field": "color"
},
"aggs": {
"avg_price": { //自定义度量名称
"avg": { //ES聚合度量字段,此处是平均值的度量
"field": "price" //计算价格的平均值
}
}
}
}
}
}
得到的结果:
{
...
"aggregations": {
"colors": {
"buckets": [
{
"key": "red",
"doc_count": 4, //聚合的数量
"avg_price": {
"value": 32500 //度量的值
}
},
{
"key": "blue",
"doc_count": 2,
"avg_price": {
"value": 20000
}
},
{
"key": "green",
"doc_count": 2,
"avg_price": {
"value": 21000
}
}
]
}
}
...
}