一. ES聚合分析查询的写法
在查询请求体中以aggregations节点按如下语法定义聚合分析:
"aggregations" : {
"<aggregation_name>" : { <!--聚合的名字 -->
"<aggregation_type>" : { <!--聚合的类型 -->
<aggregation_body> <!--聚合体:对哪些字段进行聚合 -->
}
[,"meta" : { [<meta_data_body>] } ]? <!--元 -->
[,"aggregations" : { [<sub_aggregation>]+ } ]? <!--在聚合里面在定义子聚合 -->
}
[,"<aggregation_name_2>" : { ... } ]*<!--聚合的名字 -->
}
说明:aggregations 也可简写为 aggs
二. 指标聚合
1. max min sum avg
{
"size":0,
"aggs": {
"masxAge": {
"max": {
"field": "age"
}
}
}
}
结果:
{
"took": 16,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 3,
"max_score": 0.0,
"hits": []
},
"aggregations": {
"masxAge": {
"value": 35.0
}
}
}
2. 文档计数count
POST /megacorp/employee/_count HTTP/1.1
Host: 192.168.31.233:9200
Content-Type: application/json
{
"query": {
"match": {
"age" : 35
}
}
}
结果:
{
"count": 3,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
}
}
3.去重计数
POST /megacorp/employee/_search?size=0 HTTP/1.1
Host: 192.168.31.233:9200
Content-Type: application/json
{
"aggs": {
"age_count": {
"cardinality": {
"field": "age"
}
}
}
}
结果:
{
"took": 7,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 5,
"max_score": 0.0,
"hits": []
},
"aggregations": {
"age_count": {
"value": 3
}
}
}
4. stats 统计 count max min avg sum 5个值
GET /megacorp/employee/_search?size=0 HTTP/1.1
Host: 192.168.31.233:9200
Content-Type: application/json
{
"aggs": {
"age_stats": {
"stats": {
"field": "age"
}
}
}
}
结果:
{
"took": 5,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 5,
"max_score": 0.0,
"hits": []
},
"aggregations": {
"age_stats": {
"count": 5,
"min": 25.0,
"max": 35.0,
"avg": 32.4,
"sum": 162.0
}
}
}
5.Extends Stats
高级统计,比stats多4个统计结果: 平方和、方差、标准差、平均值加/减两个标准差的区间
GET /megacorp/employee/_search?size=0 HTTP/1.1
Host: 192.168.31.233:9200
Content-Type: application/json
{
"aggs": {
"age_stats": {
"extended_stats": {
"field": "age"
}
}
}
}
结果
{
"took": 9,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 5,
"max_score": 0.0,
"hits": []
},
"aggregations": {
"age_stats": {
"count": 5,
"min": 25.0,
"max": 35.0,
"avg": 32.4,
"sum": 162.0,
"sum_of_squares": 5324.0,
"variance": 15.039999999999964,
"std_deviation": 3.8781438859330586,
"std_deviation_bounds": {
"upper": 40.15628777186612,
"lower": 24.643712228133882
}
}
}
}