【问题标题】:How to update nested numeric field value in Elasticsearch/ AWS Opensearch?如何更新 Elasticsearch/AWS Opensearch 中的嵌套数字字段值?
【发布时间】:2021-12-24 20:27:56
【问题描述】:

我对 ES 不太熟悉,所以可能我犯了一些错误。

我有一个索引users,其映射如下。

{
   "mappings":{
      "dynamic":false,
      "properties":{
         "id":{
            "type":"keyword"
         },
         "userId":{
            "type":"text"
         },
         "total":{
            "type":"float"
         },
         "count":{
            "type":"float"
         },
         "earnings":{
            "properties":{
               "potential":{
                  "properties":{
                     "pending":{
                        "type":"float"
                     },
                     "finished":{
                        "type":"float"
                     }
                  }
               },
               "completed":{
                  "properties":{
                     "pending":{
                        "type":"float"
                     },
                     "paid":{
                        "type":"float"
                     }
                  }
               }
            }
         }
      }
   }
}

我想使用更新 API 更新嵌套字段,例如收益.potential.pending。我有一个类似于下面使用更新 API 的脚本。

{
  "script" : {
    "source": "ctx._source.earnings.potential.pending += params.total",
    "lang": "painless",
    "params" : {
      "total" : 4
    }
  }
}


但是,我遇到了illegal_argument_exception,点符号是假设的问题,如下所示。

"ctx._source.earnings.potential.pending += params.total",
            ^---- HERE'

【问题讨论】:

    标签: elasticsearch aws-elasticsearch opensearch


    【解决方案1】:

    如果您尝试更新的文档上的earnings 为空,您将收到错误消息:

    ...
    "caused_by": {
      "type": "null_pointer_exception",
      "reason": "cannot access method/field [potential] from a null def reference"
    }
    

    所以本质上你需要在字段上设置一个默认值,如果它是空的。最简单的方法是在索引时执行此操作,或者运行一次性查询以在任何地方设置默认值。但如果这不是一个选项,您可以扩展您的脚本以检查并分配一个默认值:

    {
        "script": {
            "lang": "painless",
            "source": "if(ctx._source.earnings == null) { ctx._source.earnings = [:] }\n if(ctx._source.earnings.potential == null) { ctx._source.earnings.potential = [:] }\n if(ctx._source.earnings.potential.pending == null) { ctx._source.earnings.potential.pending = 0 } \n ctx._source.earnings.potential.pending += params.total",
            "params": {
                "total": 5
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 2021-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-25
      相关资源
      最近更新 更多