首页 > 解决方案 > Elastic-search 聚合 top 3 常见结果

问题描述

我的索引数据具有以下结构,我想聚合前 3 个重复次数最多的产品属性,因此前 3 个重复次数最多的产品属性将出现在聚合结果中

  [
    {
        productProperty: "material",
        productValue:[{value: wood},{value: plastic}] ,
    },
    {
        productProperty: "material",
        productValuea:[{value: wood},{value: plastic}] ,
    },
    {
        productProperty: "type",
        productValue:[{value: 26A},{value: 23A}] ,
    },
    {
        productProperty: "type",
        productValue:[{value: 22B},{value: 90C}] ,
    },
    {
        productProperty: "material",
        productValue:[{value: wood},{value: plastic}] ,
    },
    {
        productProperty: "age_rating",
        productValue:[{value: 18},{value: 13}] ,
    }
    ]

下面的查询聚合所有基于 productProperty 但我怎样才能从中获得前 3 个结果

{
  "query": {},
  "aggs": {
    "filtered_product_property": {
      "filter": {
        "bool": {
          "must": []
        }
      },
      "aggs": {
        "aggs": {
          "productProperty": {
            "terms": {
              "field": "productProperty"
            }
          }
        }
      }
    }
  }
}

标签: elasticsearch

解决方案


可以在term aggregation.

{
  "query": {},
  "aggs": {
    "filtered_product_property": {
      "filter": {
        "bool": {
          "must": []
        }
      },
      "aggs": {
        "aggs": {
          "productProperty": {
            "terms": {
              "field": "productProperty", 
             "size" : 3
            }
          }
        }
      }
    }
  }
}

需要指出的是,在某些情况下,术语聚合并不是最准确的。


推荐阅读