文章目录
前言
这篇文档就简单记录哈ES中的聚合分析,包括指标聚合、桶聚合、管道聚合。其实就是数据库中的各类分析函数,比如max()、min()、avg()、group by、having等等。主要应用在一些统计分析业务中。
一、指标聚合
1、统计最大值:Max Aggregation
查询建筑最高的楼层:
GET /building_info/_search
{
"aggs": {
"max_floor": {
"max": {
"field": "floor"
}
}
}
}
查询结果如下:

如果字段不存在:
GET /building_info/_search
{
"aggs": {
"max_floor": {
"max": {
"field": "floor1",
"missing": 6
}
}
}
}
如果某个文档中缺少 floor1字段,则设置该字段的值为 6。
也可以通过脚本来查询最大值:
GET /building_info/_search
{
"aggs": {
"max_floor": {
"max": {
"script": {
"source": "if(doc['floor'].size()!=0){doc.floor.value}"
}
}
}
}
}
使用脚本时,可以先通过 doc['floor'].size()!=0 去判断文档是否有对应的属性。
2、统计最小值:Min Aggregation
统计最小值,用法和 Max Aggregation 基本一致:
GET /building_info/_search
{
"aggs": {
"min_floor": {
"min": {
"field": "floor",
"missing": 6
}
}
}
}
脚本:
GET /building_info/_search
{
"aggs": {
"min_floor": {
"min": {
"script": {
"source": "if(doc['floor'].size()!=0){doc.floor.value}"
}
}
}
}
}
3、统计平均值:Avg Aggregation
统计平均值:
GET /building_info/_search
{
"aggs": {
"avg_floor": {
"avg": {
"field": "floor"
}
}
}
}
GET /building_info/_search
{
"aggs": {
"avg_floor": {
"avg": {
"script": {
"source": "if(doc['floor'].size()!=0){doc.floor.value}"
}
}
}
}
}
4、求和:Sum Aggregation
求和:
GET /building_info/_search
{
"aggs": {
"sum_floor": {
"sum": {
"field": "floor"
}
}
}
}
GET /building_info/_search
{
"aggs": {
"sum_floor": {
"sum": {
"script": {
"source": "if(doc['floor'].size()!=0){doc.floor.value}"
}
}
}
}
}
5、Cardinality Aggregation
cardinality aggregation 用于基数统计。类似于 SQL 中的 distinct count(0)。
text 类型是分析型类型,默认是不允许进行聚合操作的,如果相对 text 类型进行聚合操作,需要设置其 fielddata 属性为 true,这种方式虽然可以使 text 类型进行聚合操作,但是无法满足精准聚合,如果需要精准聚合,可以设置字段的子域为 keyword。
- 1、方式一:
定义 books 索引:
PUT books
{
"mappings": {
"properties": {
"name":{
"type": "text",
"analyzer": "ik_max_word"
},
"publish":{
"type": "text",
"analyzer": "ik_max_word",
"fielddata": true
},
"type":{
"type": "text",
"analyzer": "ik_max_word"
}

最低0.47元/天 解锁文章
1979

被折叠的 条评论
为什么被折叠?



