2

I want to add something into array “tags”:[“red”] using JavaScript api in elastic search, currently, i am doing this as follows:

client.update(
"test":{
"index": "test",
"type": "type1",
"id": "1",
"body": {
"script": "ctx._source.tags += tag", 
"params": { "tag": "blue" }
}
})

this changes the field "tags" : ["red"] to "tags" : blue instead of ["red","blue"],

I am getting the expected output via Ubuntu Terminal using curl -XPUT or curl -XPOST methods

My node module elastic search version is 2.4.2 elastic search server is 1.3.2

Please Help...

1 Answer 1

2

ElasticSearch script engine does not support javascript, Read:why not javascript.

To add an item to a array, use the add() function and not +=

curl -XPOST 'localhost:9200/test/type1/1/_update' -d '{
"script":"ctx._source.tags.add(tag)",
"params":{"tag":"blue"}
}'
Sign up to request clarification or add additional context in comments.

3 Comments

This is not working in two cases,1) if tags is integer type or 2) tags does not already exist, i also tried "upsert": { "tags": [] }, but this is not working....please help
@RajitGarg-if tags is integer, then you need to use ctx._source.tags += tag. If it doesn't exist, it would be ignored. I suggest you to query based on your schema. It would be more helpful for you, if you set up a new question, depicting the schema, if this is not resolved.
I am doing this for update integer type field client.update( {"index": "test", "type": "type1", "id": "2201", "body": {"script" : "ctx._source.counter+=count", "params": { "count":50 } } }) Initially my counter = 10, then it should be updated to 60(50+10), but it replaces this from the new one and result is 50, please help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.