Welcome! In this lesson, you’ll explore how to work with geospatial indexes in Redis using the powerful ioredis module. In addition to learning how to add geographic coordinates to a sorted set, you will also learn how to calculate distances between locations.
Redis does not store geospatial data as raw latitude and longitude values. Instead, it encodes them into a Geohash, a compact string representation that enables efficient range queries. This means locations are indexed in a way that makes proximity searches extremely fast.
In this lesson, you will discover:
- How to add geographical coordinates (longitude and latitude) to a Redis sorted set using the
geoadd
command. - How to calculate the distance between two locations using the
geodist
command.
Below is an example that connects to Redis using ioredis, adds two locations, and computes the distance between them.
Explanation:
- geoadd Command: The
geoadd
function adds a location to the Redis geospatial index. In this example, we add two locations—'Palermo' and 'Catania'—with their respective longitude and latitude. - geodist Command: The
geodist
function calculates the geographical distance between two locations. Here, it computes the distance between 'Palermo' and 'Catania' in kilometers. Note, the formula assumes the Earth is a perfect sphere, which is an approximation (the Earth is slightly elliptical). Redis does not consider roads, terrain, or travel routes—only straight-line distances. - Connection Management: ioredis automatically manages connection pooling. After performing the operations, we disconnect to clean up our connection.
Understanding geospatial indexes in Redis is crucial if your applications need to handle geographical data. With ioredis, these operations are efficient and straightforward, enabling features such as nearby search, location-based filtering, and more.
Harnessing geospatial capabilities in Redis with ioredis provides you with a robust tool to build location-aware applications. Ready to explore further? Let's dive into the practical exercises!
