- ES 聚合分析的預設作用範圍是query的查詢結果集
-
同時 ES 還支援以下方式改變聚合的作用範圍
- Filter
- Post_Filter
-
Global
# Query POST employees/_search { "size": 0, "query": { "range": { "age": { "gte": 20 } } }, "aggs": { "jobs": { "terms": { "field":"job.keyword" } } } }
Filter
#Filter
POST employees/_search
{
"size": 0,
"aggs": {
"older_person": {
"filter":{
"range":{
"age":{
"from":35
}
}
},
"aggs":{
"jobs":{
"terms": {
"field":"job.keyword"
}
}
}},
"all_jobs": {
"terms": {
"field":"job.keyword"
}
}
}
}
Post_Filter
- 是對聚合分析後的文件進行再次過濾
- Size 無需設定為0
- 使用場景
- 一條語句,獲取聚合資訊 + 獲取符合條件的文件
#Post field. 一條語句,找出所有的job型別。還能找到聚合後符合條件的結果
POST employees/_search
{
"aggs": {
"jobs": {
"terms": {
"field": "job.keyword"
}
}
},
"post_filter": {
"match": {
"job.keyword": "Dev Manager"
}
}
}
Global
#global
POST employees/_search
{
"size": 0,
"query": {
"range": {
"age": {
"gte": 40
}
}
},
"aggs": {
"jobs": {
"terms": {
"field":"job.keyword"
}
},
"all":{
"global":{},//Golbal,無視query,對全部文件進行統計
"aggs":{
"salary_avg":{
"avg":{
"field":"salary"
}
}
}
}
}
}
排序
- 指定order,按照count和key 排序
- 預設情況,按照count降序排序
- 指定size,就能返回相應的桶
#排序 order #count正序 and key倒敘 POST employees/_search { "size": 0, "query": { "range": { "age": { "gte": 20 } } }, "aggs": { "jobs": { "terms": { "field": "job.keyword", "order": [ { "_count": "asc" }, { "_key": "desc" } ] } } } }
- 基於子聚合的數值進行排序
POST employees/_search { "size": 0, "aggs": { "jobs": { "terms": { "field": "job.keyword", "order": [ { "avg_salary": "desc" } ] }, "aggs": { "avg_salary": { "avg": { "field": "salary" } } } } } }
- 使用子聚合,Aggregation name
POST employees/_search { "size": 0, "aggs": { "jobs": { "terms": { "field": "job.keyword", "order": [ { "stats_salary.min": "desc" } ] }, "aggs": { "stats_salary": { "stats": { "field": "salary" } } } } } }
本作品採用《CC 協議》,轉載必須註明作者和本文連結