Elasticsearch - how to append term?

99封情书 提交于 2020-01-13 05:52:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!