Elasticsearch Geo Polygon Query

The Geo Polygon Query in Elasticsearch allows you to find documents with geo-points that fall within a specified polygon. This query is particularly useful for geospatial searches where you need to filter results based on complex geographical boundaries.

Syntax

GET /_search
{
  "query": {
    "geo_polygon": {
      "field_name": {
        "points": [
          {"lat": lat1, "lon": lon1},
          {"lat": lat2, "lon": lon2},
          ...
        ]
      }
    }
  }
}

For more details, refer to the official Elasticsearch documentation.

Example Query

GET /my_locations/_search
{
  "query": {
    "geo_polygon": {
      "location": {
        "points": [
          {"lat": 40.73, "lon": -74.1},
          {"lat": 40.01, "lon": -71.12},
          {"lat": 50.56, "lon": -90.58},
          {"lat": 40.73, "lon": -74.1}
        ]
      }
    }
  }
}

This query searches for documents in the my_locations index where the location field contains geo-points within the specified polygon.

Common Issues

  1. Ensure that the field you're querying is mapped as a geo_point type.
  2. The polygon must be closed, meaning the first and last points should be the same.
  3. Be cautious with the order of latitude and longitude in your points.
  4. Large polygons may impact query performance.

Best Practices

  1. Use the Geo Polygon Query in combination with other queries for more refined results.
  2. Consider using a geo-shape index for complex or frequently changing polygons.
  3. Optimize your polygon by reducing the number of points while maintaining accuracy.
  4. Use the validation_method parameter to control error handling for invalid polygons.

Frequently Asked Questions

Q: Can I use the Geo Polygon Query with other geo queries?
A: Yes, you can combine the Geo Polygon Query with other geo queries using boolean queries for more complex geospatial searches.

Q: How many points can I use to define a polygon?
A: There's no strict limit, but using too many points can impact performance. Try to balance accuracy with efficiency.

Q: What happens if my polygon is not closed?
A: Elasticsearch will automatically close the polygon by connecting the last point to the first point.

Q: Can I use the Geo Polygon Query for exclusion?
A: Yes, you can use a must_not clause in a bool query to exclude documents within a polygon.

Q: How does the Geo Polygon Query handle the antimeridian (180th meridian)?
A: The query supports polygons that cross the antimeridian. Ensure your longitude values are between -180 and 180 degrees.

Pulse - Elasticsearch Operations Done Right

Stop googling errors and staring at dashboards.

Free Trial

Subscribe to the Pulse Newsletter

Get early access to new Pulse features, insightful blogs & exclusive events , webinars, and workshops.