Elasticsearch in Action: The geo_bounding_box Query
The excerpts are taken from my book Elasticsearch in Action, Second Edition. The code is available in my GitHub repository. You can find executable Kibana scripts in the repository so you can run the commands in Kibana straight away. All code is tested against Elasticsearch 8.4 version.
This is a series of mini articles about geo-spatial queries in Elasticsearch.
In this article, we discuss about geo_bounding_box
query. In the next two articles, we look at the geo_distance
and geo_shape
queries.
Overview
When we search for a list of addresses, we can use an area of interest. This area can be represented by a circle of a certain radius or an area enclosed by a shape such as a rectangle, or a polygon from a central point (a landmark).
Elasticsearch provides a geo_bounding_box
query that lets us search locations that fall inside these areas. For example, as the figure given below shows, we can construct a rectangle using latitude and longitude coordinates and search if our address exists in that area.
The top_left
and bottom_right
fields are the coordinates of latitude and longitude that make up our georectangle. Once we define a georectangle, we can check if the points of interest (the Imperial College London, for example) are present inside this rectangle.
Before we discuss the geo_bounding_box
query in detail, let’s write the query first and then we can come back to dissect it. The following query searches all the documents (locations) that would fit in the rectangle constructed with top_left
and bottom_right
coordinates.
GET restaurants/_search
{
"query": {
"geo_bounding_box": {
"location": {
"top_left": {
"lat": 52,
"lon": 0.2
},
"bottom_right": {
"lat": 49,
"lon": 0.1
}
}
}
}
}
The query searches all the documents that intersect (fit in) a georectangle made by the two coordinates, top_left
and bottom_right
, as in the previous figure. The user can provide these two coordinates so that we can construct a rectangular shape with them.
The restaurants that fall inside this rectangle are returned as search results, whereas the rest are dropped. In the previous listing, we are essentially creating an area represented by a rectangle and searching for our restaurants in that rectangle.
> You can also represent the vertices of the bounded rectangle as top_right
and bottom_left
(as opposed to top_left
and bot`tom_right). Or, if you want, you can break it down even further by simply having the corresponding coordinates named as top, left, bottom, and right.
In this article, we discussed about geo_bounding_box
query. In the next two articles, we look at the geo_distance
and geo_shape
queries.