This is the eighth post of The Redis Series.
Part One: Install Redis inside Ubuntu VM
Part Two: Redis Persistence by Example
Part Three: Implement game leaderboard using Redis
Part Four: Implement Job Queue using Redis
Part Five: Building REST API backed by Redis
Part Six: Building Chat Service in Golang and Websockets backed by Redis
Part Seven: Redis Cluster configurations by example
Part Eight: Redis Geospatial by example 👈
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.
Commands
Redis has a group of handy commands — besides some operations from the sorted set- we will talk about such commands here.
GEOADD
: Add/update the longitude and latitude of a member in the geospatial index.
127.0.0.1:6379> 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:
127.0.0.1:6379> GEODIST cities Cairo Alexandria km
"182.1844"
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:
127.0.0.1:6379> 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.
127.0.0.1:6379> 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.
127.0.0.1:6379> 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..
References: