How to handle geospatial data in Redis
Overview
Geospatial data in Redis is represented in terms of longitude and latitude. The geospatial data is stored as a sorted set, as it makes it possible to query the items.
Some of the most frequently used commands for geospatial data in Redis are as follows:
The GEOADD command
The GEOADD command is used to add the specified geospatial data to the given key.
Syntax
The syntax is as follows:
GEOADD key longitude latitude member [ longitude latitude member ...]
where:
keyis the name under which the sorted set for geospatial data is registered.longitudeis the longitude of the location.latitudeis the latitude of the location.memberis the member to store.
The GEODIST command
The GEODIST command is used to get the distance between two geospatial members or points in the specified unit.
Syntax
The syntax is as follows:
GEODIST key member1 member2 [ M | KM | FT | MI]
where:
keyis the name under which the sorted set for geospatial data is registered.member1is the first geospatial member or point.member2is the second geospatial member or point.
The following units of distance are supported.
The unit must be one of the following and defaults to meters:
mfor meters.kmfor kilometers.mifor miles.ftfor feet.
The GEOSEARCH command
The GEOSEARCH command is used to return the members of a geospatial populated sorted set that are within the borders of the area specified by a given shape. This command supports searching in circular as well as rectangular areas.
Syntax
The syntax is as follows:
GEOSEARCH key FROMMEMBER member | FROMLONLAT longitude latitude BYRADIUS radius M | KM | FT | MI | BYBOX width height M | KM | FT | MI [ ASC | DESC]
where:
keyis the name under which the sorted set for geospatial data is registered.
The reference center point for querying is provided by either of the following mandatory options:
FROMMEMBER: This option indicates to use the given member in the sorted set.FROMLONLAT: This option indicates to use the given longitude and latitude.
The search shape for querying is provided by either of the following mandatory options:
BYRADIUS: Search in a circular area according to the given radius.BYBOX: Search in a rectangle according to the given height and width.
To sort the returned results, use one of the following options:
ASC: This option indicates that the results should be sorted in relation to the central point from nearest to farthest.DESC: This option indicates that the results should be sorted in relation to the central point from farthest to nearest.
The GEOPOS command
The GEOPOS command is used to get the positions (longitude, latitude) of all the specified members.
Syntax
The syntax is as follows:
GEOPOS key member [member ...]
where:
keyis the name under which the sorted set for geospatial data is registered.memberis the member whose position has to be retrieved.