简介
聚合:英文为Aggregation (ES中简称Aggs),是ES除搜索功能外提供的针对ES数据做统计分析的功能。聚合有助于根据搜索查询提供聚合数据。
聚合查询是数据库中重要的功能特性,ES作为搜索引擎兼数据库,同样提供了强大的聚合分析能力。它基于查询条件来对数据进行分桶、计算的方法。有点类似于SQL中的group by 再加一些函数方法的操作。
注意:text类型是不支持聚合的。
测试数据
# 创建索引 index 和映射 mapping
PUT /friends
{
"mappings": {
"properties": {
"name":{
"type":"keyword"
},
"age":{
"type": "integer"
},
"gender":{
"type": "boolean"
},
"description":{
"type": "text",
"analyzer": "ik_smart"
}
}
}
}
# 放入测试用例
PUT _bulk
{"index":{"_id":1,"_index" : "friends"} }
{"name" : "cfd","age":200,"gender":true,"description":"这个人很搞笑"}
{"index":{"_id":2,"_index" : "friends"} }
{"name" : "cdf","age":100,"gender":true,"description":"这个人很聪明"}
{"index":{"_id":3,"_index" : "friends"} }
{"name" : "fcd","age":50,"gender":true,"description":"这个人很乐观"}
{"index":{"_id":4,"_index" : "friends"} }
{"name" : "fdc","age":25,"gender":true,"description":"这个人很帅气"}
{"index":{"_id":5,"_index" : "friends"} }
{"name" : "dcf","age":10,"gender":true,"description":"这个人很积极"}
{"index":{"_id":6,"_index" : "friends"} }
{"name" : "dfc","age":20,"gender":true,"description":"这个人很喜欢"}
GET /friends/_search
{
"query": {
"match_all": {}
}
}
使用
根据某个字段分组
# 根据某个字段分组 统计数量
GET /friends/_search
{
"query": {
"match_all": {}
},
"aggs": {
"price_group": {
"terms": {
"field": "age"
}
}
}
}
求最大值(最小值)
GET /friends/_search
{
"query": {
"match_all": {}
},
"size": 0,
"aggs": {
"max_price": {
"max": {
"field": "age"
}
}
}
}
GET /friends/_search
{
"query": {
"match_all": {}
},
"size": 0,
"aggs": {
"min_price": {
"min": {
"field": "age"
}
}
}
}
求和(平均值avg)
GET /friends/_search
{
"query": {
"match_all": {}
},
"size": 0,
"aggs": {
"sum_price": {
"sum": {
"field": "age"
}
}
}
}