Elasticsearch查询3(过滤和聚合)

数据集合
Elasticsearch查询3(过滤和聚合) - chy2z - 黑暗行动
 主要讲过滤和统计聚合

//过滤 查询年龄22和32岁之间的
GET /mydb/_search
{
"query": {
"bool": {
"must": { "match_all": {} },
"filter": {
"range": {
"age": {
"gte": 29,
"lte": 32
}
}
}
}
}
}

//查询结果
"hits" : {
"total": 1,
"max_score": 1,
"hits": [
{
"_index": "mydb",
"_type": "external",
"_id": "1",
"_score": 1,
"_source": {
"name": "jack",
"age": 31,
"date": "2018-04-12 12:01:01"
}
}
]
}

//统计 按照年龄聚合并根据统计数量排序
GET /mydb/_search
{
"aggs": {
"结果": {
"terms": {
"field": "age",
"order": [
{
"_count": "asc"
}
],
"size": 10
}
}
},
"size": 0
}

//查询结果
"aggregations" : {
"结果": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": 22,
"doc_count": 1
},
{
"key": 31,
"doc_count": 1
},
{
"key": 100,
"doc_count": 1
},
{
"key": 28,
"doc_count": 7
}
]
}
}


//统计 按照名称统计数量,并计算平均年龄和按平均年龄排序
GET /mydb/_search
{
"size": 0,
"aggs": {
"结果": {
"terms": {
"field": "name.keyword",
"order": [
{
"平均年龄": "asc"
}
]
},
"aggs": {
"平均年龄": {
"avg": {
"field": "age"
}
}
}
}
}
}

//查询结果
"aggregations" : {
"结果": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "王明坤",
"doc_count": 1,
"平均年龄": {
"value": 22
}
},
{
"key": "cheng hong fei",
"doc_count": 1,
"平均年龄": {
"value": 28
}
},
.....省略部分记录.....
,
{
"key": "jack",
"doc_count": 2,
"平均年龄": {
"value": 29.5
}
},
{
"key": "王鹏",
"doc_count": 1,
"平均年龄": {
"value": 100
}
}
]
}
}

//统计 按年龄区间分组 并在每个年龄区间 按照姓名分组并计算平均年龄
GET /mydb/_search
{
"size": 0,
"aggs": {
"年龄分组": {
"range": {
"field": "age",
"ranges": [
{
"from": 20,
"to": 28
},
{
"from": 28,
"to": 35
},
{
"from": 35,
"to": 101
}
]
},
"aggs": {
"姓名分组": {
"terms": {
"field": "name.keyword"
},
"aggs": {
"average_balance": {
"avg": {
"field": "age"
}
}
}
}
}
}
}
}

//查询结果
"aggregations" : {
"年龄分组": {
"buckets": [
{
"key": "20.0-28.0",
"from": 20,
"to": 28,
"doc_count": 1,
"姓名分组": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "王明坤",
"doc_count": 1,
"average_balance": {
"value": 22
}
}
]
}
},
{
"key": "28.0-35.0",
"from": 28,
"to": 35,
"doc_count": 8,
"姓名分组": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "jack",
"doc_count": 2,
"average_balance": {
"value": 29.5
}
},
.....省略部分内容.....
,
{
"key": "王明",
"doc_count": 1,
"average_balance": {
"value": 28
}
}
]
}
},
{
"key": "35.0-101.0",
"from": 35,
"to": 101,
"doc_count": 1,
"姓名分组": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "王鹏",
"doc_count": 1,
"average_balance": {
"value": 100
}
}
]
}
}
]
}
}

猜你喜欢

转载自blog.csdn.net/chy2z/article/details/80104198