Update array on source

Hi guys, I use Elasticsearch 2.2.0 and I tried to update array inside a source
here is my source
{
"list":[
{
"tweet_id":"1",
"a":"b"
},
{
"tweet_id":"123",
"a":"f"
}
]
}

and i use this script to update the data

{
"script":"foreach (item : ctx._source.list) {if (item['tweet_id'] ==tweet_id) { item['new_field'] = 'ghi'; } }",
"params":{
"tweet_id":"123"
}
}

but the result is error
here is the error

{
"error": {
"root_cause": [
{
"type": "remote_transport_exception",
"reason": "[node1_ES2-2][127.0.0.1:9300][indices:data/write/update[s]]"
}
],
"type": "illegal_argument_exception",
"reason": "failed to execute script",
"caused_by": {
"type": "script_exception",
"reason": "failed to run inline script [foreach (item : ctx._source.list) {if (item['tweet_id'] ==tweet_id) { item['new_field'] = 'ghi'; } }] using lang [groovy]",
"caused_by": {
"type": "missing_method_exception",
"reason": "No signature of method: 1a98d9460b8843033b48ef3d6cf1537914f98f76.foreach() is applicable for argument types: (java.util.LinkedHashMap, 1a98d9460b8843033b48ef3d6cf1537914f98f76$_run_closure1) values: [[item:[[tweet_id:1, a:b], [tweet_id:123, a:f]]], 1a98d9460b8843033b48ef3d6cf1537914f98f76$_run_closure1@74f92d43] Possible solutions: each(groovy.lang.Closure)"
}
}
},
"status": 400
}

Can anyone tell me what is wrong here?

Thanks

Hey,

you tried to write javascript as your scripting language (at least that's what I am interpreting here), but you need to use groovy here. Groovy does not have a concept called foreach, you may want to check out some groovy examples...

As an example (without knowing any of your data structure or having tested this)

ctx.source.list.each { elem -> if (elem.tweetId == tweet_id) { ctx.source.new_field = 'ghi' } }

Hope this helps...

--Alex

Hi Alexander

Thanks for the answer. But when I use the script from above , it show error "Cannot get property 'list' on null object". But I have value on list array. Can you tell me what is going wrong here?? thank a lot

here is my properties setting
"list": {
"properties": {
"a": {
"type": "string"
},
"tweet_id": {
"type": "string"
}
}
},

and the error is :
{
"error": {
"root_cause": [
{
"type": "remote_transport_exception",
"reason": "[node1_ES2-2][127.0.0.1:9300][indices:data/write/update[s]]"
}
],
"type": "illegal_argument_exception",
"reason": "failed to execute script",
"caused_by": {
"type": "script_exception",
"reason": "failed to run inline script [ctx.source.list.each { }] using lang [groovy]",
"caused_by": {
"type": "null_pointer_exception",
"reason": "Cannot get property 'list' on null object"
}
}
},
"status": 400
}

I found out what the problem is. use _source instead of source.

thanks