title: Aggregate only matched nested object values in ElasticSearch
body: <p>I need to sum only the values on the nested objects that match the query. It looks like ElasticSearch determines the documents matching the query and then sums across all of the nested objects. From the below outline I want to search on nestedobjects.objtype="A" and get back the sum of objvalue only for matching nestedobjects, I want to get the value 4. is this possible? If so, how?</p>
  
  <p>Here is the mapping</p>
  
  <pre><code>{
    "myindex": {
      "mappings": {
        "mytype": {
          "properties": {
             "nestedobjects": {
               "type": "nested",
               "include_in_parent": true,
               "properties": {
                 "objtype": {
                   "type": "string"
                 },
                 "objvalue": {
                   "type": "integer"
                 }
               }
             }
           }
         }
       }
     }
   }
  </code></pre>
  
  <p>Here are my documents</p>
  
  <pre><code>PUT /myindex/mytype/1
  {
    "nestedobjects": [
      { "objtype": "A", "objvalue": 1 },
      { "objtype": "B", "objvalue": 2 }
    ]
  }
  PUT /myindex/mytype/2
  {
    "nestedobjects": [
      { "objtype": "A", "objvalue": 3 },
      { "objtype": "B", "objvalue": 3 }
    ]
  }
  </code></pre>
  
  <p>Here is my query code.</p>
  
  <pre><code>POST allscriptshl7/_search?search_type=count
  {
    "query": {
      "filtered": {
        "query": {
          "query_string": {
            "query": "nestedobjects.objtype:A"
          }
        }
      }
    },
    "aggregations": {
      "my_agg": {
        "sum": {
          "field": "nestedobjects.objvalue"
        }
      }
    }
  }
  </code></pre>