2014-11-17 32 views
4

是否有一种使用脚本动态添加字段的方法?我正在运行一个脚本来检查字段是否存在。如果没有,然后创建它。Elasticsearch - 如果不存在,则使用脚本创建字段

我尝试:

script: 'if (ctx._source.attending == null) { ctx._source.attending = { events: newField } } else if (ctx._source.attending.events == null) { ctx._source.attending.events = newField } else { ctx._source.attending.events += newField }' 

除非,除非我在_source在我的情况明确指定attending有一个字段,我得到:

[Error: ElasticsearchIllegalArgumentException[failed to execute script]; 
nested: PropertyAccessException[ 
    [Error: could not access: attending; in class: java.util.LinkedHashMap] 

回答

11

要检查一个字段是否存在使用在ctx._source.containsKey功能,如:

curl -XPOST "http://localhost:9200/myindex/message/1/_update" -d' 
{ 
    "script": "if (!ctx._source.containsKey(\"attending\")) { ctx._source.attending = newField }", 
    "params" : {"newField" : "blue" }, 
    "myfield": "data" 
}' 
+0

谢谢你将在我有机会的时候测试一下。有没有一个像'contains'和'containsKey'这样的所有方法的网站?如果我知道在哪里看,我会尝试他们。 – Maruf

+0

我不知道任何单一资源 - 我的信息来自各种论坛。当我遇到这个问题时,我最终决定将这些字段存储在一个单独的子文档中 - 这看起来更加健壮和简单。 –

0

我想,如果它真的ñ考虑需要查看该领域是否存在。只需将新映射应用于ES,并在需要时添加它,如果已经存在,则不执行任何操作。

我们的系统在每次应用程序启动时重新应用映射。

+0

该字段存在于映射中,但它会抛出错误,无论 – Maruf

+0

如果它是一个简单的字段 - 那么是的,** upsert **将起作用。然而,这看起来像是一组值,脚本需要添加到数组中,如果它存在,或者创建它,如果它不存在。 –

相关问题