嵌套聚合:如何获取聚合对象的属性

时间:2020-07-22 05:45:49

标签: elasticsearch elasticsearch-aggregation elasticsearch-7

我有一个带有嵌套字段映射的“产品”索引。我通过嵌套对象的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"}}
      }
    }
  }
}

1 个答案:

答案 0 :(得分:1)

这是一个很好的开始!!您需要做的就是添加一个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"]
              }
            }
          }
        }
      }
    }
  }
}