Reputation: 6199
I'm trying to dynamically add a new array type field to documents as they need it, If the field exists already (ie, someone else already added an item to the array) then append my item. If it doesn't exist, I need it to create the field then append my item.
Currently I can only append if I first create the field but the way I've written it overwrites existing field values if present.
# Create the field, not ideal as it wipes the field if it existed already
es.update(
index='index_name',
id='doc_id_987324bhashjgbasf',
body={"doc": {
'notes': []}})
# Append my value
es.update(index='index_name', id='doc_id_987324bhashjgbasf',
body={
"script": {
"source": "ctx._source.notes.addAll(params.new_note)",
"lang": "painless",
"params": {
"new_note": [{'note': 'Hello I am a note', 'user':'Ari'}]
}
}
})
Ideally the process I'd like is
Upvotes: 3
Views: 1804
Reputation: 783
The following should work -
"script" : "if (ctx._source.notes == null) { ctx._source.notes = [params.new_note]; } else {ctx._source.notes.add(params.new_note);} "
Upvotes: 0
Reputation: 18608
logstash:
if [notes] {
notes.add("NewItem");
} else {
notes = new ArrayList();
notes.add("NewItem");
}
elasticsearch:
"script": "if (ctx._source.containsKey(\"notes\")) {ctx._source.notes += value;} else {ctx._source.notes = [value]}"
Upvotes: 3