0
0
Redisquery~5 mins

Geo-proximity with sorted sets in Redis

Choose your learning style9 modes available
Introduction

Geo-proximity helps find places near a location quickly. Sorted sets store locations with scores to keep them ordered by distance.

Finding nearby restaurants to a user's current location.
Showing gas stations close to a car's GPS position.
Locating friends near you in a social app.
Finding delivery points within a certain radius.
Sorting places by how close they are to a given spot.
Syntax
Redis
GEOADD key longitude latitude member
GEORADIUS key longitude latitude radius m|km|ft|mi [WITHDIST] [WITHCOORD] [COUNT count]

GEOADD adds a location with longitude and latitude to a sorted set.

GEORADIUS finds members within a radius from a point, sorted by distance (ascending).

Examples
Adds the location "Palermo" with given longitude and latitude to the sorted set named "places".
Redis
GEOADD places 13.361389 38.115556 "Palermo"
Finds all places within 200 kilometers of longitude 15 and latitude 37, returns distances, sorted from nearest to farthest.
Redis
GEORADIUS places 15 37 200 km WITHDIST
Finds up to 3 places within 100 kilometers, sorted from nearest to farthest.
Redis
GEORADIUS places 15 37 100 km COUNT 3 WITHDIST
Sample Program

This adds two cities to the sorted set "cities" and then finds all cities within 200 km of longitude 15 and latitude 37, showing their distances sorted nearest first.

Redis
GEOADD cities 13.361389 38.115556 "Palermo" 15.087269 37.502669 "Catania"
GEORADIUS cities 15 37 200 km WITHDIST
OutputSuccess
Important Notes

Longitude comes before latitude in GEOADD and GEORADIUS commands.

Distances returned by GEORADIUS are in the unit you specify (m, km, ft, mi).

Sorted sets keep locations ordered by their geohash score internally.

Summary

Use GEOADD to store locations with longitude and latitude.

Use GEORADIUS to find nearby locations within a radius.

You can get distances and sort results by proximity easily.