Sergey Zharov
Sergey Zharov

Reputation: 11

Added unique values from array to array in ElasticSearch

How do I add a string array to an existing string array field in Elasticsearch with the help of script?

The result string array in Elasticsearch must be only contain unique string elements.

I know how to add a value in string array:

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}}

I need the same code for string array

x = ["test1", "test2"]

Upvotes: 0

Views: 1334

Answers (2)

Sergey Zharov
Sergey Zharov

Reputation: 11

This code solved the problem:

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

Upvotes: 1

Rahul
Rahul

Reputation: 16355

You can simply concatenate all elements and then find the unique elements as below.

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

The uniq method removes all duplicate elements and retains all unique elements in the array.

Upvotes: 1

Related Questions