2016-03-21 70 views
0

如何在脚本的帮助下将字符串数组添加到Elasticsearch中的现有字符串数组字段?在ElasticSearch中添加阵列到阵列的唯一值

Elasticsearch中的结果字符串数组必须只包含唯一的字符串元素。

我知道如何在字符串数组中添加值:

x = "test" 
client.update index:'test', type:'test', id:'1', body:{script:"if (!ctx._source.a.contains(x)) {ctx._source.a += x;}", params:{x: x}} 

我需要的相同的代码字符串数组

x = ["test1", "test2"] 

回答

0

你可以简单地串联所有元素,然后找到独特的元素下面。

{ 
     script:"ctx._source.a += x; ctx._source.a = ctx._source.a.uniq;", 
     params:{x: x} 
    } 

uniq method删除所有重复的元素并保留在阵列中的所有唯一元素。

+0

我试图执行该代码。错误:{“script”:“ctx._source.a + = x; “111”,“222”,“333”]}} <{“error”:“ElasticsearchIllegalArgumentException [未能执行脚本];嵌套:GroovyScriptExecutionException [MissingPropertyException [异常评估属性'uniq'for java.util.ArrayList, :groovy.lang.MissingPropertyException:No such property:uniq for class:java.lang.String]];“,”status“:400} –

+0

由于您的问题中的语言标记建议使用ruby,因此uniq是一种有效的ruby语法。而错误显示语言为groovy,这意味着脚本被作为groovy脚本执行而不是ruby代码。默认语言是groovy。您的解决方案与我的答案基本相同。 – Rahul

1

此代码解决了这个问题:

x = ['test1', 'test2'] 
client.update index:'test', type:'test', id:'1', body:{script:"ctx._source.a += x; ctx._source.a.unique()", params: {x:x}} 
+0

ctx._source.a.unique()工作完美。 –