Redis Command: GEODIST

Summary

Command NameGEODIST
UsageDistance between two geo index members
Group geo
ACL Category@read
@geo
@slow
Time ComplexityO(1)
FlagREADONLY
Arity-4

Signature

GEODIST <key> <member1> <member2> [M|KM|FT|MI]

Usage

Get the distance between 2 members/items saved in geospatial index. Geospatial information is saved in a sorted set data structure, when added with GEOADD command. This GEODIST command helps us to get the distance between 2 members saved in the geoindex.

NOTES

  • A 0.5% error is possible while calculating the distance between 2 members, because of the inconsistent shape of the earth.
  • This command can return distance in units like meters(m), kilometers(km), miles(mi), or feet(ft)

Arguments

ParameterGroupDescriptionNameTypeOptional
<key>Name of the key that holds the geo indexkeykey
<member1>Name of the first member location saved in the geo indexmember1string
<member2>Name of the second member location saved in the geo indexmember2string
MunitReturn distance in meter unitmpure-tokenTrue
KMunitReturn distance in kilometer unitkmpure-tokenTrue
FTunitReturn distance in feet unitftpure-tokenTrue
MIunitReturn distance in mile unitmipure-tokenTrue

NOTES

  • Default unit of distance is meters(m). If none of the unit params are provided then the returned value will be in meter unit.

Return Value

Return valueCase for the return valueType
DistanceOn success, it returns the distance between 2 members that are providedstring
(nil)If one or both members are missingnull
errorIf the applied to the wrong data type.error

NOTES

  • The return distance is actually a double value, but represented as a string.
  • If the command is applied to a key that is not a hash, then the following error is returned-
    (error) WRONGTYPE Operation against a key holding the wrong kind of value

Examples

Here are a few examples of the usage examples of the Redis GEODIST command-

# Redis GEODIST command examples

# Add city longitude and latitude to geoindex named bigboxcity
127.0.0.1:6379> geoadd bigboxcity 2.352222 48.856613 Paris 100.501762 13.756331 Bangkok 114.109497 22.396427 "Hong Kong" 139.691711 35.689487 Tokyo 12.496365 41.902782 Rome
(integer) 5

# Check the items in bigboxcity
127.0.0.1:6379> zrange bigboxcity 0 -1
1) "Rome"
2) "Paris"
3) "Bangkok"
4) "Hong Kong"
5) "Tokyo"

# Check distance of Paris and Tokyo
# This distance is in meter unit, as meter is the default
127.0.0.1:6379> geodist bigboxcity Paris Tokyo
"9714811.3348"

# Check distance of Paris and Hong Kong
# This distance is in kilometer as we provide km to the command
127.0.0.1:6379> geodist bigboxcity Paris "Hong Kong" km
"9618.5790"

# Distance to the same city will be zero
127.0.0.1:6379> geodist bigboxcity Paris Paris
"0.0000"

# We get (nil) if one or both of the cities do not exist in our geoindex
127.0.0.1:6379> geodist bigboxcity Paris "unknown city"
(nil)

# Set a string
127.0.0.1:6379> set bigboxstr "test string here"
OK

# Try to add GEODIST on a string
# We get a type error
127.0.0.1:6379> geodist bigboxstr Paris Tokyo
(error) WRONGTYPE Operation against a key holding the wrong kind of value

Code Implementations

Redis GEODIST command example implementation in Golang, NodeJS, Java, C#, PHP, Python, Ruby-

// Redis GEODIST command example in Golang

package main

import (
	"context"
	"fmt"

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

var rdb *redis.Client
var ctx context.Context

func init() {
	rdb = redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Username: "default",
		Password: "",
		DB:       0,
	})

	ctx = context.Background()
}

func main() {

	/**
	* Add city longitude and latitude to geoindex named bigboxcity
	* Command: geoadd bigboxcity 2.352222 48.856613 Paris 100.501762 13.756331 Bangkok 114.109497 22.396427 "Hong Kong" 139.691711 35.689487 Tokyo 12.496365 41.902782 Rome
	* Result: (integer) 5
	 */
	getaddResult, err := rdb.GeoAdd(ctx, "bigboxcity",
		&redis.GeoLocation{Longitude: 2.352222, Latitude: 48.856613, Name: "Paris"},
		&redis.GeoLocation{Longitude: 100.501762, Latitude: 13.756331, Name: "Bangkok"},
		&redis.GeoLocation{Longitude: 114.109497, Latitude: 22.396427, Name: "Hong Kong"},
		&redis.GeoLocation{Longitude: 139.691711, Latitude: 35.689487, Name: "Tokyo"},
		&redis.GeoLocation{Longitude: 12.496365, Latitude: 41.902782, Name: "Rome"},
	).Result()

	if err != nil {
		fmt.Println("Command: geoadd bigboxcity 2.352222 48.856613 Paris 100.501762 13.756331 Bangkok 114.109497 22.396427 "Hong Kong" 139.691711 35.689487 Tokyo 12.496365 41.902782 Rome | Error: " + err.Error())
	}

	fmt.Println("Command: geoadd bigboxcity 2.352222 48.856613 Paris 100.501762 13.756331 Bangkok 114.109497 22.396427 "Hong Kong" 139.691711 35.689487 Tokyo 12.496365 41.902782 Rome | Result: ", getaddResult)

	/**
	* Check the items in bigboxcity
	* Command: zrange bigboxcity 0 -1
	* Result:
	*      1) "Rome"
	*      2) "Paris"
	*      3) "Bangkok"
	*      4) "Hong Kong"
	*      5) "Tokyo"
	 */
	zrangeResult, err := rdb.ZRange(ctx, "bigboxcity", 0, -1).Result()

	if err != nil {
		fmt.Println("Command: zrange bigboxcity 0 -1 withscores | Error: " + err.Error())
	}

	fmt.Println("Command: zrange bigboxcity 0 -1 withscores | Result: ", zrangeResult)

	/**
	* Check distance of Paris and Tokyo
	* This distance is in meter unit, as meter is the default
	*
	* Command: geodist bigboxcity Paris Tokyo
	* Result: "9714811.3348"
	 */
	geodistResult, err := rdb.GeoDist(ctx, "bigboxcity", "Paris", "Tokyo", "M").Result()

	if err != nil {
		fmt.Println("Command: geodist bigboxcity Paris Tokyo | Error: " + err.Error())
	}

	fmt.Println("Command: geodist bigboxcity Paris Tokyo | Result: ", geodistResult)

	/**
	* Check distance of Paris and Hong Kong
	* This distance is in kilometer as we provide km to the command
	*
	* Command: geodist bigboxcity Paris "Hong Kong" km
	* Result: "9618.5790"
	 */
	geodistResult, err = rdb.GeoDist(ctx, "bigboxcity", "Paris", "Hong Kong", "KM").Result()

	if err != nil {
		fmt.Println("Command: geodist bigboxcity Paris "Hong Kong" km | Error: " + err.Error())
	}

	fmt.Println("Command: geodist bigboxcity Paris "Hong Kong" km | Result: ", geodistResult)

	/**
	* Distance to the same city will be zero
	*
	* Command: geodist bigboxcity Paris Paris
	* Result: "0.0000"
	 */
	geodistResult, err = rdb.GeoDist(ctx, "bigboxcity", "Paris", "Paris", "M").Result()

	if err != nil {
		fmt.Println("Command: geodist bigboxcity Paris Paris | Error: " + err.Error())
	}

	fmt.Println("Command: geodist bigboxcity Paris Paris | Result: ", geodistResult)

	/**
	* We get (nil) if one or both of the cities do not exist in our geoindex
	*
	* Command: geodist bigboxcity Paris "unknown city"
	* Result: (nil)
	 */
	geodistResult, err = rdb.GeoDist(ctx, "bigboxcity", "Paris", "unknown city", "M").Result()

	if err != nil {
		fmt.Println("Command: geodist bigboxcity Paris "unknown city" | Error: " + err.Error())
	}

	fmt.Println("Command: geodist bigboxcity Paris "unknown city" | Result: ", geodistResult)

	/**
	* Set a string
	*
	* Command: set bigboxstr "test string here"
	* Result: OK
	 */
	setResult, err := rdb.Set(ctx, "bigboxstr", "test string here", 0).Result()

	if err != nil {
		fmt.Println("Command: set bigboxstr "test string here" | Error: " + err.Error())
	}

	fmt.Println("Command: set bigboxstr "test string here" | Result: ", setResult)

	/**
	* Try to add GEODIST on a string
	* We get a type error
	*
	* Command: geodist bigboxstr Paris Tokyo
	* Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
	 */
	geodistResult, err = rdb.GeoDist(ctx, "bigboxstr", "Paris", "Tokyo", "M").Result()

	if err != nil {
		fmt.Println("Command: geodist bigboxstr Paris Tokyo | Error: " + err.Error())
	}

	fmt.Println("Command: geodist bigboxstr Paris Tokyo | Result: ", geodistResult)

}

Output:

Command: geoadd bigboxcity 2.352222 48.856613 Paris 100.501762 13.756331 Bangkok 114.109497 22.396427 "Hong Kong" 139.691711 35.689487 Tokyo 12.496365 41.902782 Rome | Result:  5
Command: zrange bigboxcity 0 -1 withscores | Result:  [Rome Paris Bangkok Hong Kong Tokyo]
Command: geodist bigboxcity Paris Tokyo | Result:  9.7148113348e+06
Command: geodist bigboxcity Paris "Hong Kong" km | Result:  9618.579
Command: geodist bigboxcity Paris Paris | Result:  0
Command: geodist bigboxcity Paris "unknown city" | Error: redis: nil
Command: geodist bigboxcity Paris "unknown city" | Result:  0
Command: set bigboxstr "test string here" | Result:  OK
Command: geodist bigboxstr Paris Tokyo | Error: WRONGTYPE Operation against a key holding the wrong kind of value
Command: geodist bigboxstr Paris Tokyo | Result:  0

NOTES

  • Use “GeoDist” method from redis-go module.
  • Signature of the method is-
    GeoDist(ctx context.Context, key string, member1, member2, unit string) *FloatCmd
// Redis GEODIST command example in JavaScript(NodeJS)

import { createClient } from "redis";

// Create redis client
const redisClient = createClient({
  url: "redis://default:@localhost:6379",
});

redisClient.on("error", (err) =>
  console.log("Error while connecting to Redis", err)
);

// Connect Redis client
await redisClient.connect();


/**
 * Add city longitude and latitude to geoindex named bigboxcity
 * Command: geoadd bigboxcity 2.352222 48.856613 Paris 100.501762 13.756331 Bangkok 114.109497 22.396427 "Hong Kong" 139.691711 35.689487 Tokyo 12.496365 41.902782 Rome
 * Result: (integer) 5
 */
const locationData = [
  {
    member: "Paris",
    longitude: 2.352222,
    latitude: 48.856613,
  },
  {
    member: "Bangkok",
    longitude: 100.501762,
    latitude: 13.756331,
  },
  {
    member: "Hong Kong",
    longitude: 114.109497,
    latitude: 22.396427,
  },
  {
    member: "Tokyo",
    longitude: 139.691711,
    latitude: 35.689487,
  },
  {
    member: "Rome",
    longitude: 12.496365,
    latitude: 41.90278,
  },
];
let commandResult = await redisClient.geoAdd("bigboxcity", locationData);

console.log("Command: geoadd bigboxcity 2.352222 48.856613 Paris 100.501762 13.756331 Bangkok 114.109497 22.396427 "Hong Kong" 139.691711 35.689487 Tokyo 12.496365 41.902782 Rome | Result: ", commandResult);

/**
* Check the items in bigboxcity
* Command: zrange bigboxcity 0 -1
* Result:
*      1) "Rome"
*      2) "Paris"
*      3) "Bangkok"
*      4) "Hong Kong"
*      5) "Tokyo"
*/
commandResult = await redisClient.zRange("bigboxcity", 0, -1);

console.log("Command: zrange bigboxcity 0 -1 withscores | Result: ", commandResult);

/**
* Check distance of Paris and Tokyo
* This distance is in meter unit, as meter is the default
*
* Command: geodist bigboxcity Paris Tokyo
* Result: "9714811.3348"
*/
commandResult = await redisClient.geoDist("bigboxcity", "Paris", "Tokyo");

console.log("Command: geodist bigboxcity Paris Tokyo | Result: ", commandResult);

/**
* Check distance of Paris and Hong Kong
* This distance is in kilometer as we provide km to the command
*
* Command: geodist bigboxcity Paris "Hong Kong" km
* Result: "9618.5790"
*/
commandResult = await redisClient.geoDist("bigboxcity", "Paris", "Hong Kong", 'km');

console.log("Command: geodist bigboxcity Paris "Hong Kong" km | Result: ", commandResult);

/**
* Distance to the same city will be zero
*
* Command: geodist bigboxcity Paris Paris
* Result: "0.0000"
*/
commandResult = await redisClient.geoDist("bigboxcity", "Paris", "Paris");

console.log("Command: geodist bigboxcity Paris Paris | Result: ", commandResult);

/**
* We get (nil) if one or both of the cities do not exist in our geoindex
*
* Command: geodist bigboxcity Paris "unknown city"
* Result: (nil)
*/
commandResult = await redisClient.geoDist("bigboxcity", "Paris", "unknown city");

console.log("Command: geodist bigboxcity Paris "unknown city" | Result: ", commandResult);

/**
* Set a string
*
* Command: set bigboxstr "test string here"
* Result: OK
*/
commandResult = await redisClient.set("bigboxstr", "test string here");

console.log("Command: set bigboxstr "test string here" | Result: ", commandResult);

/**
* Try to add GEODIST on a string
* We get a type error
*
* Command: geodist bigboxstr Paris Tokyo
* Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
*/
try {
  commandResult = await redisClient.geoDist("bigboxstr", "Paris", "Tokyo");

  console.log("Command: geodist bigboxstr Paris Tokyo | Result: ", commandResult);
} catch (err) {
  console.log("Command: geodist bigboxstr Paris Tokyo | Result: ", err);
}

process.exit(0);

Output:

Command: geoadd bigboxcity 2.352222 48.856613 Paris 100.501762 13.756331 Bangkok 114.109497 22.396427 "Hong Kong" 139.691711 35.689487 Tokyo 12.496365 41.902782 Rome | Result:  5
Command: zrange bigboxcity 0 -1 withscores | Result:  [ 'Rome', 'Paris', 'Bangkok', 'Hong Kong', 'Tokyo' ]
Command: geodist bigboxcity Paris Tokyo | Result:  9714811.3348
Command: geodist bigboxcity Paris "Hong Kong" km | Result:  9618.579
Command: geodist bigboxcity Paris Paris | Result:  0
Command: geodist bigboxcity Paris "unknown city" | Result:  null
Command: set bigboxstr "test string here" | Result:  OK
Command: geodist bigboxstr Paris Tokyo | Result:  [ErrorReply: WRONGTYPE Operation against a key holding the wrong kind of value]

NOTES

  • Use the function “geoDist” of node-redis.
  • Signature of the method-
    function geoDist(key: RedisCommandArgument, member1: RedisCommandArgument, member2: RedisCommandArgument, unit?: GeoUnits)
  • GeoUnits type is defined as-
    type GeoUnits = 'm' | 'km' | 'mi' | 'ft'
// Redis GEODIST command example in Java

import redis.clients.jedis.GeoCoordinate;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.args.GeoUnit;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GeoDist {

    public static void main(String[] args) {
        // Create connection pool
        JedisPool jedisPool = new JedisPool("localhost", 6379);

        try (Jedis jedis = jedisPool.getResource()) {

            /**
             * Add city longitude and latitude to geoindex named bigboxcity
             * Command: geoadd bigboxcity 2.352222 48.856613 Paris 100.501762 13.756331 Bangkok 114.109497 22.396427 "Hong Kong" 139.691711 35.689487 Tokyo 12.496365 41.902782 Rome
             * Result: (integer) 5
             */
            Map<String, GeoCoordinate> locationData = new HashMap<>() {{
                put("Paris", new GeoCoordinate(2.352222, 48.856613));
                put("Bangkok", new GeoCoordinate(100.501762, 13.756331));
                put("Hong Kong", new GeoCoordinate(114.109497, 22.396427));
                put("Tokyo", new GeoCoordinate(139.691711, 35.689487));
                put("Rome", new GeoCoordinate(12.496365, 41.90278));
            }};
            long getaddResult = jedis.geoadd("bigboxcity", locationData);

            System.out.println("Command: geoadd bigboxcity 2.352222 48.856613 Paris 100.501762 13.756331 Bangkok 114.109497 22.396427 "Hong Kong" 139.691711 35.689487 Tokyo 12.496365 41.902782 Rome | Result: " + getaddResult);


            /**
             * Check the items in bigboxcity
             * Command: zrange bigboxcity 0 -1
             * Result:
             *      1) "Rome"
             *      2) "Paris"
             *      3) "Bangkok"
             *      4) "Hong Kong"
             *      5) "Tokyo"
             */
            List<String> zrangeResult = jedis.zrange("bigboxcity", 0, -1);

            System.out.println("Command: zrange bigboxcity 0 -1 withscores | Result: " + zrangeResult.toString());

            /**
             * Check distance of Paris and Tokyo
             * This distance is in meter unit, as meter is the default
             *
             * Command: geodist bigboxcity Paris Tokyo
             * Result: "9714811.3348"
             */
            Double geodistResult = jedis.geodist("bigboxcity", "Paris", "Tokyo");

            System.out.println("Command: geodist bigboxcity Paris Tokyo | Result: " + geodistResult);

            /**
             * Check distance of Paris and Hong Kong
             * This distance is in kilometer as we provide km to the command
             *
             * Command: geodist bigboxcity Paris "Hong Kong" km
             * Result: "9618.5790"
             */
            geodistResult = jedis.geodist("bigboxcity", "Paris", "Hong Kong", GeoUnit.KM);

            System.out.println("Command: geodist bigboxcity Paris "Hong Kong" km | Result: " + geodistResult);

            /**
             * Distance to the same city will be zero
             *
             * Command: geodist bigboxcity Paris Paris
             * Result: "0.0000"
             */
            geodistResult = jedis.geodist("bigboxcity", "Paris", "Paris");

            System.out.println("Command: geodist bigboxcity Paris Paris | Result: " + geodistResult);

            /**
             * We get (nil) if one or both of the cities do not exist in our geoindex
             *
             * Command: geodist bigboxcity Paris "unknown city"
             * Result: (nil)
             */
            geodistResult = jedis.geodist("bigboxcity", "Paris", "unknown city");

            System.out.println("Command: geodist bigboxcity Paris "unknown city" | Result: " + geodistResult);

            /**
             * Set a string
             *
             * Command: set bigboxstr "test string here"
             * Result: OK
             */
            String setResult = jedis.set("bigboxstr", "test string here");

            System.out.println("Command: set bigboxstr "test string here" | Result: " + setResult);

            /**
             * Try to add GEODIST on a string
             * We get a type error
             *
             * Command: geodist bigboxstr Paris Tokyo
             * Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
             */
            try {
                geodistResult = jedis.geodist("bigboxstr", "Paris", "Tokyo");

                System.out.println("Command: geodist bigboxstr Paris Tokyo | Result: " + geodistResult);
            } catch (Exception e) {
                System.out.println("Command: geodist bigboxstr Paris Tokyo | Result: " + e.getMessage());
            }

        }

        jedisPool.close();

    }
}

Output:

Command: geoadd bigboxcity 2.352222 48.856613 Paris 100.501762 13.756331 Bangkok 114.109497 22.396427 "Hong Kong" 139.691711 35.689487 Tokyo 12.496365 41.902782 Rome | Result: 5
Command: zrange bigboxcity 0 -1 withscores | Result: [Rome, Paris, Bangkok, Hong Kong, Tokyo]
Command: geodist bigboxcity Paris Tokyo | Result: 9714811.3348
Command: geodist bigboxcity Paris "Hong Kong" km | Result: 9618.579
Command: geodist bigboxcity Paris Paris | Result: 0.0
Command: geodist bigboxcity Paris "unknown city" | Result: null
Command: set bigboxstr "test string here" | Result: OK
Command: geodist bigboxstr Paris Tokyo | Result: WRONGTYPE Operation against a key holding the wrong kind of value

NOTES

  • Use method “geodist” from Jedis package.
  • The signatures of the method are-
    • Double geodist(final String key, final String member1, final String member2)
    • Double geodist(final String key, final String member1, final String member2, final GeoUnit unit)
// Redis GEODIST command examples in C#

using StackExchange.Redis;

namespace GeoDist
{
    internal class Program
    {
        static void Main(string[] args)
        {
            ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
            IDatabase rdb = redis.GetDatabase();

            /**
             * Add city longitude and latitude to geoindex named bigboxcity
             * Command: geoadd bigboxcity 2.352222 48.856613 Paris 100.501762 13.756331 Bangkok 114.109497 22.396427 "Hong Kong" 139.691711 35.689487 Tokyo 12.496365 41.902782 Rome
             * Result: (integer) 5
             */
            GeoEntry[] locationData = new GeoEntry[]{
                new GeoEntry(2.352222, 48.856613, "Paris"),
                new GeoEntry(100.501762, 13.756331, "Bangkok"),
                new GeoEntry(114.109497, 22.396427, "Hong Kong"),
                new GeoEntry(139.691711, 35.689487, "Tokyo"),
                new GeoEntry(12.496365, 41.90278, "Rome"),
            };
            long getaddResults = rdb.GeoAdd("bigboxcity", locationData);

            Console.WriteLine("Command: geoadd bigboxcity 2.352222 48.856613 Paris 100.501762 13.756331 Bangkok 114.109497 22.396427 "Hong Kong" 139.691711 35.689487 Tokyo 12.496365 41.902782 Rome | Result: " + getaddResults);

            /**
             * Check the items in bigboxcity
             * Command: zrange bigboxcity 0 -1
             * Result:
             *      1) "Rome"
             *      2) "Paris"
             *      3) "Bangkok"
             *      4) "Hong Kong"
             *      5) "Tokyo"
             */
            RedisValue[] zrangeResult = rdb.SortedSetRangeByScore("bigboxcity", 0, -1);

            Console.WriteLine("Command: zrange bigboxcity 0 -1 withscores | Result: " + String.Join(",", zrangeResult));

            /**
             * Check distance of Paris and Tokyo
             * This distance is in meter unit, as meter is the default
             *
             * Command: geodist bigboxcity Paris Tokyo
             * Result: "9714811.3348"
             */
            double? geodistResult = rdb.GeoDistance("bigboxcity", "Paris", "Tokyo");

            Console.WriteLine("Command: geodist bigboxcity Paris Tokyo | Result: " + geodistResult);

            /**
             * Check distance of Paris and Hong Kong
             * This distance is in kilometer as we provide km to the command
             *
             * Command: geodist bigboxcity Paris "Hong Kong" km
             * Result: "9618.5790"
             */
            geodistResult = rdb.GeoDistance("bigboxcity", "Paris", "Hong Kong", GeoUnit.Kilometers);

            Console.WriteLine("Command: geodist bigboxcity Paris "Hong Kong" km | Result: " + geodistResult);

            /**
             * Distance to the same city will be zero
             *
             * Command: geodist bigboxcity Paris Paris
             * Result: "0.0000"
             */
            geodistResult = rdb.GeoDistance("bigboxcity", "Paris", "Paris");

            Console.WriteLine("Command: geodist bigboxcity Paris Paris | Result: " + geodistResult);

            /**
             * We get (nil) if one or both of the cities do not exist in our geoindex
             *
             * Command: geodist bigboxcity Paris "unknown city"
             * Result: (nil)
             */
            geodistResult = rdb.GeoDistance("bigboxcity", "Paris", "unknown city");

            Console.WriteLine("Command: geodist bigboxcity Paris "unknown city" | Result: " + geodistResult);

            /**
             * Set a string
             *
             * Command: set bigboxstr "test string here"
             * Result: OK
             */
            bool setResult = rdb.StringSet("bigboxstr", "test string here");

            Console.WriteLine("Command: set bigboxstr "test string here" | Result: " + setResult);

            /**
             * Try to add GEODIST on a string
             * We get a type error
             *
             * Command: geodist bigboxstr Paris Tokyo
             * Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
             */
            try
            {
                geodistResult = rdb.GeoDistance("bigboxstr", "Paris", "Tokyo");

                Console.WriteLine("Command: geodist bigboxstr Paris Tokyo | Result: " + geodistResult);
            }
            catch (Exception e)
            {
                Console.WriteLine("Command: geodist bigboxstr Paris Tokyo | Result: " + e.Message);
            }
        }
    }
}

Output:

Command: geoadd bigboxcity 2.352222 48.856613 Paris 100.501762 13.756331 Bangkok 114.109497 22.396427 "Hong Kong" 139.691711 35.689487 Tokyo 12.496365 41.902782 Rome | Result: 5
Command: zrange bigboxcity 0 -1 withscores | Result:
Command: geodist bigboxcity Paris Tokyo | Result: 9714811.3348
Command: geodist bigboxcity Paris "Hong Kong" km | Result: 9618.579
Command: geodist bigboxcity Paris Paris | Result: 0
Command: geodist bigboxcity Paris "unknown city" | Result:
Command: set bigboxstr "test string here" | Result: True
Command: geodist bigboxstr Paris Tokyo | Result: WRONGTYPE Operation against a key holding the wrong kind of value

NOTES

  • Use the method “GeoDistance” from StackExchange.Redis.
  • Method signatures-
    • double? GeoDistance(RedisKey key, RedisValue member1, RedisValue member2, GeoUnit unit = GeoUnit.Meters, CommandFlags flags = CommandFlags.None)
<?php
// Redis GEODIST command example in PHP

require 'vendor/autoload.php';

// Connect to Redis
$redisClient = new PredisClient([
    'scheme' => 'tcp',
    'host' => 'localhost',
    'port' => 6379,
]);


/**
 * Add city longitude and latitude to geoindex named bigboxcity
 * Command: geoadd bigboxcity 2.352222 48.856613 Paris 100.501762 13.756331 Bangkok 114.109497 22.396427 "Hong Kong" 139.691711 35.689487 Tokyo 12.496365 41.902782 Rome
 * Result: (integer) 5
 */
$commandResult = $redisClient->geoadd(
    "bigboxcity",
    2.352222,
    48.856613,
    "Paris",
    100.501762,
    13.756331,
    "Bangkok",
    114.109497,
    22.396427,
    "Hong Kong",
    139.691711,
    35.689487,
    "Tokyo",
    12.496365,
    41.902782,
    "Rome"
);

echo "Command: geoadd bigboxcity 2.352222 48.856613 Paris 100.501762 13.756331 Bangkok 114.109497 22.396427 "Hong Kong" 139.691711 35.689487 Tokyo 12.496365 41.902782 Rome | Result: " . $commandResult . "n";

/**
 * Check the items in bigboxcity
 * Command: zrange bigboxcity 0 -1
 * Result:
 *      1) "Rome"
 *      2) "Paris"
 *      3) "Bangkok"
 *      4) "Hong Kong"
 *      5) "Tokyo"
 */
$commandResult = $redisClient->zrange("bigboxcity", 0, -1);

echo "Command: zrange bigboxcity 0 -1 withscores | Result: ";
print_r($commandResult);

/**
 * Check distance of Paris and Tokyo
 * This distance is in meter unit, as meter is the default
 *
 * Command: geodist bigboxcity Paris Tokyo
 * Result: "9714811.3348"
 */
$commandResult = $redisClient->geodist("bigboxcity", "Paris", "Tokyo");

echo "Command: geodist bigboxcity Paris Tokyo | Result: " . $commandResult . "n";

/**
 * Check distance of Paris and Hong Kong
 * This distance is in kilometer as we provide km to the command
 *
 * Command: geodist bigboxcity Paris "Hong Kong" km
 * Result: "9618.5790"
 */
$commandResult = $redisClient->geodist("bigboxcity", "Paris", "Hong Kong", "km");

echo "Command: geodist bigboxcity Paris "Hong Kong" km | Result: " . $commandResult . "n";

/**
 * Distance to the same city will be zero
 *
 * Command: geodist bigboxcity Paris Paris
 * Result: "0.0000"
 */
$commandResult = $redisClient->geodist("bigboxcity", "Paris", "Paris");

echo "Command: geodist bigboxcity Paris Paris | Result: " . $commandResult . "n";

/**
 * We get (nil) if one or both of the cities do not exist in our geoindex
 *
 * Command: geodist bigboxcity Paris "unknown city"
 * Result: (nil)
 */
$commandResult = $redisClient->geodist("bigboxcity", "Paris", "unknown city");

echo "Command: geodist bigboxcity Paris "unknown city" | Result: " . $commandResult . "n";

/**
 * Set a string
 *
 * Command: set bigboxstr "test string here"
 * Result: OK
 */
$commandResult = $redisClient->set("bigboxstr", "test string here");

echo "Command: set bigboxstr "test string here" | Result: " . $commandResult . "n";

/**
 * Try to add GEODIST on a string
 * We get a type error
 *
 * Command: geodist bigboxstr Paris Tokyo
 * Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
 */
try {
    $commandResult = $redisClient->geodist("bigboxstr", "Paris", "Tokyo");

    echo "Command: geodist bigboxstr Paris Tokyo | Result: " . $commandResult . "n";
} catch (Exception $e) {
    echo "Command: geodist bigboxstr Paris Tokyo | Result: " . $e->getMessage() . "n";
}

Output:

Command: geoadd bigboxcity 2.352222 48.856613 Paris 100.501762 13.756331 Bangkok 114.109497 22.396427 "Hong Kong" 139.691711 35.689487 Tokyo 12.496365 41.902782 Rome | Result: 5
Command: zrange bigboxcity 0 -1 withscores | Result: Array
(
    [0] => Rome
    [1] => Paris
    [2] => Bangkok
    [3] => Hong Kong
    [4] => Tokyo
)
Command: geodist bigboxcity Paris Tokyo | Result: 9714811.3348
Command: geodist bigboxcity Paris "Hong Kong" km | Result: 9618.5790
Command: geodist bigboxcity Paris Paris | Result: 0.0000
Command: geodist bigboxcity Paris "unknown city" | Result:
Command: set bigboxstr "test string here" | Result: OK
Command: geodist bigboxstr Paris Tokyo | Result: WRONGTYPE Operation against a key holding the wrong kind of value

NOTES

  • Use the method “geodist” of predis.
  • Signature of the method is-
    geodist(string $key, $member1, $member2, $unit = null): string|null
# Redis GEODIST command example in Python

import redis
import time

# Create Redis client
redisClient = redis.Redis(
    host="localhost", port=6379, username="default", password="", decode_responses=True
)


# Add city longitude and latitude to geoindex named bigboxcity
# Command: geoadd bigboxcity 2.352222 48.856613 Paris 100.501762 13.756331 Bangkok 114.109497 22.396427 "Hong Kong" 139.691711 35.689487 Tokyo 12.496365 41.902782 Rome
# Result: (integer) 5
commandResult = redisClient.geoadd(
    "bigboxcity",
    (2.352222, 48.856613, "Paris")
    + (100.501762, 13.756331, "Bangkok")
    + (114.109497, 22.396427, "Hong Kong")
    + (139.691711, 35.689487, "Tokyo")
    + (12.496365, 41.902782, "Rome"),
)

print(
    'Command: geoadd bigboxcity 2.352222 48.856613 Paris 100.501762 13.756331 Bangkok 114.109497 22.396427 "Hong Kong" 139.691711 35.689487 Tokyo 12.496365 41.902782 Rome | Result: {}'.format(
        commandResult
    )
)

# Check the items in bigboxcity
# Command: zrange bigboxcity 0 -1
# Result:
#      1) "Rome"
#      2) "Paris"
#      3) "Bangkok"
#      4) "Hong Kong"
#      5) "Tokyo"
commandResult = redisClient.zrange("bigboxcity", 0, -1)

print("Command: zrange bigboxcity 0 -1 withscores | Result: {}".format(commandResult))

# Check distance of Paris and Tokyo
# This distance is in meter unit, as meter is the default
# Command: geodist bigboxcity Paris Tokyo
# Result: "9714811.3348"
commandResult = redisClient.geodist("bigboxcity", "Paris", "Tokyo")

print("Command: geodist bigboxcity Paris Tokyo | Result: {}".format(commandResult))

# Check distance of Paris and Hong Kong
# This distance is in kilometer as we provide km to the command
# Command: geodist bigboxcity Paris "Hong Kong" km
# Result: "9618.5790"
commandResult = redisClient.geodist("bigboxcity", "Paris", "Hong Kong", "km")

print(
    'Command: geodist bigboxcity Paris "Hong Kong" km | Result: {}'.format(
        commandResult
    )
)

# Distance to the same city will be zero
# Command: geodist bigboxcity Paris Paris
# Result: "0.0000"
commandResult = redisClient.geodist("bigboxcity", "Paris", "Paris")

print("Command: geodist bigboxcity Paris Paris | Result: {}".format(commandResult))

# We get (nil) if one or both of the cities do not exist in our geoindex
# Command: geodist bigboxcity Paris "unknown city"
# Result: (nil)
commandResult = redisClient.geodist("bigboxcity", "Paris", "unknown city")

print(
    'Command: geodist bigboxcity Paris "unknown city" | Result: {}'.format(
        commandResult
    )
)

# Set a string
# Command: set bigboxstr "test string here"
# Result: OK
commandResult = redisClient.set("bigboxstr", "test string here")

print('Command: set bigboxstr "test string here" | Result: {}'.format(commandResult))

# Try to add GEODIST on a string
# We get a type error
# Command: geodist bigboxstr Paris Tokyo
# Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
try:
    commandResult = redisClient.geodist("bigboxstr", "Paris", "Tokyo")

    print("Command: geodist bigboxstr Paris Tokyo | Result: {}".format(commandResult))
except Exception as error:
    print("Command: geodist bigboxstr Paris Tokyo | Result: ", error)

Output:

Command: geoadd bigboxcity 2.352222 48.856613 Paris 100.501762 13.756331 Bangkok 114.109497 22.396427 "Hong Kong" 139.691711 35.689487 Tokyo 12.496365 41.902782 Rome | Result: 5
Command: zrange bigboxcity 0 -1 withscores | Result: ['Rome', 'Paris', 'Bangkok', 'Hong Kong', 'Tokyo']
Command: geodist bigboxcity Paris Tokyo | Result: 9714811.3348
Command: geodist bigboxcity Paris "Hong Kong" km | Result: 9618.579
Command: geodist bigboxcity Paris Paris | Result: 0.0
Command: geodist bigboxcity Paris "unknown city" | Result: None
Command: set bigboxstr "test string here" | Result: True
Command: geodist bigboxstr Paris Tokyo | Result:  WRONGTYPE Operation against a key holding the wrong kind of value

NOTES

  • Use method “geodist” from redis-py.
  • Signature of the method is –
    • def geodist(self, name: KeyT, place1: FieldT, place2: FieldT, unit: Union[str, None] = None) -> ResponseT
# Redis GEODIST command example in Ruby

require 'redis'

redis = Redis.new(host: "localhost", port: 6379)


# Add city longitude and latitude to geoindex named bigboxcity
# Command: geoadd bigboxcity 2.352222 48.856613 Paris 100.501762 13.756331 Bangkok 114.109497 22.396427 "Hong Kong" 139.691711 35.689487 Tokyo 12.496365 41.902782 Rome
# Result: (integer) 5
commandResult = redis.geoadd(
    "bigboxcity",
    2.352222, 48.856613, "Paris",
    100.501762, 13.756331, "Bangkok",
    114.109497, 22.396427, "Hong Kong",
    139.691711, 35.689487, "Tokyo",
    12.496365, 41.902782, "Rome",
)

print("Command: geoadd bigboxcity 2.352222 48.856613 Paris 100.501762 13.756331 Bangkok 114.109497 22.396427 "Hong Kong" 139.691711 35.689487 Tokyo 12.496365 41.902782 Rome | Result: ", commandResult, "n")

# Check the items in bigboxcity
# Command: zrange bigboxcity 0 -1
# Result:
#      1) "Rome"
#      2) "Paris"
#      3) "Bangkok"
#      4) "Hong Kong"
#      5) "Tokyo"
commandResult = redis.zrange("bigboxcity", 0, -1)

print("Command: zrange bigboxcity 0 -1 withscores | Result: ", commandResult, "n")

# Check distance of Paris and Tokyo
# This distance is in meter unit, as meter is the default
# Command: geodist bigboxcity Paris Tokyo
# Result: "9714811.3348"
commandResult = redis.geodist("bigboxcity", "Paris", "Tokyo")

print("Command: geodist bigboxcity Paris Tokyo | Result: ", commandResult, "n")

# Check distance of Paris and Hong Kong
# This distance is in kilometer as we provide km to the command
# Command: geodist bigboxcity Paris "Hong Kong" km
# Result: "9618.5790"
commandResult = redis.geodist("bigboxcity", "Paris", "Hong Kong", "km")

print("Command: geodist bigboxcity Paris "Hong Kong" km | Result: ", commandResult, "n")

# Distance to the same city will be zero
# Command: geodist bigboxcity Paris Paris
# Result: "0.0000"
commandResult = redis.geodist("bigboxcity", "Paris", "Paris")

print("Command: geodist bigboxcity Paris Paris | Result: ", commandResult, "n")

# We get (nil) if one or both of the cities do not exist in our geoindex
# Command: geodist bigboxcity Paris "unknown city"
# Result: (nil)
commandResult = redis.geodist("bigboxcity", "Paris", "unknown city")

print("Command: geodist bigboxcity Paris "unknown city" | Result: ", commandResult, "n")

# Set a string
# Command: set bigboxstr "test string here"
# Result: OK
commandResult = redis.set("bigboxstr", "test string here")

print("Command: set bigboxstr "test string here" | Result: ", commandResult, "n")

# Try to add GEODIST on a string
# We get a type error
# Command: geodist bigboxstr Paris Tokyo
# Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
begin
    commandResult = redis.geodist("bigboxstr", "Paris", "Tokyo")

    print("Command: geodist bigboxstr Paris Tokyo | Result: ", commandResult, "n")
rescue => e
    print("Command: geodist bigboxstr Paris Tokyo | Result: ", e, "n")
end

Output:

Command: geoadd bigboxcity 2.352222 48.856613 Paris 100.501762 13.756331 Bangkok 114.109497 22.396427 "Hong Kong" 139.691711 35.689487 Tokyo 12.496365 41.902782 Rome | Result: 5
Command: zrange bigboxcity 0 -1 withscores | Result: ["Rome", "Paris", "Bangkok", "Hong Kong", "Tokyo"]
Command: geodist bigboxcity Paris Tokyo | Result: 9714811.3348
Command: geodist bigboxcity Paris "Hong Kong" km | Result: 9618.5790
Command: geodist bigboxcity Paris Paris | Result: 0.0000
Command: geodist bigboxcity Paris "unknown city" | Result: 
Command: set bigboxstr "test string here" | Result: OK
Command: geodist bigboxstr Paris Tokyo | Result: WRONGTYPE Operation against a key holding the wrong kind of value

NOTES

  • Use method “geodist” from the redis-rb.
  • Signature of the method is-
    • # @param [String ]key
      # @param [Array<String>] members
      # @param ['m', 'km', 'mi', 'ft'] unit
      # @return [String, nil] returns distance in spefied unit if both members present, nil otherwise.

      def geodist(key, member1, member2, unit = 'm')

Source Code

Use the following links to get the source code used in this article-

Related Commands

CommandDetails
GEOADD Command Details
ZRANGE Command Details

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.