【问题标题】:Nested aggregation: how to get properties of aggregated object嵌套聚合:如何获取聚合对象的属性
【发布时间】:2020-11-11 14:40:32
【问题描述】:

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

【问题讨论】:

    标签: elasticsearch elasticsearch-aggregation elasticsearch-7


    【解决方案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"]
                  }
                }
              }
            }
          }
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 2018-08-06
      相关资源
      最近更新 更多