使用场景,对于数据库中所有的es索引,如果需要对于结构化的数据进行聚合,例如根据书目的分类,书目的出版社等进行聚合
语法:
POST /book/_search
{
"size": 0, #不包含文档结果,只返回聚合结果
"aggs": {
"categoryaggs": { #聚合名称,可自定义
"terms": { #聚合类型,由于书目分类为keyword类型,因此使用term
"field": "category", #以书目的分类进行聚合
"size": 10 #期望返回的聚合结果数量
}
}
}
}
查询结果:
{
"took" : 2,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 7,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
},
"aggregations" : {
"categoryaggs" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [ #聚合结果
{
"key" : "科幻",
"doc_count" : 5
},
{
"key" : "物理",
"doc_count" : 4
},
{
"key" : "人文",
"doc_count" : 3
},
{
"key" : "大气",
"doc_count" : 1
},
{
"key" : "宇宙",
"doc_count" : 1
},
{
"key" : "文学",
"doc_count" : 1
},
{
"key" : "科学",
"doc_count" : 1
}
]
}
}
}
POST /book/_search
{
"size": 0,
"aggs": {
"categoryaggs": {
"terms": {
"field": "category",
# order默认是但对于聚合结果降序排序。这里指定排序字段和排序类型
"order": {
"_count": "asc"
},
"size": 10
}
}
}
}
查询结果:
{
"took" : 6,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 7,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
},
"aggregations" : {
"categoryaggs" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "大气",
"doc_count" : 1
},
{
"key" : "宇宙",
"doc_count" : 1
},
{
"key" : "文学",
"doc_count" : 1
},
{
"key" : "科学",
"doc_count" : 1
},
{
"key" : "人文",
"doc_count" : 3
},
{
"key" : "物理",
"doc_count" : 4
},
{
"key" : "科幻",
"doc_count" : 5
}
]
}
}
}
#聚合查询
POST /book/_search
{
"size": 0,
#限定查询title包含‘三体’的文档
"query": {
"match": {
"title": "三体"
}
},
"aggs": {
"categoryaggs": {
"terms": {
"field": "category",
"order": {
"_count": "asc"
},
"size": 10
}
}
}
}
查询结果:
{
"took" : 9,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 3,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
},
"aggregations" : {
"categoryaggs" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "人文",
"doc_count" : 1
},
{
"key" : "宇宙",
"doc_count" : 1
},
{
"key" : "文学",
"doc_count" : 1
},
{
"key" : "物理",
"doc_count" : 1
},
{
"key" : "科幻",
"doc_count" : 3
}
]
}
}
}