ES-聚合操作

  • 所谓 聚合,就是在查询完某些数据之后,进行 group by 等操作,并进行一系列的统计
  • 基本语法如下:
POST /index/_search
{
    "size":0,
    "query":{
        "match_all":{

        }
    },
    "aggs":{
        "group_by_model":{
            "terms":{
                "field":"red"
            }
        }
    }
}

  • 以下是对以上的参数的解释:
  • size:不查询任何数据,因为聚合操作主要是为了统计,查询数据并没有意义
  • match_all:查询所有
  • group_by_model:相当于给 count(*) 起一个别名
  • field:根据哪个字段聚合

统计每个type下的文档数量

  • 对应的 SQL 语句:select type,count(*) from artuicle group by type
POST /index/_search
{
    "query":{
        "match_all":{

        }
    },
    "size":0,
    "aggs":{
        "types_count":{
            "terms":{
                "field":"types"
            }
        }
    }
}

统计阅读量大于100的文档数量

POST /index/_search
{
    "query":{
        "range":{
            "red":{
                "gt":100
            }
        }
    },
    "size":0,
    "aggs":{
        "types_count":{
            "terms":{
                "field":"types"
            }
        }
    }
}

  • 除了统计数量以外,es 还支持 最大值最小值平均值总和 等操作
  • 分别对应着 max、min、avg、sum,只需要把上面的 terms 换成这些关键字即可

bucket和metric

  • bucket:数据的分组
班级 姓名
一年级 BNTang
一年级 李四
二年级 王五
二年级 赵六
二年级 田七
  • 划分出来两个 bucket,一个一年级,一个是二年级
  • 一年级 bucket:包含了 2 个人,BNTang,李四
  • 二年级 bucket:包含了 3 个人,王五,赵六,田七
  • metric:对数据分组执行的统计,比如说 最大值最小值总数平均值
posted @ 2020-10-13 16:13  BNTang  阅读(825)  评论(0编辑  收藏  举报