There are circumstances when we have a set of coordinates and we want to perform a geo search on them. More specifically we want to find out if the coordinate used in our search falls within a shape. In that case we can use the Elastic Search geo shape query to achieve that. In this post I’m going to use geo shape query to perform a search and explain how it works.
What is Geo Shape Query?
Geo Shape query is a type of query we use to see if a coordinate falls within a specific geometric shape. Let’s show this with an example, consider the blow image.
Imagine we already have a coordinate in our database that represent a place which here is represented by a red marker. Now we want to specify a shape on the map (which in this case is a pentagon) to see the our coordinate falls within this shape. If the coordinate falls within this shape then we have a match. Also worth noting that the shape does not have to be a pentagon. But it can be any type of polygon, here’s the definition of polygon.
A plane figure with at least three straight sides and angles, and typically five or more.
So by that definition, this shape is also acceptable.
If you need a set of polygon for testing purposes, I already created one in this link. This tool in google map is also can be a powerful tool to help us to debug our geo shape queries.
How the Geo Shape Query Works
First we need to create the necessary mappings. In the code below we create a mapping for field
location with the type
geo_shape. After that we create some coordinate points.
Now we can run our queries against the created point. Below you see two queries with different shapes. One polygon in the shape of polygon and another in the shape of a triangle. The coordinates use here can visualized in this custom map which I created previously.
Also it’s a good idea to receive
GeoJson for our search coordinates. This format allows us to work with the data in a programmatic way as opposed to other format which are textual and need string interpretation.
Geo Shape Query Necessary Mapping
The type of mapping for geo shape query needs to be
geo_shape. But it can also work with type geo-point, on the condition that we use
"relation": "intersect" instead of
"relation": "within". So the following error is only occur when we want to use relation within.
So as an example, we we try to use the following mapping for our geo shape query:
Instead of this:
When we try to run a geo shape query, we’re going to receive the following error.