Агрегация обратного вложенного уровня
Специальная агрегация по одной группе, которая позволяет агрегировать по родительским документам из вложенных документов. По сути, эта агрегация может выйти за пределы структуры вложенных блоков и связаться с другими вложенными структурами или корневым документом, что позволяет встраивать другие агрегации, которые не являются частью вложенного объекта, в вложенную агрегацию.
Агрегация reverse_nested должна быть определена внутри агрегации nested.
Параметры:
-
path- Определяет, к какому вложенному объекту должно происходить присоединение. По умолчанию значение пустое, что означает присоединение к корневому/главному уровню документа. Путь не может содержать ссылку на поле вложенного объекта, которое выходит за пределы вложенной структуры агрегацииnested, в которой находитсяreverse_nested.
Например, предположим, что у нас есть индекс для системы отслеживания тикетов с проблемами и комментариями. Комментарии встроены в документы проблем в качестве вложенных документов. Структура отображения может выглядеть так:
resp = client.indices.create(
index="issues",
mappings={
"properties": {
"tags": {
"type": "keyword"
},
"comments": {
"type": "nested",
"properties": {
"username": {
"type": "keyword"
},
"comment": {
"type": "text"
}
}
}
}
},
)
print(resp) response = client.indices.create(
index: 'issues',
body: {
mappings: {
properties: {
tags: {
type: 'keyword'
},
comments: {
type: 'nested',
properties: {
username: {
type: 'keyword'
},
comment: {
type: 'text'
}
}
}
}
}
}
)
puts response const response = await client.indices.create({
index: "issues",
mappings: {
properties: {
tags: {
type: "keyword",
},
comments: {
type: "nested",
properties: {
username: {
type: "keyword",
},
comment: {
type: "text",
},
},
},
},
},
});
console.log(response); PUT /issues
{
"mappings": {
"properties": {
"tags": { "type": "keyword" },
"comments": {
"type": "nested",
"properties": {
"username": { "type": "keyword" },
"comment": { "type": "text" }
}
}
}
}
} |
|
Следующие агрегации вернут имена пользователей самых активных комментирующих пользователей, которые оставили комментарии, и для каждого активного комментатора — самые популярные теги проблем, по которым пользователь оставил комментарии:
resp = client.search(
index="issues",
query={
"match_all": {}
},
aggs={
"comments": {
"nested": {
"path": "comments"
},
"aggs": {
"top_usernames": {
"terms": {
"field": "comments.username"
},
"aggs": {
"comment_to_issue": {
"reverse_nested": {},
"aggs": {
"top_tags_per_comment": {
"terms": {
"field": "tags"
}
}
}
}
}
}
}
}
},
)
print(resp) response = client.search(
index: 'issues',
body: {
query: {
match_all: {}
},
aggregations: {
comments: {
nested: {
path: 'comments'
},
aggregations: {
top_usernames: {
terms: {
field: 'comments.username'
},
aggregations: {
comment_to_issue: {
reverse_nested: {},
aggregations: {
top_tags_per_comment: {
terms: {
field: 'tags'
}
}
}
}
}
}
}
}
}
}
)
puts response const response = await client.search({
index: "issues",
query: {
match_all: {},
},
aggs: {
comments: {
nested: {
path: "comments",
},
aggs: {
top_usernames: {
terms: {
field: "comments.username",
},
aggs: {
comment_to_issue: {
reverse_nested: {},
aggs: {
top_tags_per_comment: {
terms: {
field: "tags",
},
},
},
},
},
},
},
},
},
});
console.log(response); GET /issues/_search
{
"query": {
"match_all": {}
},
"aggs": {
"comments": {
"nested": {
"path": "comments"
},
"aggs": {
"top_usernames": {
"terms": {
"field": "comments.username"
},
"aggs": {
"comment_to_issue": {
"reverse_nested": {},
"aggs": {
"top_tags_per_comment": {
"terms": {
"field": "tags"
}
}
}
}
}
}
}
}
}
} Как вы можете видеть выше, агрегация reverse_nested помещена в агрегацию nested, так как это единственное место в DSL, где можно использовать агрегацию reverse_nested. Её единственная цель — связаться с родительским документом на более высоком уровне вложенной структуры.
| Агрегация |
Возможный фрагмент ответа:
{
"aggregations": {
"comments": {
"doc_count": 1,
"top_usernames": {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets": [
{
"key": "username_1",
"doc_count": 1,
"comment_to_issue": {
"doc_count": 1,
"top_tags_per_comment": {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets": [
{
"key": "tag_1",
"doc_count": 1
}
...
]
}
}
}
...
]
}
}
}
}
© 2023-2025 Elasticsearch
As of September 2024, Elasticsearch is available under a choice of three licenses: the Server Side Public License (SSPL), the Elastic License, or the AGPLv3 (OSI approved).
Elasticsearch and the Elasticsearch logo are trademarks of Elasticsearch B.V., registered in the U.S. and in other countries.
https://www.elastic.co/guide/en/elasticsearch/reference/8.17/search-aggregations-bucket-reverse-nested-aggregation.html