Geospatial Indexes

Learn how to use the geospatial data type to store and query coordinate data in Redis.

Geospatial

The Redis geospatial data type allows us to store location data in the form of coordinates. Once stored, we can use geospatial indexes to query this data in different ways. For example, it can be used to find the distance between two locations or places within a certain radius.

Geospatial commands

To better understand how geospatial indexes work in Redis, let’s explore some of the commands associated with this data type.

The GeoAdd command

The GeoAdd command is used to add data to a geospatial index. In the following example, we add the member city1 with a latitude and longitude (coordinates) of 40 and -83, respectively, to an index named cities:

client.GeoAdd(context.Background(), "cities", &redis.GeoLocation{Name: "city-1", Latitude: 40, Longitude: -83})
Add coordinates to a geospatial index

The GeoPos command

With the GeoPos command, we can query for the coordinates of one or more members of a geospatial index. For example, we can find the location for city1 in the index cities:

coordinates := client.GeoPos(context.Background(), "cities", "city1").Val()
Query coordinate location in a geospatial index

The GeoDist command

The GeoDist command lets us find the distance between two members (locations) of a geospatial index. In the following example, we calculate the distance (in miles) between city1 and city2, which are stored in the cities index.

distance := client.GeoDist(context.Background(), "cities", "city1", "city2", "mi").Val()
Find the distance between two members of a geospatial index

Run sample code

Now that you have an overview of the basic geospatial operations, you can ...