Script appends instead of adding the value

Hi All,

I am trying to update the size field of a document using script however, instead of adding 2 to the existing value (9) of the size field, it is appending it.

Document is -

{
"_index" : "products",
"_type" : "shoes",
"_id" : "2",
"_version" : 1,
"found" : true,
"_source" : {
"name" : "Adidas",
"size" : "9",
"color" : "black"
}
}

curl -X POST -d "{"script":"ctx._source.size += 2"}" -H "Content-type: application/json" -X POST "http://localhost:9200/products/shoes/2/_update?pretty"

{
"_index" : "products",
"_type" : "shoes",
"_id" : "2",
"_version" : 2,
"found" : true,
"_source" : {
"name" : "Adidas",
"size" : "92", <------------------------------------------------------ I want (9+2=11) but it is appending 9 to 2 (92)
"color" : "black"
}
}

Kindly advise.

It looks like when you originally added the data, the size contained a string "size" : "9" instead of a number "size" : 9. As a result this field was mapped as a string field instead of a long. The string + operation concatenates string, as a result you are getting back the string "92" instead of the number 11. The simplest way to solve this issue is to reindex your data while making sure that the field size is mapped as a number.

Alternatively, you can also convert from a string to integer and back to string on the fly in your script by doing something like this ctx._source.size = (Integer.parseInt(ctx._source.size) + 2).toString()

1 Like

Thank you Igor. Its now clear.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.