Skip to main content

What are Geospatial types in Redis?

Geospatial types in Redis are a set of commands that let you store and process geographic coordinates (longitude and latitude), and run fast geospatial queries, for example, finding nearby points or calculating the distance between them.

Redis has no separate "geo type", geodata is stored inside a Sorted Set (ZSet), where the score is used to encode the coordinates.

How this is set up

Every location is a (longitude, latitude) pair, converted into a special numeric code (a Geohash). That code is stored as the score in a sorted set (ZSet). This lets Redis:

  • add points to a map,
  • find the points nearest to a given one,
  • calculate distances,
  • filter by radius.

Main commands

CommandDescription
GEOADD key longitude latitude member [longitude latitude member ...]add one or several points
GEOPOS key member [member ...]get a point's coordinates
GEODIST key member1 member2 [unit]calculate the distance between two points
GEORADIUS key longitude latitude radius unit [options]find points within a radius (deprecated, replaced by GEOSEARCH)
GEOSEARCH key FROMMEMBER <member> BYRADIUS <radius> <unit>find points around another point
GEOSEARCH key FROMLONLAT <lon> <lat> BYBOX <width> <height> <unit>search within an area (a rectangle)
GEOHASH key member [member ...]get geohashes (as short strings)

Example

bash
GEOADD cities 37.618423 55.751244 "Moscow" GEOADD cities 30.31413 59.93863 "Saint-Petersburg" GEODIST cities "Moscow" "Saint-Petersburg" km

Result:

javascript
633.4789

A radius-search example

bash
GEOADD shops 37.6 55.7 "Shop1" 37.65 55.75 "Shop2" 37.7 55.8 "Shop3" GEOSEARCH shops FROMLONLAT 37.61 55.74 BYRADIUS 10 km WITHDIST

Result:

javascript
1) "Shop1" (0.4 km) 2) "Shop2" (5.7 km) 3) "Shop3" (9.8 km)

Units of measurement

Supported units:

  • m, meters
  • km, kilometers
  • mi, miles
  • ft, feet

Internal structure

  • Every point is stored in a ZSet, where score is a 52-bit geo-coded value (a Geohash).
  • Redis uses a Mercator projection algorithm to approximately convert coordinates into numbers.
  • Search runs through range operations on the score, which makes it very fast, O(log N).

Uses

  • Finding the nearest shops, delivery points, or drivers.
  • Geo-analytics, point density, activity by region.
  • Games and logistics systems with geolocation.
  • Real-time object tracking.

A practical example

bash
GEOADD couriers 37.61 55.75 "Courier:101" GEOADD couriers 37.63 55.76 "Courier:102" GEOSEARCH couriers FROMMEMBER "Courier:101" BYRADIUS 2 km WITHDIST

Every courier within 2 km of a given one can be found instantly.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.