通过Java中的脚本进行UpdateRequest

时间:2015-11-09 08:42:54

标签: java elasticsearch

我试图通过Java在Elasticsearch中更新嵌套对象中的属性。我的映射如下:

"mappings": {
    "cv":{
        "properties":{
            "name":{"type":"string"},
            "skills": {
                "type": "nested",
                "properties": {
                    "skillId": {"type": "string"},
                    "yearExperience": {"type": "integer"}
                }
            }
        }
    }
}

我要做的是更新属性' skillId'在嵌套对象中的技能'使用UpdateRequest和脚本功能。所有与输入的id匹配的技能都应该用新的id替换。我到目前为止提出的代码是:

UpdateRequest updateRequest = new UpdateRequest("cv", "cv", "AVDdS7_u8voLjZ32rEnT")
            .addScriptParam("oldId", "AVDdSy4u8voLjZ32rEi4")
            .addScriptParam("newId", "AVDdSy4u8voLjZ32rEi0")
            .script("foreach(item : ctx._source.skills) {if(item['skillId'] == oldId) { item['skillId'] = newId })}");
client.update(updateRequest);   

我已经尝试过脚本的某些部分,其中一些是有效的。对我来说没有用的部分是用嵌套对象做的事情。

编辑:好的,谢谢slawek,我设法得到一个工作脚本:

String script = "def oldElement = ctx._source.skills.find {it.skillsId.equals(oldId) };"
+ "def newElement = oldElement; newElement.skillsId = newId;"
+ "ctx._source.skills -= oldElement;"
+ "ctx._source.skills += newElement;";

0 个答案:

没有答案