Redis geospatial

Introduction to the Redis Geospatial data type

Redis geospatial indexes let you store coordinates and search for them. This data structure is useful for finding nearby points within a given radius or bounding box.

Note:
Take care not to confuse the Geospatial data type with the Geospatial features in Redis Query Engine. Although there are some similarities between these two features, the data type is intended for simpler use cases and doesn't have the range of format options and queries available in Redis Query Engine.

Basic commands

  • GEOADD adds a location to a given geospatial index (note that longitude comes before latitude with this command).
  • GEOSEARCH returns locations with a given radius or a bounding box.

See the complete list of geospatial index commands.

Examples

Suppose you're building a mobile app that lets you find all of the bike rental stations closest to your current location.

Add several locations to a geospatial index:

> GEOADD bikes:rentable -122.27652 37.805186 station:1
(integer) 1
> GEOADD bikes:rentable -122.2674626 37.8062344 station:2
(integer) 1
> GEOADD bikes:rentable -122.2469854 37.8104049 station:3
(integer) 1
"""
Code samples for Geospatial doc pages:
    https://redis.io/docs/latest/develop/data-types/geospatial/
"""
import redis

r = redis.Redis(decode_responses=True)

res1 = r.geoadd("bikes:rentable", [-122.27652, 37.805186, "station:1"])
print(res1)  # >>> 1

res2 = r.geoadd("bikes:rentable", [-122.2674626, 37.8062344, "station:2"])
print(res2)  # >>> 1

res3 = r.geoadd("bikes:rentable", [-122.2469854, 37.8104049, "station:3"])
print(res3)  # >>> 1


res4 = r.geosearch(
    "bikes:rentable",
    longitude=-122.27652,
    latitude=37.805186,
    radius=5,
    unit="km",
)
print(res4)  # >>> ['station:1', 'station:2', 'station:3']

import assert from 'assert';
import { createClient } from 'redis';

const client = createClient();
await client.connect();


const res1 = await client.geoAdd('bikes:rentable', { 
  longitude: -122.27652,
  latitude: 37.805186,
  member: 'station:1'
});
console.log(res1)  // 1

const res2 = await client.geoAdd('bikes:rentable', {
  longitude: -122.2674626,
  latitude: 37.8062344,
  member: 'station:2'
});
console.log(res2)  // 1

const res3 = await client.geoAdd('bikes:rentable', {
  longitude: -122.2469854,
  latitude: 37.8104049,
  member: 'station:3'
})
console.log(res3)  // 1


const res4 = await client.geoSearch(
  'bikes:rentable', {
    longitude: -122.27652,
    latitude: 37.805186,
  },
  { radius: 5,
    unit: 'km'
  }
);
console.log(res4)  // ['station:1', 'station:2', 'station:3']

await client.close()
package io.redis.examples;

import redis.clients.jedis.GeoCoordinate;
import redis.clients.jedis.UnifiedJedis;
import redis.clients.jedis.args.GeoUnit;
import redis.clients.jedis.resps.GeoRadiusResponse;

import java.util.List;
import java.util.stream.Collectors;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class GeoExample {

  public void run() {
    try (UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379")) {

      long res1 = jedis.geoadd("bikes:rentable", -122.27652, 37.805186, "station:1");
      System.out.println(res1); // 1

      long res2 = jedis.geoadd("bikes:rentable", -122.2674626, 37.8062344, "station:2");
      System.out.println(res2); // 1

      long res3 = jedis.geoadd("bikes:rentable", -122.2469854, 37.8104049, "station:3");
      System.out.println(res2); // 1


      List<GeoRadiusResponse> res4 = jedis.geosearch(
          "bikes:rentable",
          new GeoCoordinate(-122.27652, 37.805186),
          5,
          GeoUnit.KM
      );
      List<String> members = res4.stream() //
          .map(GeoRadiusResponse::getMemberByString) //
          .collect(Collectors.toList());
      System.out.println(members); // [station:1, station:2, station:3]

    }
  }
}
package example_commands_test

import (
	"context"
	"fmt"

	"github.com/redis/go-redis/v9"
)


func ExampleClient_geoadd() {
	ctx := context.Background()

	rdb := redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "", // no password docs
		DB:       0,  // use default DB
	})


	res1, err := rdb.GeoAdd(ctx, "bikes:rentable",
		&redis.GeoLocation{
			Longitude: -122.27652,
			Latitude:  37.805186,
			Name:      "station:1",
		}).Result()

	if err != nil {
		panic(err)
	}

	fmt.Println(res1) // >>> 1

	res2, err := rdb.GeoAdd(ctx, "bikes:rentable",
		&redis.GeoLocation{
			Longitude: -122.2674626,
			Latitude:  37.8062344,
			Name:      "station:2",
		}).Result()

	if err != nil {
		panic(err)
	}

	fmt.Println(res2) // >>> 1

	res3, err := rdb.GeoAdd(ctx, "bikes:rentable",
		&redis.GeoLocation{
			Longitude: -122.2469854,
			Latitude:  37.8104049,
			Name:      "station:3",
		}).Result()

	if err != nil {
		panic(err)
	}

	fmt.Println(res3) // >>> 1

}

func ExampleClient_geosearch() {
	ctx := context.Background()

	rdb := redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "", // no password docs
		DB:       0,  // use default DB
	})


	res4, err := rdb.GeoSearch(ctx, "bikes:rentable",
		&redis.GeoSearchQuery{
			Longitude:  -122.27652,
			Latitude:   37.805186,
			Radius:     5,
			RadiusUnit: "km",
		},
	).Result()

	if err != nil {
		panic(err)
	}

	fmt.Println(res4) // >>> [station:1 station:2 station:3]

}

using NRedisStack.Tests;
using StackExchange.Redis;



public class GeoTutorial
{
    public void Run()
    {
        var muxer = ConnectionMultiplexer.Connect("localhost:6379");
        var db = muxer.GetDatabase();


        bool res1 = db.GeoAdd("bikes:rentable", -122.27652, 37.805186, "station:1");
        Console.WriteLine(res1);    // >>> True

        bool res2 = db.GeoAdd("bikes:rentable", -122.2674626, 37.8062344, "station:2");
        Console.WriteLine(res2);    // >>> True

        bool res3 = db.GeoAdd("bikes:rentable", -122.2469854, 37.8104049, "station:3");
        Console.WriteLine(res3);    // >>> True

        // Tests for 'geoadd' step.


        GeoRadiusResult[] res4 = db.GeoSearch("bikes:rentable",
            -122.27652,
            37.805186,
            new GeoSearchCircle(5, GeoUnit.Kilometers)
        );

        foreach (GeoRadiusResult member in res4)
        {
            Console.WriteLine($"Member: '{member.Member}', distance: {member.Distance}, position: {member.Position}");
        }
        // >>> Member: 'station:1', distance: 0.0001, position: -122.27652043104172 37.80518485897756
        // >>> Member: 'station:2', distance: 0.8047, position: -122.26745992898941 37.80623423353753
        // >>> Member: 'station:3', distance: 2.6596, position: -122.24698394536972 37.81040384984464

        // Tests for 'geosearch' step.


    }
}

Find all locations within a 5 kilometer radius of a given location, and return the distance to each location:

> GEOSEARCH bikes:rentable FROMLONLAT -122.2612767 37.7936847 BYRADIUS 5 km WITHDIST
1) 1) "station:1"
   2) "1.8523"
2) 1) "station:2"
   2) "1.4979"
3) 1) "station:3"
   2) "2.2441"
"""
Code samples for Geospatial doc pages:
    https://redis.io/docs/latest/develop/data-types/geospatial/
"""
import redis

r = redis.Redis(decode_responses=True)

res1 = r.geoadd("bikes:rentable", [-122.27652, 37.805186, "station:1"])
print(res1)  # >>> 1

res2 = r.geoadd("bikes:rentable", [-122.2674626, 37.8062344, "station:2"])
print(res2)  # >>> 1

res3 = r.geoadd("bikes:rentable", [-122.2469854, 37.8104049, "station:3"])
print(res3)  # >>> 1


res4 = r.geosearch(
    "bikes:rentable",
    longitude=-122.27652,
    latitude=37.805186,
    radius=5,
    unit="km",
)
print(res4)  # >>> ['station:1', 'station:2', 'station:3']

import assert from 'assert';
import { createClient } from 'redis';

const client = createClient();
await client.connect();


const res1 = await client.geoAdd('bikes:rentable', { 
  longitude: -122.27652,
  latitude: 37.805186,
  member: 'station:1'
});
console.log(res1)  // 1

const res2 = await client.geoAdd('bikes:rentable', {
  longitude: -122.2674626,
  latitude: 37.8062344,
  member: 'station:2'
});
console.log(res2)  // 1

const res3 = await client.geoAdd('bikes:rentable', {
  longitude: -122.2469854,
  latitude: 37.8104049,
  member: 'station:3'
})
console.log(res3)  // 1


const res4 = await client.geoSearch(
  'bikes:rentable', {
    longitude: -122.27652,
    latitude: 37.805186,
  },
  { radius: 5,
    unit: 'km'
  }
);
console.log(res4)  // ['station:1', 'station:2', 'station:3']

await client.close()
package io.redis.examples;

import redis.clients.jedis.GeoCoordinate;
import redis.clients.jedis.UnifiedJedis;
import redis.clients.jedis.args.GeoUnit;
import redis.clients.jedis.resps.GeoRadiusResponse;

import java.util.List;
import java.util.stream.Collectors;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class GeoExample {

  public void run() {
    try (UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379")) {

      long res1 = jedis.geoadd("bikes:rentable", -122.27652, 37.805186, "station:1");
      System.out.println(res1); // 1

      long res2 = jedis.geoadd("bikes:rentable", -122.2674626, 37.8062344, "station:2");
      System.out.println(res2); // 1

      long res3 = jedis.geoadd("bikes:rentable", -122.2469854, 37.8104049, "station:3");
      System.out.println(res2); // 1


      List<GeoRadiusResponse> res4 = jedis.geosearch(
          "bikes:rentable",
          new GeoCoordinate(-122.27652, 37.805186),
          5,
          GeoUnit.KM
      );
      List<String> members = res4.stream() //
          .map(GeoRadiusResponse::getMemberByString) //
          .collect(Collectors.toList());
      System.out.println(members); // [station:1, station:2, station:3]

    }
  }
}
package example_commands_test

import (
	"context"
	"fmt"

	"github.com/redis/go-redis/v9"
)


func ExampleClient_geoadd() {
	ctx := context.Background()

	rdb := redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "", // no password docs
		DB:       0,  // use default DB
	})


	res1, err := rdb.GeoAdd(ctx, "bikes:rentable",
		&redis.GeoLocation{
			Longitude: -122.27652,
			Latitude:  37.805186,
			Name:      "station:1",
		}).Result()

	if err != nil {
		panic(err)
	}

	fmt.Println(res1) // >>> 1

	res2, err := rdb.GeoAdd(ctx, "bikes:rentable",
		&redis.GeoLocation{
			Longitude: -122.2674626,
			Latitude:  37.8062344,
			Name:      "station:2",
		}).Result()

	if err != nil {
		panic(err)
	}

	fmt.Println(res2) // >>> 1

	res3, err := rdb.GeoAdd(ctx, "bikes:rentable",
		&redis.GeoLocation{
			Longitude: -122.2469854,
			Latitude:  37.8104049,
			Name:      "station:3",
		}).Result()

	if err != nil {
		panic(err)
	}

	fmt.Println(res3) // >>> 1

}

func ExampleClient_geosearch() {
	ctx := context.Background()

	rdb := redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "", // no password docs
		DB:       0,  // use default DB
	})


	res4, err := rdb.GeoSearch(ctx, "bikes:rentable",
		&redis.GeoSearchQuery{
			Longitude:  -122.27652,
			Latitude:   37.805186,
			Radius:     5,
			RadiusUnit: "km",
		},
	).Result()

	if err != nil {
		panic(err)
	}

	fmt.Println(res4) // >>> [station:1 station:2 station:3]

}

using NRedisStack.Tests;
using StackExchange.Redis;



public class GeoTutorial
{
    public void Run()
    {
        var muxer = ConnectionMultiplexer.Connect("localhost:6379");
        var db = muxer.GetDatabase();


        bool res1 = db.GeoAdd("bikes:rentable", -122.27652, 37.805186, "station:1");
        Console.WriteLine(res1);    // >>> True

        bool res2 = db.GeoAdd("bikes:rentable", -122.2674626, 37.8062344, "station:2");
        Console.WriteLine(res2);    // >>> True

        bool res3 = db.GeoAdd("bikes:rentable", -122.2469854, 37.8104049, "station:3");
        Console.WriteLine(res3);    // >>> True

        // Tests for 'geoadd' step.


        GeoRadiusResult[] res4 = db.GeoSearch("bikes:rentable",
            -122.27652,
            37.805186,
            new GeoSearchCircle(5, GeoUnit.Kilometers)
        );

        foreach (GeoRadiusResult member in res4)
        {
            Console.WriteLine($"Member: '{member.Member}', distance: {member.Distance}, position: {member.Position}");
        }
        // >>> Member: 'station:1', distance: 0.0001, position: -122.27652043104172 37.80518485897756
        // >>> Member: 'station:2', distance: 0.8047, position: -122.26745992898941 37.80623423353753
        // >>> Member: 'station:3', distance: 2.6596, position: -122.24698394536972 37.81040384984464

        // Tests for 'geosearch' step.


    }
}

Learn more

RATE THIS PAGE
Back to top ↑