liveBook · Manning

Geo_shape query

As explained in Elasticsearch in Action, Second Edition

An Elasticsearch geo_shape query matches documents whose indexed geographic shapes have a specified spatial relationship to a query shape.

Use a geo_shape query when a location is a shape rather than a single point: for example, finding cafes or plots of land related to a coordinate-defined envelope. section 12.6 section 12.3

The query compares shapes indexed in a geographic field with a supplied shape, such as a triangle or multisided polygon. The supplied envelope must be closed rather than open-ended. section 12.1.3 section 12.6

Listing 12.10 Searching for cafes within a given shape
GET cafes/_search
{
  "query": {
    "geo_shape": {             #1
      "address": {
        "shape": {
          "type": "envelope",  #2
          "coordinates": [
            [0.1,55],
            [1,45]
          ]
        },
        "relation": "within"   #3
      }
    }
  }
}

A focused REST example searches the cafes index with an envelope and sets the relation to within. section 12.6

The relation controls how indexed shapes must relate to the query shape:

  • intersects returns documents that intersect the supplied shape and is the default. section 12.6
  • within matches documents located within the supplied shape. section 12.6
  • contains returns documents that contain the supplied shape. section 12.6
  • disjoint returns documents that do not exist in the supplied shape. section 12.6

London plots and a hexagonal boundary

For a hexagonal query shape, plots A and B are within it, plot C intersects its boundary, and plot D is outside. Using intersects returns A, B, and C; using within returns A and B; using disjoint returns D. section 12.6

Prepare the geospatial mapping and index shape documents before searching. Use geo_shape for geographic shapes; use the separate shape type for 2D Cartesian drawings and designs. section 12.1.3 section 12.7

How Elasticsearch in Action, Second Edition covers it

How deep it goes
Explains envelopes, indexed shapes, and four relations with worked cafe and plot examples, but defers broader indexing mechanics.
Examples
Uses cafes in an envelope, London farmland plots, hexagons, polygons, and coordinate-defined envelopes.
What it assumes
Assumes indexed geospatial fields and coordinate pairs, while introducing geo_shape data mapping and shape-query mechanics.
What you can do after
Apply it via the Elasticsearch REST API to filter indexed geographic shapes by intersects, within, contains, or disjoint.
How it connects
Connects geo_shape queries with geo_point, geo_bounding_box, geo_distance, geospatial data types, and shape queries.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Elasticsearch in Action, Second Edition. The section links point to the parts of the book it draws on.