elasticsearch:use script to update nested field?

后端 未结 1 498
北恋
北恋 2020-12-06 13:28

I want to add a object into the nested field every update time.

For example,I have a doc:

{
    \"test\":[{\"remark\":\"remark1\"}]
}


        
相关标签:
1条回答
  • 2020-12-06 14:21

    I suggest to try a script like this, which takes two parameters in argument. It will check if any of the nested objects already contains the given id:

    • if yes, it will update the given remark
    • if not, it will insert a new nested object in the test array.

    The script goes like this:

    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)
    }
    

    After being inlined and with proper semicolons, the script looks like this:

    {
        "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": "affffd",
                "id": "1"
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题