title: Elasticsearch: Search for a group of summed fields
body: <p>I have a benchmark index with data from for hospital wards and I want to know the medication usages for a wards location per week. </p>
  
  <p>The problem now is that when I select a week of data, the population for a location with multiple wards will be calculated wrong. I want to know the average population for a location in that week. The location's population is the sum of the population from the wards within the location</p>
  
  <pre><code>{
      "_index": "development_benchmark",
      "_type": "score",
      "_id": "3147603",
      "_score": null,
      "_source": {
        "id": 3147603,
        "score": 86,
        "amount": 1758.7,
        "population": 2045,
        "date": "2018-01-12T03:00:00+01:00",
        "benchmark_id": 10,
        "ward": {
          "id": 24170,
          "ward_types": [
            3
          ]
        },
        "location_id": 24285,
        "cluster_id": 72997
      }
  }
  </code></pre>
  
  <p>My query looks like this:</p>
  
  <pre><code>GET development_benchmark/_search
  {
   "query": {
      "bool": {
          "must": [
          {
              "range": {
              "date": {
                  "gte": "2017-12-20",
                "lte": "2017-12-20"
              }
            }
          }
        ]
      }
    },
    "aggs": {
      "benchmarks": {
          "terms": {
              "field": "benchmark_id",
          "size": 100
        },
        "aggs": {
              "clusterScore": {
                  "filter": {
                      "bool": {
                          "must": [
                  {
                      "term": {
                      "cluster_id": 72997
                    }
                  }
                ]
              }
            },
            "aggs": {
                "amount": {
                    "sum": {
                        "field": "amount"
                    }
                },
                "population": {
                    "sum": {
                        "field": "population"
                    }
                },
                "locations": {
                    "terms": {
                              "field": "location_id",
                  "size": 1000
                },
                "aggs": {
                              "amount": {
                                  "sum": {
                                      "field": "amount"
                    }
                  },
                  "population": {
                                  "sum": {
                                      "field": "population"
                    }
                  }
                }
              }
            }
        }
      }
    }
  }
  </code></pre>