嵌套聚合:如何获取聚合对象的属性
Nested aggregation: how to get properties of aggregated object
我有一个带有嵌套字段映射的“产品”索引。我通过嵌套对象的 id 使用嵌套聚合和术语聚合执行搜索查询。如何从存储桶中的嵌套对象获取“title”和“slug”属性?
PUT /products
{
"mappings": {
"properties": {
"categories": {
"type": "nested",
"properties": {
"id": { "type": "long" },
"title": { "type": "text" },
"slug": { "type": "keyword" }
}
}
}
}
}
POST /products/_doc
{
"name": "Acer Aspire 5 Slim Laptop",
"categories": [
{
"id": 1,
"title": "Laptops",
"slug": "/catalog/laptops"
},
{
"id": 2,
"title": "Ultrabooks",
"slug": "/catalog/ultrabooks"
}
]
}
GET /products/_search
{
"query": {
"match": { "name": "acer" }
},
"aggs": {
"categories": {
"nested": {
"path": "categories"
},
"aggs": {
"id": {"terms": {"field": "categories.id"}}
}
}
}
}
这是一个很好的开始!!您只需要像这样添加一个 top_hits
子聚合:
GET /products/_search
{
"query": {
"match": {
"name": "acer"
}
},
"aggs": {
"categories": {
"nested": {
"path": "categories"
},
"aggs": {
"id": {
"terms": {
"field": "categories.id"
},
"aggs": {
"hits": {
"top_hits": {
"size": 1,
"_source": ["categories.title", "categories.slug"]
}
}
}
}
}
}
}
}
我有一个带有嵌套字段映射的“产品”索引。我通过嵌套对象的 id 使用嵌套聚合和术语聚合执行搜索查询。如何从存储桶中的嵌套对象获取“title”和“slug”属性?
PUT /products
{
"mappings": {
"properties": {
"categories": {
"type": "nested",
"properties": {
"id": { "type": "long" },
"title": { "type": "text" },
"slug": { "type": "keyword" }
}
}
}
}
}
POST /products/_doc
{
"name": "Acer Aspire 5 Slim Laptop",
"categories": [
{
"id": 1,
"title": "Laptops",
"slug": "/catalog/laptops"
},
{
"id": 2,
"title": "Ultrabooks",
"slug": "/catalog/ultrabooks"
}
]
}
GET /products/_search
{
"query": {
"match": { "name": "acer" }
},
"aggs": {
"categories": {
"nested": {
"path": "categories"
},
"aggs": {
"id": {"terms": {"field": "categories.id"}}
}
}
}
}
这是一个很好的开始!!您只需要像这样添加一个 top_hits
子聚合:
GET /products/_search
{
"query": {
"match": {
"name": "acer"
}
},
"aggs": {
"categories": {
"nested": {
"path": "categories"
},
"aggs": {
"id": {
"terms": {
"field": "categories.id"
},
"aggs": {
"hits": {
"top_hits": {
"size": 1,
"_source": ["categories.title", "categories.slug"]
}
}
}
}
}
}
}
}