# How to aggregate only results returned from query in elastic search

**URL:** <https://discuss.elastic.co/t/how-to-aggregate-only-results-returned-from-query-in-elastic-search/71789>\
**Category:** Elasticsearch\
**Created:** [January 16, 2017, 11:11pm UTC](https://discuss.elastic.co/t/how-to-aggregate-only-results-returned-from-query-in-elastic-search/71789 "2017-01-16T23:11:24Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![codemonkey](https://avatars.discourse-cdn.com/v4/letter/c/9fc348/32.png) [@codemonkey](https://discuss.elastic.co/u/codemonkey)\
**Post date:** [January 16, 2017, 11:11pm UTC](https://discuss.elastic.co/t/how-to-aggregate-only-results-returned-from-query-in-elastic-search/71789/1 "2017-01-16T23:11:24Z")

</div>

I'm trying to do bucket aggregations in elastic search that only runs on the results that were returned from query.

It seems like the the aggregation runs on every hits but only return a portion of it. Which is fine but the problem is the documents that are returned from the aggregation doesn't match the documents that are returned from the query.

Here is my mapping:

```
LOCATION_MAPPING = {
  id: { type: 'long' },
  name: { type: 'text' },
  street: { type: 'text' },
  city: { type: 'text' },
  state: { type: 'text' },
  zip: { type: 'text' },
  price: { type: 'text' },
  geolocation: { type: 'geo_point' },
  amenities: { type: 'nested' },
  reviews: { type: 'nested' },
}

```

Here is the query:

```
{
  "sort": [
    {
      "_score": {
        "order": "desc"
      }
    }
  ],
  "query": {
    "bool": {
      "filter": {
        "geo_distance": {
          "distance": "1000yd",
          "geolocation": [
            -73.990768410025,
            40.713144830193
          ]
        }
      },
      "must": {
        "multi_match": {
          "query": "new york",
          "fields": [
            "name^2",
            "city",
            "state",
            "zip"
          ],
          "type": "best_fields"
        }
      }
    }
  },
  "aggs": {
    "reviews": {
      "nested": {
        "path": "reviews"
      },
      "aggs": {
        "location": {
          "terms": {
            "field": "reviews.locationId"
          },
          "aggs": {
            "avg_rating": {
              "avg": {
                "field": "reviews.rating"
              }
            }
          }
        }
      }
    }
  }
}
```

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [February 13, 2017, 11:12pm UTC](https://discuss.elastic.co/t/how-to-aggregate-only-results-returned-from-query-in-elastic-search/71789/2 "2017-02-13T23:12:22Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
