Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 42 ยท Specialized Data Types

Geospatial Indexes

Learn Redis geospatial indexes: GEOADD, GEOPOS, GEODIST, GEOHASH and GEOSEARCH, how geohash scores live in sorted sets, and nearby search, with live demos.

Redis can store places and answer "what is near here?" questions. The geospatial commands (GEOADD, GEOPOS, GEODIST, GEOHASH, GEOSEARCH) let you add named points with a longitude and latitude, measure the distance between two of them, and find every point within a radius or inside a box. Typical jobs are "stores near me", "drivers within 2 km of this pickup", or "is this delivery address inside our service area?".

There is no separate geo data type. A geospatial index is a sorted set: each place is a member, and its score is a 52-bit number called a geohash that encodes the coordinates. Everything you know about sorted sets applies: ZRANGE lists the places, ZREM removes one, ZCARD counts them, and the key's TYPE is zset. The geo commands add the encoding, the decoding and the distance maths on top.

Real Redis cannot run on this page, so the redis-cli snippets are read-only. The runnable examples are JavaScript stand-ins that re-implement the real encoding (the same 52-bit interleaved geohash) and the real distance formula (haversine with Redis's earth radius), so scores, hashes and distances match what a server prints. The stand-in scans all points for a search, whereas Redis only looks at nearby cells of the sorted set; the second TryIt shows how that trick works.

Places in a sorted set

Member The place name, such as store:12.
Score A 52-bit geohash of lon and lat.
Normal zset ZRANGE, ZREM and ZCARD all work.
1 / 2

Adding places and measuring distance

GEOADD key longitude latitude member [longitude latitude member ...] adds places and returns how many were new. Longitude comes first, which is the opposite of how people usually say coordinates, and is a classic source of bugs. Valid longitudes run from -180 to 180 and latitudes from about -85.05 to 85.05 (the limit of the projection the encoding uses); anything else is an error. Adding an existing member again updates its position.

Text
127.0.0.1:6379> GEOADD Sicily 13.361389 38.115556 Palermo 15.087269 37.502669 Catania
(integer) 2
127.0.0.1:6379> GEODIST Sicily Palermo Catania
"166274.1516"
127.0.0.1:6379> GEODIST Sicily Palermo Catania km
"166.2742"
  • GEODIST key member1 member2 [m|km|ft|mi] returns the distance (meters by default) or (nil) if a member does not exist.
  • GEOPOS key member [member ...] returns the coordinates, or (nil) for unknown members. The values are slightly rounded versions of what you stored, because the 52-bit hash has finite resolution (about 0.6 meters).
  • GEOHASH key member [member ...] returns the standard 11-character geohash string, which you can paste into other geohash tools and use as a URL-friendly cell name.

The first TryIt implements the encoding and these commands. Compare its numbers with the ones above, then run ZRANGE on the geo key to see that the scores are ordinary sorted-set scores. The emulator prints coordinates with six decimals; real Redis prints many more digits.

JS GEOADD, GEODIST and GEOSEARCH in the emulator

Press Run (or Ctrl + Enter) to see the console output here.

No output.

If your numbers match the transcript above (166274.1516 meters, sqc8b49rny0 for Palermo), the encoding is the real one. Note the two GEOSEARCH shapes: BYRADIUS finds points inside a circle, BYBOX width height inside a rectangle whose sides are measured in the chosen unit.

Searching nearby

GEOSEARCH key FROMMEMBER member | FROMLONLAT lon lat BYRADIUS radius unit | BYBOX width height unit [ASC|DESC] [COUNT n [ANY]] [WITHCOORD] [WITHDIST] [WITHHASH] is the search command. The center is either an existing member or a free coordinate pair (the user's phone location, say). ASC sorts nearest first, COUNT n keeps the first n results, and the WITH... flags add the distance, coordinates and raw score to each result. GEOSEARCHSTORE does the same but writes the matches into another key (add STOREDIST to store distances as scores). The older GEORADIUS and GEORADIUSBYMEMBER commands still exist but are deprecated in favour of GEOSEARCH (Redis 6.2+).

Deleting and listing use sorted-set commands: ZREM removes a place, ZRANGE lists place names, ZCARD counts them. There is no GEODEL.

How the search stays fast

The geohash interleaves the bits of the latitude and the longitude, so points that share a long prefix of the score lie in the same small rectangle of the map. Because a sorted set can fetch a score range in O(log N + M), "everything in this rectangle" becomes one range query. A single rectangle is not enough: the center of your search may sit near a cell border, so Redis picks a cell size from the radius, takes the center cell and its eight neighbours, fetches each score range, and finally filters the candidates with the exact distance formula. The second TryIt does exactly that on 5,000 generated coffee shops and compares it with scanning all of them.

JS Why nearby search is fast: score ranges

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The cell method examined 176 of the 5,000 points yet returned exactly what a full scan returns. A larger dataset only changes the first number: the work follows the number of points near the search, not the size of the whole index.

Practical advice

  • Longitude first. GEOADD key lon lat member, and the same order in GEOSEARCH FROMLONLAT.
  • One key per area or category keeps each sorted set small enough to search quickly. Millions of points in one key work, but a single huge GEOSEARCH with a big radius returns lots of data; use COUNT and a sensible radius. Note that COUNT n ANY is faster but returns some matches, not the nearest.
  • Moving objects. GEOADD with a new position simply overwrites the old one, so a driver app can update a driver key every few seconds. Expire stale drivers yourself (a sorted set cannot expire members), for example by also keeping a timestamp sorted set and removing old members with ZREMRANGEBYSCORE.
  • Accuracy. Distances assume a perfect sphere, so expect an error up to roughly 0.5% compared with surveying-grade results; use a dedicated GIS database such as PostGIS when you need polygons, routes or exact geodesics.
  • Not for the poles. Latitudes beyond about 85.05 degrees are rejected.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In which order do you pass coordinates to GEOADD?

    GEOADD takes longitude first, then latitude, then the member name. Swapping them is a common bug, and out-of-range values are rejected.
  2. 2. What data type is a Redis geospatial index?

    GEOADD stores each place as a sorted-set member with a 52-bit geohash score, so ZRANGE, ZREM and ZCARD work on it and TYPE reports zset.
  3. 3. How do you remove a place from a geo index?

    There is no GEODEL. Because the index is a sorted set, ZREM removes a member.
  4. 4. Why does GEOSEARCH check a center cell and its eight neighbours?

    Geohash cells are rectangles. Points within the radius can lie just across a border, so adjacent cells' score ranges are fetched too, and the exact distance filter removes the extras.
  5. 5. Which statement about GEOPOS results is correct?

    The 52-bit hash has finite resolution of well under a meter, so GEOPOS returns the center of that cell, which may differ from the input in the later decimals.

Summary

  • GEOADD key lon lat member stores places (longitude first) in a sorted set whose score is a 52-bit geohash.
  • GEODIST, GEOPOS and GEOHASH read distances, coordinates and 11-character geohash strings; GEOSEARCH finds places by radius or box.
  • Search works on score ranges: the center cell and its eight neighbours are fetched, then candidates are filtered by exact haversine distance.
  • Remove places with ZREM, list them with ZRANGE; there is no geo-specific delete.
  • Distances assume a sphere, latitudes are limited to about plus or minus 85.05, and expiring members is your job.

Next, bring all the data types together in Choosing the Right Data Type.