elasticSearch聚合

当斧头来到树林里的时候,好多树都说,至少它的把手是我们自己人。
ES中的聚合被分为两大类:Metric度量和bucket桶(原谅我英语差,找不到合适的词语.....就用单词来说吧!)。说的通俗点,metric很像SQL中的avg、max、min等方法,而bucket就有点类似group by了。

Sum 求和

1
2
3
"aggs" : {
"intraday_return" : { "sum" : { "field" : "change" } }
}

Min 求最小值

1
2
3
4
5
{
"aggs" : {
"min_price" : { "min" : { "field" : "price" } }
}
}

cardinality 求唯一值,即不重复的字段有多少

1
2
3
4
5
6
7
8
9
{
"aggs" : {
"author_count" : {
"cardinality" : {
"field" : "author"
}
}
}
}

一次性返回所有指标,count,min,max,avg,sum

1
2
3
4
5
{
"aggs" : {
"grades_stats" : { "stats" : { "field" : "total_price" } }
}
}

先过滤后聚合

1
2
3
4
5
6
7
8
9
10
{
"aggs" : {
"paid_order" : {
"filter" : { "term": { "status_code": "paid" } },
"aggs" : {
"avg_price" : { "avg" : { "field" : "total_price" } }
}
}
}
}

去除结果中的产品

1
2
3
4
5
6
7
8
9
10
11
{
"size":0,
"aggs" : {
"paid_order" : {
"filter" : { "term": { "status_code": "paid" } },
"aggs" : {
"avg_price" : { "avg" : { "field" : "total_price" } }
}
}
}
}

使用区间统计

1
2
3
4
5
6
7
8
9
10
{
"aggs" : {
"prices" : {
"histogram" : {
"field" : "total_price",
"interval" : 1000
}
}
}
}

日期过滤

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
"aggs": {
"range": {
"date_range": {
"field": "created_at",
"format": "MM-yyy",
"ranges": [
{ "to": "now-10M/M" },
{ "from": "now-10M/M" }
]
}
}
}
}