【问题标题】:Elasticsearch aggregate on nested JSON data嵌套 JSON 数据上的 Elasticsearch 聚合
【发布时间】:2019-11-19 04:29:14
【问题描述】:

我必须对 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"
                    }
                }
            }
        }
   }

}

但它不起作用请帮助

【问题讨论】:

    标签: elasticsearch elasticsearch-aggregation elasticsearch-dsl-py


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2018-01-12
      • 2021-12-14
      • 2015-11-18
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 2017-09-13
      • 1970-01-01
      相关资源
      最近更新 更多