Continue from section 16
9), aggregations (execute aggregation)
Aggregation provides 分组和提取数据
capabilities from data .
The easiest method is substantially equal to the polymerization SQL GROUP BY
and SQL 聚合函数
.
In Elasticsearch, you have the ability to perform a search and return hits (hit results), and at the same time return aggregated results,
separating all hits (hit results) in a response. This is very powerful and effective. You can perform queries and multiple aggregations,
and get their own (any one) return results in one use. Use a concise and simplified API to avoid network round trips.
aggregations query syntax:
"aggregations" : {
"<aggregation_name>" : {
"<aggregation_type>" : {
<aggregation_body>
}
[,"meta" : {
[<meta_data_body>] } ]?
[,"aggregations" : {
[<sub_aggregation>]+ } ]?
}
[,"<aggregation_name_2>" : {
... } ]*
}
Give a chestnut:
- Search for the age distribution and average age of all people whose address contains mill, but do not display the details of these people.
GET /bank/_search
{
"query": {
//查询
"match": {
"address": "mill"
}
},
"aggs": {
//聚合
"ageAgg": {
//年龄分布
"terms": {
"field": "age",
"size": 10 //只取10中聚合的结果
}
},
"ageAvg":{
//平均年龄,基于上一次的结果
"avg": {
"field": "age"
}
},
"balanceAvg":{
//平均薪资
"avg": {
"field": "balance"
}
}
},
"size": 0 //不显示搜索数据,只显示聚合结果
}
aggs,执行聚合。聚合语法如下:
"aggs":{
"ages_name 这次聚合的名字,方便展示在结果集中":{
"AGG-TYPE 聚合的类型(avg,term,terms) ":{
}
}
}
- Complex aggregation: Aggregate by age, and request the average salary of these people in these age groups (using a sub-aggregation)
GET /bank/_search
{
"query": {
"match_all": {
}
},
"aggs": {
"ageAgg": {
"terms": {
//年龄范围分布聚合
"field": "age",
"size": 100//返回100中情况
},
"aggs": {
//基于ageAgg的结果做聚合
"ageAvg": {
"avg": {
//求balance的平均值
"field": "balance"
}
}
}
}
}
}
- Complex aggregation advanced: find out all age distributions, and the average salary of M and F in these age groups, and the overall average new salary of this age group
GET /bank/_search
{
"query": {
"match_all": {
}
},
"aggs": {
//聚合
"ageAgg":{
"terms": {
//年龄分布
"field": "age",
"size": 100
},
"aggs": {
//基于ageAgg做聚合
"genderAgg": {
//性别分布
"terms": {
//文本字段聚合使用keyword进行精确匹配,否则会报错
"field": "gender.keyword",
"size": 10
},
"aggs": {
//基于genderAgg做聚合
"balanceAvg": {
//求性别为M和F的各自的平均薪资
"avg": {
"field": "balance"
}
}
}
},
"ageBalanceAvg":{
//基于ageAgg,求各个年龄段的平均薪资
"avg": {
"field": "balance"
}
}
}
}
}
}
For more aggregation query operations, please refer to the official ES document: Reference Document-search-aggregations
reference:
Getting started with the full-text search engine Elasticsearch