Elasticsearch 聚合嵌套 JSON 数据

Elasticsearch aggregate on nested JSON data

我必须对 json 数据进行一些汇总。我在 Whosebug 上看到了多个答案,但没有对我有用。 我有多行,在 timeCountry 列中,我有一个存储 JSON 个对象的数组。键数,country_name,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"
    }
]

以上数据只有一行我有多行时间国家是列

我尝试为聚合编写的内容

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

}

但它不起作用请帮助

我在我的本地弹性集群上试过了,我能够获得嵌套文档的聚合数据。根据您的索引映射,答案可能与我的不同。以下是我尝试用于聚合的 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"
            }
        }
    }
    }
}