Geospatial Indexes
Redis provides built-in geospatial capabilities that allow you to:
- Store geographic locations (longitude, latitude)
- Query nearby points within a radius
- Calculate distances between two locations
- Sort by distance
- Use bounding boxes and circular radius queries
Redis geospatial features are built on top of the sorted set (ZSET) data structure using a technique called Geohash encoding.
How Redis Geospatial Works Internally
- Every geospatial point is stored as a Geohash, which is a 52-bit integer.
- Redis stores that integer inside a sorted set.
- Geospatial commands (
GEOADD,GEORADIUS, etc.) handle encoding and querying.
Redis does not store altitude or 3D coordinates—just latitude & longitude.
Redis Geospatial Commands
| Command | Description |
|---|---|
GEOADD | Add a location with longitude, latitude, and name |
GEOPOS | Get coordinates of a member |
GEODIST | Get distance between two points |
GEORADIUS | Find members within a radius (circle) |
GEORADIUSBYMEMBER | Radius query based on another member |
GEORADIUS_RO, GEORADIUSBYMEMBER_RO | Read-only versions |
GEOHASH | Get geohash strings |
-
Adding Geospatial Data
GEOADD cities -74.00597 40.71427 "NewYork"- cities = key name holding geospatial index
- Each entry requires: longitude, latitude, member name
- Redis converts data → geohash → stores in sorted set
-
Retrieve Coordinates of a City
GEOPOS cities "NewYork"Output:
1) 1) "-74.00596940505599976"
2) "40.71426910448555265"Redis returns the actual stored coordinates (with high precision).
-
Get Distance Between Cities
GEODIST cities "NewYork" "Chicago" kmOutput
1146.3023Redis uses spherical Earth approximation (Haversine formula).
-
Find Nearby Locations (Radius Query)
Example: Find cities within 1500 km of New York
GEORADIUS cities -74.00597 40.71427 1500 kmOutput:
1) "Chicago"
1) "NewYork"- Center → given manually (longitude/latitude)
- Radius → 1500 km
- Returns matching cities sorted by distance from center (closest first)
-
Radius Query Based on Another
Example: Cities within 1800 km of Chicago
GEORADIUSBYMEMBER cities "Chicago" 1800 kmOutput:
1) "NewYork"
1) "Chicago"- Uses Chicago’s coordinates as the center automatically
- Very useful for “find nearby users”, “find nearby restaurants”, etc.
-
Radius Query with Extra Details
Example: Include coordinates + distance + geohash
GEORADIUS cities -74 40 1500 km WITHCOORD WITHDIST WITHHASHOutput:
1) 1) "NewYork"
2) "14.1" ← distance
3) "3478007285230310" ← geohash
4) 1) "-74.0059" ← longitude
2) "40.7142" ← latitudeAdditional flags:
WITHDIST→ distance from centerWITHCOORD→ return lat/lonWITHHASH→ internal hash used in Redis
-
Get Geohash Values
GEOHASH cities "NewYork"Output:
1) "dr5regw3pg0"Geohashes provide:
- Location encoding
- Prefix similarity → spatial proximity (Locations close on map share geohash prefixes)