问题
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?
回答1:
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
...
回答2:
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
来源:https://stackoverflow.com/questions/36310693/elasticsearch-how-to-append-term