子级聚合
children 聚合将父文档与其相关的子文档连接起来。这使得您可以在单个查询中分析不同类型数据之间的关系,而无需运行多个查询并手动合并结果。
示例索引、样本数据和子级聚合查询
例如,如果作者、帖子和评论之间存在父子关系,您可以在单个查询中分析不同数据类型(authors、posts 和 comments)之间的关系。
authors 聚合按 author.keyword 字段对文档进行分组。这使您可以查看与每位作者关联的文档数量。
在每个作者组中,children 聚合检索关联的帖子。这为您提供了每位作者所写文章的细分。
在 posts 聚合中,另一个 children 聚合获取与每个帖子关联的评论。这为您提供了一种查看每个帖子的评论的方法。
在 comments 聚合中,value_count 聚合统计每个帖子的评论数量。这使您可以通过查看每个帖子收到的评论数量来衡量其互动水平。
示例索引
PUT /blog-sample
{
"mappings": {
"properties": {
"type": { "type": "keyword" },
"name": { "type": "keyword" },
"title": { "type": "text" },
"content": { "type": "text" },
"author": { "type": "keyword" },
"post_id": { "type": "keyword" },
"join_field": {
"type": "join",
"relations": {
"author": "post",
"post": "comment"
}
}
}
}
}
示例文档
POST /blog-sample/_doc/1?routing=1
{
"type": "author",
"name": "John Doe",
"join_field": "author"
}
POST /blog-sample/_doc/2?routing=1
{
"type": "post",
"title": "Introduction to UDB-SX",
"content": "UDB-SX is a powerful search and analytics engine...",
"author": "John Doe",
"join_field": {
"name": "post",
"parent": "1"
}
}
POST /blog-sample/_doc/3?routing=1
{
"type": "comment",
"content": "Great article! Very informative.",
"join_field": {
"name": "comment",
"parent": "2"
}
}
POST /blog-sample/_doc/4?routing=1
{
"type": "comment",
"content": "Thanks for the clear explanation.",
"join_field": {
"name": "comment",
"parent": "2"
}
}
示例子级聚合查询
GET /blog-sample/_search
{
"size": 0,
"aggs": {
"authors": {
"terms": {
"field": "name.keyword"
},
"aggs": {
"posts": {
"children": {
"type": "post"
},
"aggs": {
"post_titles": {
"terms": {
"field": "title.keyword"
},
"aggs": {
"comments": {
"children": {
"type": "comment"
},
"aggs": {
"comment_count": {
"value_count": {
"field": "_id"
}
}
}
}
}
}
}
}
}
}
}
}
示例响应
响应应类似于以下示例:
{
"took": 30,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 4,
"relation": "eq"
},
"max_score": null,
"hits": []
},
"aggregations": {
"authors": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": []
}
}
}