首页 > 解决方案 > 嵌套 JSON 数据上的 Elasticsearch 聚合

问题描述

我必须对 json 数据进行一些聚合。我在 stackoverflow 上看到了多个答案,但对我没有任何帮助。我有多行,在 timeCountry 列中我有一个存储 JSON 对象的数组。键计数,国家名称,s_name。

我必须根据 s_name 找到所有行的总和,示例 - 如果在第一行 timeCountry 包含如下所示的数组

[ {
      "count": 12,
      "country_name": "america",
      "s_name": "us"
    },
    {
      "count": 10,
      "country_name": "new zealand",
      "s_name": "nz"
    },
    {
      "count": 20,
      "country_name": "India",
      "s_name": "Ind"
    }]

第2行数据如下

[{
  "count": 12,
  "country_name": "america",
  "s_name": "us"
  },
  {
  "count": 10,
  "country_name": "South Africa",
  "s_name": "sa"
  },
  {
  "count": 20,
  "country_name": "india",
  "s_name": "ind"
  }]

像这样。

我需要如下结果

[{
        "count": 24,
        "country_name": "america",
        "s_name": "us"
    }, {
        "count": 10,
        "country_name": "new zealand",
        "s_name": "nz"
    },
    {
        "count": 40,
        "country_name": "India",
        "s_name": "Ind"
    }, {
        "count": 10,
        "country_name": "South Africa",
        "s_name": "sa"
    }
]

以上数据仅适用于一行我有多行 timeCountry 是列

我尝试为聚合编写的内容

{
   "query": {
      "match_all": {}
   },
   "aggregations":{
        "records" :{
            "nested":{
                "path":"timeCountry"
            },
            "aggregations":{
                "ids":{
                    "terms":{
                        "field": "timeCountry.country_name"
                    }
                }
            }
        }
   }

}

但它不起作用请帮助

标签: elasticsearchelasticsearch-aggregationelasticsearch-dsl-py

解决方案


我在我的本地弹性集群上尝试了这个,我能够获得嵌套文档的聚合数据。根据您的索引映射,答案可能与我的不同。以下是我尝试用于聚合的 DSL:

{
    "aggs" : {
        "records" : {
            "nested" : {
                "path" : "timeCountry"
            },
            "aggs" : {
                "ids" : { "terms" : {
                    "field" : "timeCountry.country_name.keyword"
                },
               "aggs": {"sum_name": { "sum" : { "field" : "timeCountry.count" } } }
               }
            }
        }
    }
}

以下是我的索引的映射:

{
    "settings" : {
        "number_of_shards" : 1
    },
    "mappings": {
        "agg_data" : {
        "properties" : {
            "timeCountry" : {
                "type" : "nested"
            }
        }
    }
    }
}

推荐阅读