【问题标题】:Elasticsearch: sum of each element of arrayElasticsearch:数组每个元素的总和
【发布时间】:2014-05-05 15:10:58
【问题描述】:

我正在尝试使用弹性搜索聚合来“合并”基于一组过滤器的整数数组。我的文件看起来像:

{
  "arr": [5, 4, 3, 2, 1],
  "name": "test"
}
{
  "arr": [4, 3, 2, 1, 0],
  "name": "test"
}
{
  "arr": [1, 0, 0, 0, 0],
  "name": "test"
}

我想用一个聚合(或者其他一些es方法)来返回

{
  "arr": [10, 7, 5, 3, 1]
}

最接近的聚合是

{
  "size":0,
  "aggs": {
    "sum_by_index": {
        "filter": {
          "terms": {
            "name": ["test"]
          }
        }
      },
      "aggs": {
        "names": {
          "terms": {
            "field": "name"
          },
          "aggs": {
            "arrs": {
              "terms": {
                "field": "arr"
              }
            }
          }
        }
      }
    }
  }
}

但这会导致数组中每个 value 的总和,我想要数组中每个 index 的总和。有人想吗?

【问题讨论】:

  • 你可以使用脚本字段
  • @phoet,脚本字段似乎是这样做的方法。问题是当我在脚本中使用 doc.arr.values 时,它似乎只响应数组中的 distinct 值。我似乎找不到任何关于如何在脚本中获取完整数组的文档?
  • @cmwright 我在使用doc 时也面临同样的问题。虽然有一个选项可以使用_source 来实现这一点,它会带来正确的结果。我已经在回答中指定了这一点。但我不想使用_source。在使用doc 时,您是否能够确定问题的原因。
  • @Richa 不幸的是我已经解决了这个问题,但它并不漂亮。我最终使我的文档看起来像"arr": {"1": 10, "2": 5, "3": 4, etc... 并将这些元素相加。虽然这可行,但它使用了额外的空间并且不太理想。如果您以更好的方式解决,请告诉我,我将非常感激。
  • @cmwright 我没听懂你。现在你的数组是一个内部对象?是这样吗?你现在用的是什么脚本?

标签: elasticsearch


【解决方案1】:

您可以在脚本中使用_source 来实现相同的功能。默认支持groovy

 "script" : "_source.arr?.sum(0)"

【讨论】:

    猜你喜欢
    • 2017-05-26
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 2016-07-20
    • 1970-01-01
    • 1970-01-01
    • 2015-09-20
    相关资源
    最近更新 更多