title: Elasticsearch - Create field using script if doesn't exist
body: <p>Is there a way to dynamically add fields using scripts? I am running a script that checks whether a field exists. If not then creates it.</p>
  
  <p>I'm trying out:</p>
  
  <pre><code>script: 'if (ctx._source.attending == null) { ctx._source.attending = { events: newField } } else if (ctx._source.attending.events == null) { ctx._source.attending.events = newField } else { ctx._source.attending.events += newField }'
  </code></pre>
  
  <p>Except unless I have a field in my _source explicitly named <code>attending</code> in my case, I get:</p>
  
  <pre><code>[Error: ElasticsearchIllegalArgumentException[failed to execute script];
  nested: PropertyAccessException[
      [Error: could not access: attending; in class: java.util.LinkedHashMap]
  </code></pre>