Can I Scope Aggregations to Ignore Certain Query Parameters?

I'm using Elasticsearch 5.5
I'm trying to index movies by name and location.

{
  "mappings": {
    "movie": {
      "genre": {
        "type": "keyword"
      },
      "geolocation": {
        "type": "geo_point"
      }
    }
  }
}

A user performs a search by providing a location and I'll send back the search results within a bounding box and also provided aggregation stats about the genres playing in their neighborhood.

However, I also want to provide a way to filter by location and genre BUT I still want to return ALL genres in that particular location.

The below query returns the proper search results but the aggregations will only return "Action", but I still want all genres.

{
  "size": 0,
  "query": {
    "bool": {
      "filter": [{
        "geo_bounding_box": {
          "geolocation": {
            "top_left": {
              "lat": 40.73,
              "lon": -74.1
            },
            "bottom_right": {
              "lat": 40.717,
              "lon": -73.99
            }
          }
        }
      },
      {
        "bool": {
          "should": [
            {"term": {"genre.raw": "Action"}}  
          ]
        }
      }
      ]
    }
  },
  "aggs": {
    "cuisines": {
      "terms": {
        "field": "cuisines.raw",
        "size": 10
      }
    }
  }
}

I've considered using Global Aggregations, but that will return all aggregations of genres in my entire index and not a specific bounding box. Is there a way to scope my aggregation to ignore certain query parameters?

This is a good use case to leverage post filter. you just need to change your query to:

{
  "size": 0,
  "query": {
    "bool": {
      "filter": [
        {
          "geo_bounding_box": {
            "geolocation": {
              "top_left": {
                "lat": 40.73,
                "lon": -74.1
              },
              "bottom_right": {
                "lat": 40.717,
                "lon": -73.99
              }
            }
          }
        }
      ]
    }
  },
  "post_filter": {
    "term": {
      "genre.raw": "Action"
    }
  },
  "aggs": {
    "cuisines": {
      "terms": {
        "field": "cuisines.raw",
        "size": 10
      }
    }
  }
}

This will return results within the given bounding box, compute aggregations on that result set and then filter the returned documents to only the ones with the given genre.

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