Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Geo Shapes in Elasticsearch

Introduction

Geo shapes in Elasticsearch enable you to index and query complex geometric shapes such as polygons, multipolygons, lines, and circles. This is particularly useful for geospatial data analysis and location-based queries.

Setting Up Elasticsearch

To work with geo shapes, you need to have Elasticsearch installed and running. You can use Docker to quickly set up Elasticsearch:

docker run -d -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch:7.10.1

Mapping Geo Shapes

To store geo shapes, you need to define a mapping for your index. The geo_shape field type is used to index shapes.

PUT /geo_shapes_example { "mappings": { "properties": { "location": { "type": "geo_shape" } } } }

Indexing Geo Shapes

You can index various types of geo shapes such as points, lines, and polygons. Here are some examples:

Indexing a Point

POST /geo_shapes_example/_doc/1 { "location": { "type": "point", "coordinates": [13.400544, 52.530286] } }

Indexing a Line

POST /geo_shapes_example/_doc/2 { "location": { "type": "linestring", "coordinates": [ [13.400544, 52.530286], [13.402, 52.532] ] } }

Indexing a Polygon

POST /geo_shapes_example/_doc/3 { "location": { "type": "polygon", "coordinates": [ [ [13.400544, 52.530286], [13.402, 52.532], [13.405, 52.533], [13.400544, 52.530286] ] ] } }

Querying Geo Shapes

Elasticsearch provides various ways to query geo shapes. You can use the geo_shape query to find documents that contain shapes that intersect with a specified shape.

Intersection Query

POST /geo_shapes_example/_search { "query": { "geo_shape": { "location": { "shape": { "type": "polygon", "coordinates": [ [ [13.400544, 52.530286], [13.402, 52.532], [13.405, 52.533], [13.400544, 52.530286] ] ] }, "relation": "intersects" } } } }

Within Query

POST /geo_shapes_example/_search { "query": { "geo_shape": { "location": { "shape": { "type": "polygon", "coordinates": [ [ [13.400544, 52.530286], [13.402, 52.532], [13.405, 52.533], [13.400544, 52.530286] ] ] }, "relation": "within" } } } }

Conclusion

In this tutorial, we have explored how to work with geo shapes in Elasticsearch. We have covered the basics of setting up Elasticsearch, defining mappings, indexing various types of geo shapes, and querying them. Geo shapes are powerful tools for geospatial data analysis and can be used in diverse applications such as mapping, location-based services, and more.