title: ElasticSearch: Updating nested document in array
body: <p>Given the document</p>
  
  <pre><code>curl -XPUT 'localhost:9200/test/me/here' -d '{
    "top" : [
      { "searchkey" : "change"},
      { "searchkey" : "keep"}
    ]
  }'
  </code></pre>
  
  <p>I need an update query that will add new field to sub-document with <code>searchkey</code> equal to <code>change</code> and will keep any other sub-document intact. The expected result is then:</p>
  
  <pre><code>{
    "top" : [
      { "searchkey" : "change", "newfield" : "newvalue"},
      { "searchkey" : "keep"}
    ]
  }
  </code></pre>
  
  <p>Running query that selects inner document by index works, but I do not know the inner order in advance and it is quite fragile anyways:</p>
  
  <pre><code>curl -XPOST 'localhost:9200/test/me/here/_update' -d '{
      "script" : "ctx._source.top[0].newfield = v",
      "params" : {
        "v" : "newvalue"
      }
  }'
  </code></pre>
  
  <p>Is there a way to tell ES to add the new field to the inner document that matches some condition? Something like:</p>
  
  <pre><code>curl -XPOST 'localhost:9200/test/me/here/_update' -d '{
      "script" : "ctx._source.top[ctx._source.top.searchkey == s].newfield = v",
      "params" : {
        "s" : "change",
        "v" : "newvalue"
      }
  }'
  </code></pre>
  
  <p>Or, will I do better and save some headache if I eliminate the array and transform the document to:</p>
  
  <pre><code>{
  "change" : {},
  "keep" : {}
  }
  </code></pre>