我希望nested每次更新时都在对象中添加一个对象.
例如,我有一个doc:
{
"test":[{"remark":"remark1"}]
}
Run Code Online (Sandbox Code Playgroud)
下次,我想在remark测试字段中添加一个对象并保存旧remark对象.结果是:
{
"test":[{"remark":"remark1"},{"remark":"remark2"}]
}
Run Code Online (Sandbox Code Playgroud)
怎么实现呢?
编辑 我使用脚本:
{
"script": "ctx._source.test= ((ctx._source.test?: []) += remarkItem)",
"params": {
"remarkItem": {
"remark": "addd"
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我得到了例外:
{
"error": {
"root_cause": [
{
"type": "remote_transport_exception",
"reason": "[es77][10.14.84.77:9300][indices:data/write/update[s]]"
}
],
"type": "illegal_argument_exception",
"reason": "failed to execute script",
"caused_by": {
"type": "script_exception",
"reason": "Failed to compile inline script [ctx._source.test= ((ctx._source.test?: []) += remarkItem)] using lang [groovy]",
"caused_by": {
"type": "script_exception",
"reason": "failed to compile groovy script",
"caused_by": {
"type": "multiple_compilation_errors_exception",
"reason": "startup failed:\na8220b2cf14b8b7ebeead7f068416882d04fa25d: 1: \nclass org.codehaus.groovy.ast.expr.ElvisOperatorExpression, with its value '(ctx._source.test) ? ctx._source.test: []', is a bad expression as the left hand side of an assignment operator at line: 1 column: 82. File: a8220b2cf14b8b7ebeead7f068416882d04fa25d @ line 1, column 82.\n CILastCallResultRemark ?: []) += remarkI\n ^\n\n1 error\n"
}
}
}
},
"status": 400
}
Run Code Online (Sandbox Code Playgroud)
编辑
现在,我想添加一个字段以确保更新或插入对象.例如:
{
"test":[{"remark":"remark1","id":"1"}]
}
Run Code Online (Sandbox Code Playgroud)
当我更新字段时,当id存在时,我将更新对象.相反,我将插入对象.
我建议尝试这样的脚本,它在参数中有两个参数.它将检查是否有任何嵌套对象已包含给定的id:
remarktest数组中插入一个新的嵌套对象.脚本是这样的:
def updated = false
ctx._source.test?.each { obj ->
if (obj.id == item.id) {
obj.remark = item.remark
updated = true
}
}
if (!updated) {
ctx._source.test = ((ctx._source.test ?: []) + item)
}
Run Code Online (Sandbox Code Playgroud)
在内联并使用正确的分号后,脚本如下所示:
{
"script": "def updated = false; ctx._source.test?.each { obj -> if (obj.id == item.id) { obj.remark = item.remark; updated = true } }; if (!updated) { ctx._source.test = ((ctx._source.test ?: []) + item)}",
"params": {
"item": {
"remark": "addd",
"id": "1"
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5048 次 |
| 最近记录: |