How to aggregate only results returned from query in elastic search

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"
              }
            }
          }
        }
      }
    }
  }
}

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