Redis Geospatial by example

Photo by NASA on Unsplash

Redis Support Geospatial index backed by Sorted Set. and the sorted set is similar to regular set beside it keeps a score for each element in the set.

Redis saves longitude and latitude in the score of the sorted set and the name for the location as the sorted set member.

Geospatial data saved as a sorted set in Redis

Redis has a group of handy commands — besides some operations from the sorted set- we will talk about such commands here.

Redis Geospatial commands

GEOADD: Add/update the longitude and latitude of a member in the geospatial index.> GEOADD cities 31.2233591 30.0595581 Cairo 29.8846742 31.2242386 Alexandria  30.981804 30.7930755 Tanta
(integer) 3

GEODIST: return the distance between two members in an index by different units (m, km, ft ormi)

Get distance between Cairo and Alex in kilometers:> GEODIST cities Cairo Alexandria km

GEORADIUS and GEORADIUSBYMEMBER: return the members within the radius (by m, km, ft or mi) of a point or another member

Get all members near the longitude 31.6075433 and latitude 30.0918454 (of Madinty 😀) within 100 kilometers:> GEORADIUS cities 31.6075433 30.0918454 100 km
1) "Cairo"
2) "Tanta"

we can pass WITHCOORD, WITHDIST and WITHHASH to return coordination (longitude and latitude), distance, and hash for each member of the result.> GEORADIUS cities 31.6075433 30.0918454 100 km WITHDIST
1) 1) "Cairo"
2) "37.1524"
2) 1) "Tanta"
2) "98.4055"

GEORADIUSBYMEMBER instead of accepting arbitrary longitude and latitude, it accepts a member and returns members in the Radius of such member.

GEOPOS: Returns the longitude and latitude of a member(s) in the geospatial index.> GEOPOS cities Alexandria
1) 1) "29.88467663526535034"
2) "31.22423761856266111"

You can use some of the Commands that apply to stored sets like ZRANGE and ZREM et..

Software Developer/Architect

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store