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
- Check if field ‘notes’ exists
- If it exists, append new value with existing values
- If it doesn’t exist, create field then append my value
Advertisement
Answer
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]}"