【问题标题】:How to use aggregation value on document update using script in Elasticsearch如何使用 Elasticsearch 中的脚本在文档更新中使用聚合值
【发布时间】:2021-02-02 11:52:22
【问题描述】:

我正在尝试使用脚本更新基于 id 的文档字段。该字段的值应为 MAX(field) * 2。例如考虑以下索引

PUT /my-index
{
  "mappings": {
    "properties": {
      "name": {
        "type": "text"
      },
      "cost": {
        "type": "integer"
      }
    }
  }
}

将仅使用 name 字段值

创建文档
POST /my-index/_doc/sp1
{
  "name": "Shirt"
}

创建此文档后,我想将 cost 值更新为该索引中成本的最大值 (max(cost) * 2)。我使用更新 API 尝试了这个逻辑,如下所示

POST /my-index/_doc/sp1
{
  "script" : {
    "source": "ctx._source.cost = Math.max(doc['cost'].value) * 2"
  }
}

但我无法做到这一点。遇到如下错误

"caused_by" : {
        "type" : "illegal_argument_exception",
        "reason" : "static method [java.lang.Math, max/1] not found"
      }

 

如何实现这个场景

【问题讨论】:

    标签: elasticsearch


    【解决方案1】:

    这样不行。 _update API(顺便说一下,您在示例中没有使用)只允许您在它自己的上下文中更新文档。您无权访问任何其他文档,只能访问文档本身(通过ctx._sourcedoc)和脚本参数(通过params)。

    无法对整个索引执行聚合并使用结果更新特定文档。您需要从客户端应用程序分两步执行此操作(首先查询聚合结果 + 然后将结果索引到文档中)或通过 transform API 但后者以自己的方式工作。

    【讨论】:

    • 这个运气好吗?
    猜你喜欢
    • 1970-01-01
    • 2016-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    • 1970-01-01
    • 2018-04-28
    相关资源
    最近更新 更多