子项
children
聚合是一种桶聚合,它根据索引中定义的父子关系,创建一个包含子文档的单个桶。
children
聚合与 join 字段类型 配合使用,以聚合与父文档关联的子文档。
children
聚合识别与特定子关系名称匹配的子文档,而 parent
聚合 则识别具有匹配子文档的父文档。两种聚合都将子关系名称作为输入。
参数
children
聚合接受以下参数。
参数 | 必需/可选 | 数据类型 | 描述 |
---|---|---|---|
type | 必需 | 字符串 | join 字段中子类型的名称。这用于标识要使用的父子关系。 |
示例
以下示例构建了一个包含三名员工的小型公司数据库。每条员工记录都与父部门记录具有子 join
关系。
首先,创建一个包含 join
字段的 company
索引,该字段将部门(父)映射到员工(子)。
PUT /company
{
"mappings": {
"properties": {
"join_field": {
"type": "join",
"relations": {
"department": "employee"
}
},
"department_name": {
"type": "keyword"
},
"employee_name": {
"type": "keyword"
},
"salary": {
"type": "double"
},
"hire_date": {
"type": "date"
}
}
}
}
接下来,填充包含三个部门和三名员工的数据。父子分配如下表所示。
部门(父) | 员工(子) |
---|---|
会计部 | Abel Anderson , Betty Billings |
工程部 | Carl Carter |
人力资源部 | 无 |
routing
参数确保父文档和子文档都存储在同一个分片上,这是 OpenSearch 中父子关系正常工作所必需的。
POST _bulk?routing=1
{ "create": { "_index": "company", "_id": "1" } }
{ "type": "department", "department_name": "Accounting", "join_field": "department" }
{ "create": { "_index": "company", "_id": "2" } }
{ "type": "department", "department_name": "Engineering", "join_field": "department" }
{ "create": { "_index": "company", "_id": "3" } }
{ "type": "department", "department_name": "HR", "join_field": "department" }
{ "create": { "_index": "company", "_id": "4" } }
{ "type": "employee", "employee_name": "Abel Anderson", "salary": 120000, "hire_date": "2024-04-04", "join_field": { "name": "employee", "parent": "1" } }
{ "create": { "_index": "company", "_id": "5" } }
{ "type": "employee", "employee_name": "Betty Billings", "salary": 140000, "hire_date": "2023-05-05", "join_field": { "name": "employee", "parent": "1" } }
{ "create": { "_index": "company", "_id": "6" } }
{ "type": "employee", "employee_name": "Carl Carter", "salary": 140000, "hire_date": "2020-06-06", "join_field": { "name": "employee", "parent": "2" } }
以下请求查询所有部门,然后筛选出名为 Accounting
的部门。接着,它使用 children
聚合来选择与 Accounting
部门具有子关系的两个文档。最后,avg
子聚合返回 Accounting
员工的平均工资。
GET /company/_search
{
"size": 0,
"query": {
"bool": {
"filter": [
{
"term": {
"join_field": "department"
}
},
{
"term": {
"department_name": "Accounting"
}
}
]
}
},
"aggs": {
"acc_employees": {
"children": {
"type": "employee"
},
"aggs": {
"avg_salary": {
"avg": {
"field": "salary"
}
}
}
}
}
}
示例响应
响应返回选定的部门桶,查找该部门的 employee
类型子文档,并计算他们的平均工资 avg
。
{
"took": 379,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": null,
"hits": []
},
"aggregations": {
"acc_employees": {
"doc_count": 2,
"avg_salary": {
"value": 110000
}
}
}
}