2

Is there a way to append term into an array of values?

For example if my document looks like this:

{
   "items": ["item1", "item2", "item3"]
}

I want to append "item4" and "item5" to it.

I must do it in 2 queries? one to load the current list of values, and on to update that list? or is there more elegant way that will let me append those items in one query?

I am trying to do it with elastic4s like this:

client.execute(ElasticDsl.update id id in indexName / documentType script {
  script(s"ctx._source.items += tag").params(Map("tag"->"item4"))
})

In order to use the above code snippet, I need to enable groovy scripts, and I am not sure how to do it with multiple items.

Any idea?

Tomer
  • 2,398
  • 1
  • 23
  • 31
  • 1
    Simple way is do it with two queries. But you can use custom scripting [1](http://stackoverflow.com/questions/18028280/elasticsearch-upserting-and-appending-to-array), [2](http://stackoverflow.com/questions/31142729/append-to-a-elasticsearch-field-list-array-if-its-not-an-existing-element) to do it with one query. – pkhlop Mar 30 '16 at 13:54
  • @pkhlop Thanks. What about multiple items? how can I do that? – Tomer Mar 30 '16 at 15:02

2 Answers2

4

Here is a full example of how you could achieve this.

Merge new values to array and make it unique after:

DELETE test/test/1

POST test/test/1
{
  "terms":["item1", "item2", "item3"]
}

GET test/test/1

POST test/test/1/_update
{
     "script" : " ctx._source.terms << newItems; ctx._source.terms = ctx._source.terms.flatten().unique()",
     "params" : {
         "newItems" : ["a","b"]
     }
}

make sure you have scripting enabled in server config

user:/etc/elasticsearch# head elasticsearch.yml 
script.inline: true
script.indexed: true
...
pkhlop
  • 1,824
  • 3
  • 18
  • 23
  • 1
    When trying it I get an exception : "reason": "No such property: ctx for class: 73fa07c80e9d5eb75065 any idea? – Tomer Mar 30 '16 at 16:36
  • 1
    see update in answer, you have to enable inline scripting – pkhlop Mar 30 '16 at 16:52
  • Thanks.. managed to fix this by adding groovy dependency to my build.sbt, The query worked, but the result was not as expected..:( I got- "terms":["item1","item2","item3",["item4","item5"]]. Any way to fix this? – Tomer Mar 30 '16 at 17:10
  • OK.. fixed it with : s"ctx._source.terms.addAll(newItems); ctx._source.terms.unique()" – Tomer Mar 30 '16 at 17:15
  • 1
    good! you can use *ctx._source.terms = ctx._source.terms.flatten().unique()* as well – pkhlop Mar 30 '16 at 17:17
-1

Try using 'terms' filter in your code.If you are using NEST then following link will be useful https://nest.azurewebsites.net/nest/writing-queries.html

Community
  • 1
  • 1
user2768439
  • 25
  • 1
  • 9