filter过滤+聚合分析
需求: 统计价格大于1200的电视的平均价格
请求:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22GET tvs/sales/_search
{
"size": 0,
"query": {
"constant_score": {
"filter": {
"range": {
"price": {
"gte": 1200
}
}
}
}
},
"aggs": {
"avg_of_price": {
"avg": {
"field": "price"
}
}
}
}
返回值:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19{
"took": 15,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 7,
"max_score": 0,
"hits": []
},
"aggregations": {
"avg_of_price": {
"value": 2885.714285714286
}
}
}
跟搜索聚合的结合使用其实是一样的,就是把match换成了filter
bucket filter
先来看一个请求:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45GET tvs/sales/_search
{
"size": 0,
"query": {
"term": {
"brand": {
"value": "长虹"
}
}
},
"aggs": {
"recent_150d": {
"filter": {
"range": {
"sold_date": {
"gte": "now-150d"
}
}
},
"aggs": {
"recent_150d_avg_price": {
"avg": {
"field": "price"
}
}
}
},
"recent_140d":{
"filter": {
"range": {
"sold_date": {
"gte": "now-140d"
}
}
},
"aggs": {
"recent_140d_avg_price": {
"avg": {
"field": "price"
}
}
}
}
}
}
先是query去搜索数据,过滤出只是长虹牌的数据,然后下面的aggs就是针对搜索结果的聚合, 然后每一个聚合分析里面有一个filter和aggs, filter呢,是用来过滤数据的,他是只针对这一个聚合去过滤的,然后filter下面aggs是再对filter过滤后的数据进行聚合分析.
每组聚合分析里面的数据,都是在query的结果上去过滤的,互不影响