如果值不存在,则更新ElasticSearch脚本

时间:2015-10-26 06:39:57

标签: java elasticsearch upsert elasticsearch-plugin

我正在尝试使用Java更新es文档。 我的文件如下

"_source": {

    "gender": "male" ,
    "names": ["name1"]

}

我需要在names列表中添加更多名称。但我不想重复。 如何在没有重复值的情况下更新ES文档中的数组?

我试过这样的事情。但它没有用。

client.prepareUpdate(index,type,id)
         .addScriptParam("newobject", "newName")
        .setScript("ctx._source.names.contains(newobject) ? ctx.op = \"none\" :  ctx._source.names+=newobject ").execute().actionGet(); 

1 个答案:

答案 0 :(得分:2)

想法是简单地在结果列表上调用unique()

client.prepareUpdate(index,type,id)
         .addScriptParam("newobject", "newName")
        .setScript("ctx._source.names+=newobject; ctx._source.names = ctx._source.names.unique(); ").execute().actionGet(); 

此外,您需要确保scripting is enabled