
Elasticsearch 8.x Cookbook
By :

The power of geoprocessing Elasticsearch is used to provide capabilities to a large number of applications. However, it has one limitation: it only works for world coordinates.
Using Point and Shape types, X-Pack extends the geo capabilities to every two-dimensional planar coordinate system.
Common scenarios for this use case include mapping and documenting building coordinates and checking if documents are inside a shape.
You will need an up-and-running Elasticsearch installation, as we described in the Downloading and installing Elasticsearch recipe of Chapter 1, Getting Started.
To execute the commands in this recipe, you can use any HTTP client, such as curl (https://curl.haxx.se/), Postman (https://www.getpostman.com/), or similar. I suggest using the Kibana console, which provides code completion and better character escaping for Elasticsearch.
We want to use Elasticsearch to map a device's coordinates in our shop. To achieve this, follow these steps:
PUT test-point { "mappings": { "properties": { "device": { "type": "keyword" }, "location": { "type": "point" } } } }
PUT test-point/_bulk {"index":{"_index":"test-point","_id":"1"}} {"device":"device1","location":{"x":10,"y":10}} {"index":{"_index":"test-point","_id":"2"}} {"device":"device2","location":{"x":10,"y":15}} {"index":{"_index":"test-point","_id":"3"}} {"device":"device3","location":{"x":15,"y":10}}
At this point, we want to create shapes in our shop so that we can divide it into parts and check if the people/devices are inside the defined shape. To do this, follow these steps:
PUT test-shape { "mappings": { "properties": { "room": { "type": "keyword" }, "geometry": { "type": "shape" } } } }
POST test-shape/_doc/1 { "room":"hall", "geometry" : { "type" : "polygon", "coordinates" : [ [ [8.0, 8.0], [8.0, 12.0], [12.0, 12.0], [12.0, 8.0], [8.0, 8.0]] ] } }
POST test-point/_search { "query": { "shape": { "location": { "indexed_shape": { "index": "test-shape", "id": "1", "path": "geometry" } } } } }
The result for both queries will be as follows:
{ …truncated… "hits" : [ { "_index" : "test-point", "_id" : "1", "_score" : 0.0, "_source" : { "device" : "device1", "location" : { "x" : 10, "y" : 10 } …truncated…
The point
and shape
types are used to manage every type of two-dimensional planar coordinate system inside documents. Their usage is similar to geo_point
and geo_shape
.
The advantage of storing shapes in Elasticsearch is that you can simplify how you match constraints between coordinates and shapes. This was shown in our query example, where we loaded the shape's geometry from the test-shape
index and the search from the test-point
index.
Managing coordinate systems and shapes is a very large topic that requires knowledge of shape types and geo models since they are strongly bound to data models.