跳到主要内容

嵌套聚合 nested

Nested Aggregation

一种特殊的单桶聚合,支持聚合嵌套文档。

例如,假设我们有一个products索引,每个product都有resellers列表,每个reseller都有自己的product price。映射可能如下所示:

PUT /products
{
"mappings": {
"product" : {
"properties" : {
"resellers" : {
"type" : "nested",
"properties" : {
"reseller" : { "type" : "text" },
"price" : { "type" : "double" }
}
}
}
}
}
}

resellers 是一个包含嵌套文档的数组。

以下请求添加了一个有两个resellers的product:

PUT /products/_doc/0
{
"name": "LED TV",
"resellers": [
{
"reseller": "companyA",
"price": 350
},
{
"reseller": "companyB",
"price": 500
}
]
}

以下请求返回购买product的最低price:

GET /products/_search
{
"query" : {
"match" : { "name" : "led tv" }
},
"aggs" : {
"resellers" : {
"nested" : {
"path" : "resellers"
},
"aggs" : {
"min_price" : { "min" : { "field" : "resellers.price" } }
}
}
}
}

如上所述, nested aggregation 需要top level documents中嵌套文档的path。然后可以在这些嵌套文档上定义任何类型的聚合。

返回:

{
...
"aggregations": {
"resellers": {
"doc_count": 2,
"min_price": {
"value": 350
}
}
}
}