首页 > 解决方案 > 如何在 Elasticsearch 中使用按国家/地区的 Max 聚合来获取最大值和 id

问题描述

按国家/地区获取最大值,但我需要有关最大值 ID 的其他信息。我尝试了很多方法,但我不知道如何获取。

{

"aggs" : {
    "country_groups" : {
        "terms" : { "field" : "country.keyword",
                "size":30000
        },
      "aggs":{

            "max_price":{
            "max": { "field" : "video_count"}
           }

        }

} }

}

标签: elasticsearch

解决方案


根据id字段的类型(数字或字符串),您有两种方法。

如果您查看下面的查询,如果您的查询id是数字,您可以执行与 相同的操作video_count,即使用max度量聚合(请参阅 参考资料max_id_num)。

但是,如果您的id字段是字符串,您可以利用top_hits聚合并按顺序对其进行descending排序(请参阅 参考资料max_id_str)。

{
  "aggs": {
    "country_groups": {
      "terms": {
        "field": "country.keyword",
        "size": 30000
      },
      "aggs": {
        "max_price_and_id": {
          "top_hits": {
            "size": 1,
            "sort": {
              "video_count": "desc"
            },
            "_source": ["channel_id", "video_count"]
          }
        }
      }
    }
  }
}

推荐阅读