2016-03-21 74 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()工作完美。 –