Redis Command: GEOSEARCH

Summary

Command NameGEOSEARCH
UsageFind geo positions inside certain area
Group geo
ACL Category@read
@geo
@slow
Time ComplexityO(N+log(M))
FlagREADONLY
Arity-7

NOTES

  • In the time complexity, N is the total number of items, which are in the considered grids. and M is the number of items in the circle/squire(based on the option).

Signature

GEOSEARCH <key>
( FROMMEMBER <member_name> | FROMLONLAT <longitude> <latitude> )
( BYRADIUS <radius_value> ( M | KM | FT | MI )

| BYBOX <width_of_the_box> <height_of_the_box> ( M | KM | FT | MI ))
( ASC | DESC )
( COUNT <count_value> ( ANY ) )
( WITHCOORD )
( WITHDIST )
( WITHHASH )

Usage

Find all the geo position members saved in a geoindex, which are within a certain distance and in a certain area(circular or box).

Redis GEOSEARCH diagram
Redis GEOSEARCH diagram

NOTES

  • Returned geo positions are in [longitude, latitude] format. We need to keep this in mind, as this is unusual than what we generally use in other places.
  • This command can be used as a substitute for GEORADIUS and GEOREDIUSBYMEMBER commands, as those commands are deprecated.

Arguments

ParameterGroupDescriptionNameTypeOptional
<key>Name of the key that holds the geo indexkeykey
FROMMEMBER <member_name>fromProvide the member name/identifier which will be used as the centermemberstring
FROMLONLAT <longitude> <latitude>fromProvide longitude and latitude of the point, which will be used as the centerfromlonlatblock
BYRADIUS <radius_value> (M | KM | FT | MI)byCalculate by radius, and consider a circular area.
Use M, KM, FT, MI as unit.
radiusdouble
BYBOX <width_of_the_box> <height_of_the_box> (M | KM | FT | MI)byCalculate area by width and height. Consider a rectangular area.
Use M, KM, FT, MI as unit.
boxblock
ASCorderAscending order by distanceascpure-tokenTrue
DESCorderDescending order by distancedescpure-tokenTrue
COUNT <count_value> (ANY)Return <count_vlaue> number of results.
When ANY option is provided then the the server tries to return the result as soon as possible.
count-blockblockTrue
WITHCOORDReturn coordinates in the resultwithcoordpure-tokenTrue
WITHDISTReturn distance in the resultwithdistpure-tokenTrue
WITHHASHReturn geohash of the pointwithhashpure-tokenTrue

NOTES

  • WITHCOORD, WITHDIST, and WITHHASH options are passed to return additional information on the member coordinates. These options do not affect the result coordinates, just return additional info.
  • If WIDTHDIST option is provided, then the returned distance is in the same unit which was provided for the radius of the circle, or the height & width of the rectangle.
  • Results are unsorted by default. We can use one of the ASC or DESC options to sort the result. The sorting is based on the distance from the mentioned member(geo position).
  • Units to be used-
    • M – Mile
    • KM – Kilometer
    • FT – Feet
    • MI – Mile

Return Value

Return valueCase for the return valueType
Array of membersOn success, it returns the array of the positions(array[longitude, latitude]) values of the members.
Might return other values depending on the provided options
array
(empty array)If the key does not exist(empty array)
errorIf the applied to the wrong data type,
or wrong member name used
error

NOTES

  • The returned result also includes the member from which we want to calculate the distance.
  • 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
  • If the key is correct but the member name is wrong then we get the following error-
    (error) ERR could not decode requested zset member

Examples

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

# Redis GEOSEARCH command examples

# Add members to a geo index 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 members saved in bigboxcity
127.0.0.1:6379> zrange bigboxcity 0 -1
1) "Rome"
2) "Paris"
3) "Bangkok"
4) "Hong Kong"
5) "Tokyo"

# Check cities in a certeain size rectagle from Paris
127.0.0.1:6379> geosearch bigboxcity frommember Paris bybox 21500 20000 km
1) "Rome"
2) "Paris"
3) "Bangkok"

# Check cities in 9700KM radius from Paris
127.0.0.1:6379> geosearch bigboxcity frommember Paris byradius 9700 km
1) "Rome"
2) "Paris"
3) "Bangkok"
4) "Hong Kong"

# Search location and get additional information like coordinates, distance, width
127.0.0.1:6379> geosearch bigboxcity frommember Paris byradius 9700 km withcoord withdist withhash
1) 1) "Rome"
   2) "1105.5914"
   3) (integer) 3480343273965391
   4) 1) "12.49636620283126831"
      2) "41.90278213378983452"
2) 1) "Paris"
   2) "0.0000"
   3) (integer) 3663832779125283
   4) 1) "2.35221952199935913"
      2) "48.85661220395509474"
3) 1) "Bangkok"
   2) "9445.7597"
   3) (integer) 3962257436268857
   4) 1) "100.50176292657852173"
      2) "13.75633095031508191"
4) 1) "Hong Kong"
   2) "9618.5790"
   3) (integer) 4046429669534462
   4) 1) "114.10949438810348511"
      2) "22.39642736199028406"

# Search location by distance from certain longitude and latitude
127.0.0.1:6379> geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash
1) 1) "Bangkok"
   2) "1728.5852"
   3) (integer) 3962257436268857
   4) 1) "100.50176292657852173"
      2) "13.75633095031508191"
2) 1) "Hong Kong"
   2) "0.1972"
   3) (integer) 4046429669534462
   4) 1) "114.10949438810348511"
      2) "22.39642736199028406"
3) 1) "Tokyo"
   2) "2880.1615"
   3) (integer) 4171231230197033
   4) 1) "139.69171196222305298"
      2) "35.68948605865241319"

# Use COUNT option to limit the number of results
127.0.0.1:6379> geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2
1) 1) "Hong Kong"
   2) "0.1972"
   3) (integer) 4046429669534462
   4) 1) "114.10949438810348511"
      2) "22.39642736199028406"
2) 1) "Bangkok"
   2) "1728.5852"
   3) (integer) 3962257436268857
   4) 1) "100.50176292657852173"
      2) "13.75633095031508191"

# Use ASC options to order assinding by disance
127.0.0.1:6379> geosearch bigboxcity fromlonlat 114.109497 22.3982  byradius 9000 km withcoord withdist withhash count 2 ASC
1) 1) "Hong Kong"
   2) "0.1972"
   3) (integer) 4046429669534462
   4) 1) "114.10949438810348511"
      2) "22.39642736199028406"
2) 1) "Bangkok"
   2) "1728.5852"
   3) (integer) 3962257436268857
   4) 1) "100.50176292657852173"
      2) "13.75633095031508191"

# Use DESC options to order desinding by disance
127.0.0.1:6379> geosearch bigboxcity fromlonlat 114.109497 22.3982  byradius 9000 km withcoord withdist withhash count 2 DESC
1) 1) "Tokyo"
   2) "2880.1615"
   3) (integer) 4171231230197033
   4) 1) "139.69171196222305298"
      2) "35.68948605865241319"
2) 1) "Bangkok"
   2) "1728.5852"
   3) (integer) 3962257436268857
   4) 1) "100.50176292657852173"
      2) "13.75633095031508191"

# Use non existing key
# We get empty array
127.0.0.1:6379> geosearch wrongkey frommember Paris bybox 21500 20000 km
(empty array)

# Use non existing member name
# We get an error
127.0.0.1:6379> geosearch bigboxcity frommember wrongmember bybox 21500 20000 km
(error) ERR could not decode requested zset member

# Use wrong key and wrong member name
# We get empty array
127.0.0.1:6379> geosearch wrongkey frommember wrongmember bybox 21500 20000 km
(empty array)

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

# Try to use a key that is not a geoindex
# We get an error
127.0.0.1:6379> geosearch bigboxstr fromlonlat 114.109497 22.3982 byradius 9000 km
(error) WRONGTYPE Operation against a key holding the wrong kind of value

Code Implementations

Here are the example implementations of the command in Golang, NodeJS, Java, C#, PHP, Python-

// Redis GEOSEARCH 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 members to a geo index 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 members saved 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 cities in a certeain size rectagle from Paris
	*
	* Command: geosearch bigboxcity frommember Paris bybox 21500 20000 km
	* Result:
	*      1) "Rome"
	*      2) "Paris"
	*      3) "Bangkok"
	 */
	searchQuery := &redis.GeoSearchQuery{
		Member:    "Paris",
		BoxWidth:  21_500,
		BoxHeight: 20_000,
		BoxUnit:   "km",
	}
	searchResult, err := rdb.GeoSearch(ctx, "bigboxcity", searchQuery).Result()

	if err != nil {
		fmt.Println("Command: geosearch bigboxcity frommember Paris bybox 21500 20000 km | Error: " + err.Error())
	}

	fmt.Println("Command: geosearch bigboxcity frommember Paris bybox 21500 20000 km | Result: ", searchResult)

	/**
	* Check cities in 9700KM radius from Paris
	*
	* Command: geosearch bigboxcity frommember Paris byradius 9700 km
	* Result:
	*          1) "Rome"
	*          2) "Paris"
	*          3) "Bangkok"
	*          4) "Hong Kong"
	 */
	searchQuery = &redis.GeoSearchQuery{
		Member:     "Paris",
		Radius:     9_700,
		RadiusUnit: "km",
	}
	searchResult, err = rdb.GeoSearch(ctx, "bigboxcity", searchQuery).Result()

	if err != nil {
		fmt.Println("Command: geosearch bigboxcity frommember Paris byradius 9700 km | Error: " + err.Error())
	}

	fmt.Println("Command: geosearch bigboxcity frommember Paris byradius 9700 km | Result: ", searchResult)

	/**
	* Search location and get additional information like coordinates, distance, width
	*
	* Command: geosearch bigboxcity frommember Paris byradius 9700 km withcoord withdist withhash
	* Result:
	*      1)  1) "Rome"
	*          2) "1105.5914"
	*          3) (integer) 3480343273965391
	*          4)  1) "12.49636620283126831"
	*              2) "41.90278213378983452"
	*
	*      2)  1) "Paris"
	*          2) "0.0000"
	*          3) (integer) 3663832779125283
	*          4)  1) "2.35221952199935913"
	*              2) "48.85661220395509474"
	*
	*      3)  1) "Bangkok"
	*          2) "9445.7597"
	*          3) (integer) 3962257436268857
	*          4)  1) "100.50176292657852173"
	*              2) "13.75633095031508191"
	*
	*      4)  1) "Hong Kong"
	*          2) "9618.5790"
	*          3) (integer) 4046429669534462
	*          4)  1) "114.10949438810348511"
	*              2) "22.39642736199028406"
	 */
	searchLocationQuery := &redis.GeoSearchLocationQuery{
		GeoSearchQuery: redis.GeoSearchQuery{
			Member:     "Paris",
			Radius:     9_700,
			RadiusUnit: "km",
		},
		WithCoord: true,
		WithDist:  true,
		WithHash:  true,
	}
	searchLocationResult, err := rdb.GeoSearchLocation(ctx, "bigboxcity", searchLocationQuery).Result()

	if err != nil {
		fmt.Println("Command: geosearch bigboxcity frommember Paris byradius 9700 km withcoord withdist withhash | Error: " + err.Error())
	}

	fmt.Println("Command: geosearch bigboxcity frommember Paris byradius 9700 km withcoord withdist withhash | Result: ", searchLocationResult)

	/**
	* Search location by distance from certain longitude and latitude
	*
	* Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash
	* Result:
	*      1)  1) "Bangkok"
	*          2) "1728.5852"
	*          3) (integer) 3962257436268857
	*          4)  1) "100.50176292657852173"
	*              2) "13.75633095031508191"
	*
	*      2)  1) "Hong Kong"
	*          2) "0.1972"
	*          3) (integer) 4046429669534462
	*          4)  1) "114.10949438810348511"
	*              2) "22.39642736199028406"
	*
	*      3)  1) "Tokyo"
	*          2) "2880.1615"
	*          3) (integer) 4171231230197033
	*          4)  1) "139.69171196222305298"
	*              2) "35.68948605865241319"
	 */
	searchLocationQuery = &redis.GeoSearchLocationQuery{
		GeoSearchQuery: redis.GeoSearchQuery{
			Longitude:  114.109497,
			Latitude:   22.3982,
			Radius:     9_000,
			RadiusUnit: "km",
		},
		WithCoord: true,
		WithDist:  true,
		WithHash:  true,
	}
	searchLocationResult, err = rdb.GeoSearchLocation(ctx, "bigboxcity", searchLocationQuery).Result()

	if err != nil {
		fmt.Println("Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash | Error: " + err.Error())
	}

	fmt.Println("Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash | Result: ", searchLocationResult)

	/**
	* Use COUNT option to limit the number of results
	*
	* Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2
	* Result:
	*      1)  1) "Hong Kong"
	*          2) "0.1972"
	*          3) (integer) 4046429669534462
	*          4)  1) "114.10949438810348511"
	*              2) "22.39642736199028406"
	*
	*      2)  1) "Bangkok"
	*          2) "1728.5852"
	*          3) (integer) 3962257436268857
	*          4)  1) "100.50176292657852173"
	*              2) "13.75633095031508191"
	 */
	searchLocationQuery = &redis.GeoSearchLocationQuery{
		GeoSearchQuery: redis.GeoSearchQuery{
			Longitude:  114.109497,
			Latitude:   22.3982,
			Radius:     9_000,
			RadiusUnit: "km",
			Count:      2,
		},
		WithCoord: true,
		WithDist:  true,
		WithHash:  true,
	}
	searchLocationResult, err = rdb.GeoSearchLocation(ctx, "bigboxcity", searchLocationQuery).Result()

	if err != nil {
		fmt.Println("Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2| Error: " + err.Error())
	}

	fmt.Println("Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2| Result: ", searchLocationResult)

	/**
	* Use ASC options to order assinding by disance
	*
	* Command: geosearch bigboxcity fromlonlat 114.109497 22.3982  byradius 9000 km withcoord withdist withhash count 2 ASC
	* Result:
	*      1)  1) "Hong Kong"
	*          2) "0.1972"
	*          3) (integer) 4046429669534462
	*          4)  1) "114.10949438810348511"
	*              2) "22.39642736199028406"
	*
	*      2)  1) "Bangkok"
	*          2) "1728.5852"
	*          3) (integer) 3962257436268857
	*          4)  1) "100.50176292657852173"
	*              2) "13.75633095031508191"
	 */
	searchLocationQuery = &redis.GeoSearchLocationQuery{
		GeoSearchQuery: redis.GeoSearchQuery{
			Longitude:  114.109497,
			Latitude:   22.3982,
			Radius:     9_000,
			RadiusUnit: "km",
			Count:      2,
			Sort:       "asc",
		},
		WithCoord: true,
		WithDist:  true,
		WithHash:  true,
	}
	searchLocationResult, err = rdb.GeoSearchLocation(ctx, "bigboxcity", searchLocationQuery).Result()

	if err != nil {
		fmt.Println("Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2 ASC| Error: " + err.Error())
	}

	fmt.Println("Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2 ASC| Result: ", searchLocationResult)

	/**
	* Use DESC options to order desinding by disance
	*
	* Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2 DESC
	* Result:
	*      1)  1) "Tokyo"
	*          2) "2880.1615"
	*          3) (integer) 4171231230197033
	*          4)  1) "139.69171196222305298"
	*              2) "35.68948605865241319"
	*
	*      2)  1) "Bangkok"
	*          2) "1728.5852"
	*          3) (integer) 3962257436268857
	*          4)  1) "100.50176292657852173"
	*              2) "13.75633095031508191"
	 */
	searchLocationQuery = &redis.GeoSearchLocationQuery{
		GeoSearchQuery: redis.GeoSearchQuery{
			Longitude:  114.109497,
			Latitude:   22.3982,
			Radius:     9_000,
			RadiusUnit: "km",
			Count:      2,
			Sort:       "desc",
		},
		WithCoord: true,
		WithDist:  true,
		WithHash:  true,
	}
	searchLocationResult, err = rdb.GeoSearchLocation(ctx, "bigboxcity", searchLocationQuery).Result()

	if err != nil {
		fmt.Println("Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2 DESC| Error: " + err.Error())
	}

	fmt.Println("Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2 DESC| Result: ", searchLocationResult)

	/**
	* Use non existing key
	* We get empty array
	*
	* Command: geosearch wrongkey frommember Paris bybox 21500 20000 km
	* Result: (empty array)
	 */
	searchQuery = &redis.GeoSearchQuery{
		Member:    "Paris",
		BoxWidth:  21_500,
		BoxHeight: 20_000,
		BoxUnit:   "km",
	}
	searchResult, err = rdb.GeoSearch(ctx, "wrongkey", searchQuery).Result()

	if err != nil {
		fmt.Println("Command: geosearch wrongkey frommember Paris bybox 21500 20000 km | Error: " + err.Error())
	}

	fmt.Println("Command: geosearch wrongkey frommember Paris bybox 21500 20000 km | Result: ", searchResult)

	/**
	* Use non existing member name
	* We get an error
	*
	* Command: geosearch bigboxcity frommember wrongmember bybox 21500 20000 km
	* Result: (error) ERR could not decode requested zset member
	 */
	searchQuery = &redis.GeoSearchQuery{
		Member:    "wrongmember",
		BoxWidth:  21_500,
		BoxHeight: 20_000,
		BoxUnit:   "km",
	}
	searchResult, err = rdb.GeoSearch(ctx, "bigboxcity", searchQuery).Result()

	if err != nil {
		fmt.Println("Command: geosearch bigboxcity frommember wrongmember bybox 21500 20000 km | Error: " + err.Error())
	}

	fmt.Println("Command: geosearch bigboxcity frommember wrongmember bybox 21500 20000 km | Result: ", searchResult)

	/**
	* Use wrong key and wrong member name
	* We get empty array
	*
	* Command: geosearch wrongkey frommember wrongmember bybox 21500 20000 km
	* Result: (empty array)
	 */
	searchQuery = &redis.GeoSearchQuery{
		Member:    "wrongmember",
		BoxWidth:  21_500,
		BoxHeight: 20_000,
		BoxUnit:   "km",
	}
	searchResult, err = rdb.GeoSearch(ctx, "wrongkey", searchQuery).Result()

	if err != nil {
		fmt.Println("Command: geosearch wrongkey frommember wrongmember bybox 21500 20000 km | Error: " + err.Error())
	}

	fmt.Println("Command: geosearch wrongkey frommember wrongmember bybox 21500 20000 km | Result: ", searchResult)

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

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

	fmt.Println("Command: set bigboxstr \"some str here\" | Result: " + setResult)

	/**
	* Try to use a key that is not a geoindex
	* We get an error
	*
	* Command: geosearch bigboxstr fromlonlat 114.109497 22.3982 byradius 9000 km
	* Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
	 */
	searchQuery = &redis.GeoSearchQuery{
		Member:     "Paris",
		Longitude:  114.109497,
		Latitude:   22.3982,
		Radius:     9_000,
		RadiusUnit: "km",
	}
	searchResult, err = rdb.GeoSearch(ctx, "bigboxstr", searchQuery).Result()

	if err != nil {
		fmt.Println("Command: geosearch bigboxstr fromlonlat 114.109497 22.3982 byradius 9000 km | Error: " + err.Error())
	}

	fmt.Println("Command: geosearch bigboxstr fromlonlat 114.109497 22.3982 byradius 9000 km | Result: ", searchResult)
}

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: geosearch bigboxcity frommember Paris bybox 21500 20000 km | Result:  [Rome Paris Bangkok]
Command: geosearch bigboxcity frommember Paris byradius 9700 km | Result:  [Rome Paris Bangkok Hong Kong]
Command: geosearch bigboxcity frommember Paris byradius 9700 km withcoord withdist withhash | Result:  [{Rome 12.496366202831268 41.902782133789835 1105.5914 3480343273965391} {Paris 2.352219521999359 48.856612203955095 0 3663832779125283} {Bangkok 100.50176292657852 13.756330950315082 9445.7597 3962257436268857} {Hong Kong 114.10949438810349 22.396427361990284 9618.579 4046429669534462}]
Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash | Result:  [{Bangkok 100.50176292657852 13.756330950315082 1728.5852 3962257436268857} {Hong Kong 114.10949438810349 22.396427361990284 0.1972 4046429669534462} {Tokyo 139.69171196222305 35.68948605865241 2880.1615 4171231230197033}]
Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2| Result:  [{Hong Kong 114.10949438810349 22.396427361990284 0.1972 4046429669534462} {Bangkok 100.50176292657852 13.756330950315082 1728.5852 3962257436268857}]
Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2 ASC| Result:  [{Hong Kong 114.10949438810349 22.396427361990284 0.1972 4046429669534462} {Bangkok 100.50176292657852 13.756330950315082 1728.5852 3962257436268857}]
Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2 DESC| Result:  [{Tokyo 139.69171196222305 35.68948605865241 2880.1615 4171231230197033} {Bangkok 100.50176292657852 13.756330950315082 1728.5852 3962257436268857}]
Command: geosearch wrongkey frommember Paris bybox 21500 20000 km | Result:  []
Command: geosearch bigboxcity frommember wrongmember bybox 21500 20000 km | Error: ERR could not decode requested zset member
Command: geosearch bigboxcity frommember wrongmember bybox 21500 20000 km | Result:  []
Command: geosearch wrongkey frommember wrongmember bybox 21500 20000 km | Result:  []
Command: set bigboxstr "some str here" | Result: OK
Command: geosearch bigboxstr fromlonlat 114.109497 22.3982 byradius 9000 km | Error: WRONGTYPE Operation against a key holding the wrong kind of value
Command: geosearch bigboxstr fromlonlat 114.109497 22.3982 byradius 9000 km | Result:  []

NOTES

  • Use “GeoSearch” method from redis-go module.
  • Signature of the method is-
    • GeoSearch(ctx context.Context, key string, q *GeoSearchQuery) *StringSliceCmd
    • GeoSearchLocation(ctx context.Context, key string, q *GeoSearchLocationQuery) *GeoSearchLocationCmd
  • Definition of GeoSearchQuery is-

    type GeoSearchQuery struct {
        Member string

       
    // Latitude and Longitude when using FromLonLat option.
        Longitude float64
        Latitude  float64

       
    // Distance and unit when using ByRadius option.
        // Can use m, km, ft, or mi. Default is km.

        Radius     float64
        RadiusUnit string

       
    // Height, width and unit when using ByBox option.
        // Can be m, km, ft, or mi. Default is km.

        BoxWidth  float64
        BoxHeight float64
        BoxUnit   string

       
    // Can be ASC or DESC. Default is no sort order.
        Sort     string
        Count    int
        CountAny bool
    }
  • Definition of GeoSearchLocationQuery is-

    type GeoSearchLocationQuery struct {
        GeoSearchQuery
        WithCoord bool
        WithDist  bool
        WithHash  bool
    }
  • In the response data, the values will follow GeoLocation structure, if queried with GeoSearchLocationQuery

    type GeoLocation struct {
        Name                      string
        Longitude, Latitude, Dist float64
        GeoHash                   int64
    }
// Redis GEOSEARCH command example in JavaScript(NodeJS)

import { createClient, GeoReplyWith } 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 members to a geo index 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 cities in a certeain size rectagle from Paris
 *
 * Command: geosearch bigboxcity frommember Paris bybox 21500 20000 km
 * Result:
 *      1) "Rome"
 *      2) "Paris"
 *      3) "Bangkok"
 */
commandResult = await redisClient.geoSearch("bigboxcity", "Paris", {width: 21_500, height: 20_000, unit: 'km'});

console.log("Command: geosearch bigboxcity frommember Paris bybox 21500 20000 km | Result: ", commandResult);

/**
 * Check cities in 9700KM radius from Paris
 *
 * Command: geosearch bigboxcity frommember Paris byradius 9700 km
 * Result:
 *          1) "Rome"
 *          2) "Paris"
 *          3) "Bangkok"
 *          4) "Hong Kong"
 */
commandResult = await redisClient.geoSearch("bigboxcity", "Paris", {radius: 9_700, unit: 'km'});

console.log("Command: geosearch bigboxcity frommember Paris byradius 9700 km | Result: ", commandResult);

/**
 * Search location and get additional information like coordinates, distance, width
 *
 * Command: geosearch bigboxcity frommember Paris byradius 9700 km withcoord withdist withhash
 * Result:
 *      1)  1) "Rome"
 *          2) "1105.5914"
 *          3) (integer) 3480343273965391
 *          4)  1) "12.49636620283126831"
 *              2) "41.90278213378983452"
 *
 *      2)  1) "Paris"
 *          2) "0.0000"
 *          3) (integer) 3663832779125283
 *          4)  1) "2.35221952199935913"
 *              2) "48.85661220395509474"
 *
 *      3)  1) "Bangkok"
 *          2) "9445.7597"
 *          3) (integer) 3962257436268857
 *          4)  1) "100.50176292657852173"
 *              2) "13.75633095031508191"
 *
 *      4)  1) "Hong Kong"
 *          2) "9618.5790"
 *          3) (integer) 4046429669534462
 *          4)  1) "114.10949438810348511"
 *              2) "22.39642736199028406"
 */
commandResult = await redisClient.geoSearchWith("bigboxcity", "Paris", {radius: 9_700, unit: 'km'}, [GeoReplyWith.DISTANCE, GeoReplyWith.COORDINATES, GeoReplyWith.HASH]);

console.log("Command: geosearch bigboxcity frommember Paris byradius 9700 km withcoord withdist withhash | Result: ", commandResult);

/**
 * Search location by distance from certain longitude and latitude
 *
 * Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash
 * Result:
 *      1)  1) "Bangkok"
 *          2) "1728.5852"
 *          3) (integer) 3962257436268857
 *          4)  1) "100.50176292657852173"
 *              2) "13.75633095031508191"
 *
 *      2)  1) "Hong Kong"
 *          2) "0.1972"
 *          3) (integer) 4046429669534462
 *          4)  1) "114.10949438810348511"
 *              2) "22.39642736199028406"
 *
 *      3)  1) "Tokyo"
 *          2) "2880.1615"
 *          3) (integer) 4171231230197033
 *          4)  1) "139.69171196222305298"
 *              2) "35.68948605865241319"
 */
commandResult = await redisClient.geoSearchWith("bigboxcity", {longitude: 114.109497, latitude: 22.3982}, {radius: 9000, unit: 'km'}, [GeoReplyWith.DISTANCE, GeoReplyWith.COORDINATES, GeoReplyWith.HASH]);

console.log("Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash | Result: ", commandResult);

/**
 * Use COUNT option to limit the number of results
 *
 * Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2
 * Result:
 *      1)  1) "Hong Kong"
 *          2) "0.1972"
 *          3) (integer) 4046429669534462
 *          4)  1) "114.10949438810348511"
 *              2) "22.39642736199028406"
 *
 *      2)  1) "Bangkok"
 *          2) "1728.5852"
 *          3) (integer) 3962257436268857
 *          4)  1) "100.50176292657852173"
 *              2) "13.75633095031508191"
 */
commandResult = await redisClient.geoSearchWith("bigboxcity", {longitude: 114.109497, latitude: 22.3982}, {radius: 9_000, unit: 'km'}, [GeoReplyWith.DISTANCE, GeoReplyWith.COORDINATES, GeoReplyWith.HASH], {COUNT: 2});

console.log("Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2| Result: ", commandResult);

/**
 * Use ASC options to order assinding by disance
 *
 * Command: geosearch bigboxcity fromlonlat 114.109497 22.3982  byradius 9000 km withcoord withdist withhash count 2 ASC
 * Result:
 *      1)  1) "Hong Kong"
 *          2) "0.1972"
 *          3) (integer) 4046429669534462
 *          4)  1) "114.10949438810348511"
 *              2) "22.39642736199028406"
 *
 *      2)  1) "Bangkok"
 *          2) "1728.5852"
 *          3) (integer) 3962257436268857
 *          4)  1) "100.50176292657852173"
 *              2) "13.75633095031508191"
 */
commandResult = await redisClient.geoSearchWith("bigboxcity", {longitude: 114.109497, latitude: 22.3982}, {radius: 9_000, unit: 'km'}, [GeoReplyWith.DISTANCE, GeoReplyWith.COORDINATES, GeoReplyWith.HASH], {SORT: "ASC", COUNT: 2});

console.log("Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2 ASC| Result: ", commandResult);

/**
 * Use DESC options to order desinding by disance
 *
 * Command: geosearch bigboxcity fromlonlat 114.109497 22.3982  byradius 9000 km withcoord withdist withhash count 2 DESC
 * Result:
 *      1)  1) "Tokyo"
 *          2) "2880.1615"
 *          3) (integer) 4171231230197033
 *          4)  1) "139.69171196222305298"
 *              2) "35.68948605865241319"
 *
 *      2)  1) "Bangkok"
 *          2) "1728.5852"
 *          3) (integer) 3962257436268857
 *          4)  1) "100.50176292657852173"
 *              2) "13.75633095031508191"
 */
commandResult = await redisClient.geoSearchWith("bigboxcity", {longitude: 114.109497, latitude: 22.3982}, {radius: 9_000, unit: 'km'}, [GeoReplyWith.DISTANCE, GeoReplyWith.COORDINATES, GeoReplyWith.HASH], {SORT: "DESC", COUNT: 2});

console.log("Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2 DESC| Result: ", commandResult);

/**
 * Use non existing key
 * We get empty array
 *
 * Command: geosearch wrongkey frommember Paris bybox 21500 20000 km
 * Result: (empty array)
 */
commandResult = await redisClient.geoSearch("wrongkey", "Paris", {width: 21_500, height: 20_000, unit: 'km'});

console.log("Command: geosearch wrongkey frommember Paris bybox 21500 20000 km | Result: ", commandResult);

/**
 * Use non existing member name
 * We get an error
 *
 * Command: geosearch bigboxcity frommember wrongmember bybox 21500 20000 km
 * Result: (error) ERR could not decode requested zset member
 */
try {
    commandResult = await redisClient.geoSearch("bigboxcity", "wrongmember", {width: 21_500, height: 20_000, unit: 'km'});

    console.log("Command: geosearch bigboxcity frommember wrongmember bybox 21500 20000 km | Result: ", commandResult);
} catch (err) {
    console.log("Command: geosearch bigboxcity frommember wrongmember bybox 21500 20000 km | Error: ", err);
}

 /**
 * Use wrong key and wrong member name
 * We get empty array
 *
 * Command: geosearch wrongkey frommember wrongmember bybox 21500 20000 km
 * Result: (empty array)
 */
commandResult = await redisClient.geoSearch("wrongkey", "wrongmember", {width: 21_500, height: 20_000, unit: 'km'});

console.log("Command: geosearch wrongkey frommember wrongmember bybox 21500 20000 km | Result: ", commandResult);

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

console.log("Command: set bigboxstr \"some str here\" | Result: " + commandResult);

/**
 * Try to use a key that is not a geoindex
 * We get an error
 *
 * Command: geosearch bigboxstr fromlonlat 114.109497 22.3982 byradius 9000 km
 * Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
 */
try {
    commandResult = await redisClient.geoSearch("bigboxstr", {longitude: 114.109497, latitude: 22.3982}, {radius: 9000, unit: 'km'});

    console.log("Command: geosearch bigboxstr fromlonlat 114.109497 22.3982 byradius 9000 km | Result: ", commandResult);
} catch (err) {
    console.log("Command: geosearch bigboxstr fromlonlat 114.109497 22.3982 byradius 9000 km | Error: ", 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: geosearch bigboxcity frommember Paris bybox 21500 20000 km | Result:  [ 'Rome', 'Paris', 'Bangkok' ]
Command: geosearch bigboxcity frommember Paris byradius 9700 km | Result:  [ 'Rome', 'Paris', 'Bangkok', 'Hong Kong' ]
Command: geosearch bigboxcity frommember Paris byradius 9700 km withcoord withdist withhash | Result:  [
  {
    member: 'Rome',
    distance: '1105.5916',
    hash: 3480343273965390,
    coordinates: {
      longitude: '12.49636620283126831',
      latitude: '41.90277959906867977'
    }
  },
  {
    member: 'Paris',
    distance: '0.0000',
    hash: 3663832779125283,
    coordinates: {
      longitude: '2.35221952199935913',
      latitude: '48.85661220395509474'
    }
  },
  {
    member: 'Bangkok',
    distance: '9445.7597',
    hash: 3962257436268857,
    coordinates: {
      longitude: '100.50176292657852173',
      latitude: '13.75633095031508191'
    }
  },
  {
    member: 'Hong Kong',
    distance: '9618.5790',
    hash: 4046429669534462,
    coordinates: {
      longitude: '114.10949438810348511',
      latitude: '22.39642736199028406'
    }
  }
]
Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash | Result:  [
  {
    member: 'Bangkok',
    distance: '1728.5852',
    hash: 3962257436268857,
    coordinates: {
      longitude: '100.50176292657852173',
      latitude: '13.75633095031508191'
    }
  },
  {
    member: 'Hong Kong',
    distance: '0.1972',
    hash: 4046429669534462,
    coordinates: {
      longitude: '114.10949438810348511',
      latitude: '22.39642736199028406'
    }
  },
  {
    member: 'Tokyo',
    distance: '2880.1615',
    hash: 4171231230197033,
    coordinates: {
      longitude: '139.69171196222305298',
      latitude: '35.68948605865241319'
    }
  }
]
Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2| Result:  [
  {
    member: 'Hong Kong',
    distance: '0.1972',
    hash: 4046429669534462,
    coordinates: {
      longitude: '114.10949438810348511',
      latitude: '22.39642736199028406'
    }
  },
  {
    member: 'Bangkok',
    distance: '1728.5852',
    hash: 3962257436268857,
    coordinates: {
      longitude: '100.50176292657852173',
      latitude: '13.75633095031508191'
    }
  }
]
Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2 ASC| Result:  [
  {
    member: 'Hong Kong',
    distance: '0.1972',
    hash: 4046429669534462,
    coordinates: {
      longitude: '114.10949438810348511',
      latitude: '22.39642736199028406'
    }
  },
  {
    member: 'Bangkok',
    distance: '1728.5852',
    hash: 3962257436268857,
    coordinates: {
      longitude: '100.50176292657852173',
      latitude: '13.75633095031508191'
    }
  }
]
Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2 DESC| Result:  [
  {
    member: 'Tokyo',
    distance: '2880.1615',
    hash: 4171231230197033,
    coordinates: {
      longitude: '139.69171196222305298',
      latitude: '35.68948605865241319'
    }
  },
  {
    member: 'Bangkok',
    distance: '1728.5852',
    hash: 3962257436268857,
    coordinates: {
      longitude: '100.50176292657852173',
      latitude: '13.75633095031508191'
    }
  }
]
Command: geosearch wrongkey frommember Paris bybox 21500 20000 km | Result:  []
Command: geosearch bigboxcity frommember wrongmember bybox 21500 20000 km | Error:  [ErrorReply: ERR could not decode requested zset member]
Command: geosearch wrongkey frommember wrongmember bybox 21500 20000 km | Result:  []
Command: set bigboxstr "some str here" | Result: OK
Command: geosearch bigboxstr fromlonlat 114.109497 22.3982 byradius 9000 km | Error:  [ErrorReply: WRONGTYPE Operation against a key holding the wrong kind of value]

NOTES

  • Use the function “geoSearch” of node-redis.
  • Signature of the method-
    • function geoSearch(key: RedisCommandArgument, from: GeoSearchFrom, by: GeoSearchBy, options?: GeoSearchOptions)
    • function geoSearchWith(key: RedisCommandArgument, from: GeoSearchFrom, by: GeoSearchBy, replyWith: Array<GeoReplyWith>, options?: GeoSearchOptions)
  • Here is the definition of GeoSearchFrom

    export interface GeoCoordinates {
        longitude: string | number;
        latitude: string | number;
    }
    type GeoSearchFromMember = string;
    export type GeoSearchFrom = GeoSearchFromMember | GeoCoordinates;
  • Here is GeoSearchBy type-

    interface GeoSearchByRadius {
        radius: number;
        unit: GeoUnits;
    }
    interface GeoSearchByBox {
        width: number;
        height: number;
        unit: GeoUnits;
    }
    export type GeoSearchBy = GeoSearchByRadius | GeoSearchByBox;
  • Definition of GeoSearchOptions

    export interface GeoSearchOptions {
        SORT?: 'ASC' | 'DESC';
        COUNT?: GeoCountArgument;
    }
  • Definition of GeoUnits is-
    export type GeoUnits = 'm' | 'km' | 'mi' | 'ft';
  • Definition of GeoCountArgument

    type GeoCountArgument = number | {
        value: number;
        ANY?: true;
    };
  • Definition of GeoReplyWith is-

    export declare enum GeoReplyWith {
        DISTANCE = "WITHDIST",
        HASH = "WITHHASH",
        COORDINATES = "WITHCOORD"
    }
// Redis GEOSEARCH 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 redis.clients.jedis.args.SortingOrder;
import redis.clients.jedis.params.GeoSearchParam;
import redis.clients.jedis.resps.GeoRadiusResponse;

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


public class GeoSearch {

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

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

            /**
             * Add members to a geo index 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 members saved 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 | Result: " + zrangeResult.toString());


            /**
             * Check cities in a certeain size rectagle from Paris
             *
             * Command: geosearch bigboxcity frommember Paris bybox 21500 20000 km
             * Result:
             *      1) "Rome"
             *      2) "Paris"
             *      3) "Bangkok"
             */
            List<GeoRadiusResponse> searchResult = jedis.geosearch("bigboxcity", "Paris", 21_500, 20_000, GeoUnit.KM);

            System.out.println("Command: geosearch bigboxcity frommember Paris bybox 21500 20000 km | Result: ");
            printSearchResult(searchResult, false, false);

            /**
             * Check cities in 9700KM radius from Paris
             *
             * Command: geosearch bigboxcity frommember Paris byradius 9700 km
             * Result:
             *          1) "Rome"
             *          2) "Paris"
             *          3) "Bangkok"
             *          4) "Hong Kong"
             */
            searchResult = jedis.geosearch("bigboxcity", "Paris", 9700, GeoUnit.KM);

            System.out.println("Command: geosearch bigboxcity frommember Paris byradius 9700 km | Result: ");
            printSearchResult(searchResult, false, false);

            /**
             * Search location and get additional information like coordinates, distance, width
             *
             * Command: geosearch bigboxcity frommember Paris byradius 9700 km withcoord withdist withhash
             * Result:
             *      1)  1) "Rome"
             *          2) "1105.5914"
             *          3) (integer) 3480343273965391
             *          4)  1) "12.49636620283126831"
             *              2) "41.90278213378983452"
             *
             *      2)  1) "Paris"
             *          2) "0.0000"
             *          3) (integer) 3663832779125283
             *          4)  1) "2.35221952199935913"
             *              2) "48.85661220395509474"
             *
             *      3)  1) "Bangkok"
             *          2) "9445.7597"
             *          3) (integer) 3962257436268857
             *          4)  1) "100.50176292657852173"
             *              2) "13.75633095031508191"
             *
             *      4)  1) "Hong Kong"
             *          2) "9618.5790"
             *          3) (integer) 4046429669534462
             *          4)  1) "114.10949438810348511"
             *              2) "22.39642736199028406"
             */
            searchResult = jedis.geosearch("bigboxcity", GeoSearchParam.geoSearchParam().fromMember("Paris").byRadius(9700, GeoUnit.KM).withCoord().withDist().withHash());

            System.out.println("Command: geosearch bigboxcity frommember Paris byradius 9700 km withcoord withdist withhash | Result: ");
            printSearchResult(searchResult, true, true);

            /**
             * Search location by distance from certain longitude and latitude
             *
             * Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash
             * Result:
             *      1)  1) "Bangkok"
             *          2) "1728.5852"
             *          3) (integer) 3962257436268857
             *          4)  1) "100.50176292657852173"
             *              2) "13.75633095031508191"
             *
             *      2)  1) "Hong Kong"
             *          2) "0.1972"
             *          3) (integer) 4046429669534462
             *          4)  1) "114.10949438810348511"
             *              2) "22.39642736199028406"
             *
             *      3)  1) "Tokyo"
             *          2) "2880.1615"
             *          3) (integer) 4171231230197033
             *          4)  1) "139.69171196222305298"
             *              2) "35.68948605865241319"
             */
            searchResult = jedis.geosearch("bigboxcity", GeoSearchParam.geoSearchParam().fromLonLat(114.109497, 22.3982).byRadius(9000, GeoUnit.KM).withCoord().withDist().withHash());

            System.out.println("Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash | Result: ");
            printSearchResult(searchResult, true, true);

            /**
             * Use COUNT option to limit the number of results
             *
             * Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2
             * Result:
             *      1)  1) "Hong Kong"
             *          2) "0.1972"
             *          3) (integer) 4046429669534462
             *          4)  1) "114.10949438810348511"
             *              2) "22.39642736199028406"
             *
             *      2)  1) "Bangkok"
             *          2) "1728.5852"
             *          3) (integer) 3962257436268857
             *          4)  1) "100.50176292657852173"
             *              2) "13.75633095031508191"
             */
            searchResult = jedis.geosearch("bigboxcity", GeoSearchParam.geoSearchParam().fromLonLat(114.109497, 22.3982).byRadius(9000, GeoUnit.KM).withCoord().withDist().withHash().count(2));

            System.out.println("Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2| Result: ");
            printSearchResult(searchResult, true, true);

            /**
             * Use ASC options to order assinding by disance
             *
             * Command: geosearch bigboxcity fromlonlat 114.109497 22.3982  byradius 9000 km withcoord withdist withhash count 2 ASC
             * Result:
             *      1)  1) "Hong Kong"
             *          2) "0.1972"
             *          3) (integer) 4046429669534462
             *          4)  1) "114.10949438810348511"
             *              2) "22.39642736199028406"
             *
             *      2)  1) "Bangkok"
             *          2) "1728.5852"
             *          3) (integer) 3962257436268857
             *          4)  1) "100.50176292657852173"
             *              2) "13.75633095031508191"
             */
            searchResult = jedis.geosearch("bigboxcity", GeoSearchParam.geoSearchParam().fromLonLat(114.109497, 22.3982).byRadius(9000, GeoUnit.KM).withCoord().withDist().withHash().count(2).sortingOrder(SortingOrder.ASC));

            System.out.println("Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2 ASC| Result: ");
            printSearchResult(searchResult, true, true);

            /**
             * Use DESC options to order desinding by disance
             *
             * Command: geosearch bigboxcity fromlonlat 114.109497 22.3982  byradius 9000 km withcoord withdist withhash count 2 DESC
             * Result:
             *      1)  1) "Tokyo"
             *          2) "2880.1615"
             *          3) (integer) 4171231230197033
             *          4)  1) "139.69171196222305298"
             *              2) "35.68948605865241319"
             *
             *      2)  1) "Bangkok"
             *          2) "1728.5852"
             *          3) (integer) 3962257436268857
             *          4)  1) "100.50176292657852173"
             *              2) "13.75633095031508191"
             */
            searchResult = jedis.geosearch("bigboxcity", GeoSearchParam.geoSearchParam().fromLonLat(114.109497, 22.3982).byRadius(9000, GeoUnit.KM).withCoord().withDist().withHash().count(2).sortingOrder(SortingOrder.DESC));

            System.out.println("Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2 DESC| Result: ");
            printSearchResult(searchResult, true, true);

            /**
             * Use non existing key
             * We get empty array
             *
             * Command: geosearch wrongkey frommember Paris bybox 21500 20000 km
             * Result: (empty array)
             */
            searchResult = jedis.geosearch("wrongkey", "Paris", 21500, 20000, GeoUnit.KM);

            System.out.println("Command: geosearch wrongkey frommember Paris bybox 21500 20000 km | Result: ");
            printSearchResult(searchResult, false, false);

            /**
             * Use non existing member name
             * We get an error
             *
             * Command: geosearch bigboxcity frommember wrongmember bybox 21500 20000 km
             * Result: (error) ERR could not decode requested zset member
             */
            try {
                searchResult = jedis.geosearch("bigboxcity", "wrongmember", 21500, 20000, GeoUnit.KM);

                System.out.println("Command: geosearch bigboxcity frommember wrongmember bybox 21500 20000 km | Result: ");
                printSearchResult(searchResult, false, false);
            } catch (Exception e) {
                System.out.println("Command: geosearch bigboxcity frommember wrongmember bybox 21500 20000 km | Error: " + e.getMessage());
            }

             /**
             * Use wrong key and wrong member name
             * We get empty array
             *
             * Command: geosearch wrongkey frommember wrongmember bybox 21500 20000 km
             * Result: (empty array)
             */
            searchResult = jedis.geosearch("wrongkey", "wrongmember", 21500, 20000, GeoUnit.KM);

            System.out.println("Command: geosearch wrongkey frommember wrongmember bybox 21500 20000 km | Result: ");
            printSearchResult(searchResult, false, false);

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

            System.out.println("Command: set bigboxstr \"some str here\" | Result: " + setResult);

            /**
             * Try to use a key that is not a geoindex
             * We get an error
             *
             * Command: geosearch bigboxstr fromlonlat 114.109497 22.3982 byradius 9000 km
             * Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
             */
            try {
                searchResult = jedis.geosearch("bigboxstr", new GeoCoordinate(114.109497, 22.3982), 9000, GeoUnit.KM);

                System.out.println("Command: geosearch bigboxstr fromlonlat 114.109497 22.3982 byradius 9000 km | Result: ");
                printSearchResult(searchResult, false, false);
            } catch (Exception e) {
                System.out.println("Command: geosearch bigboxstr fromlonlat 114.109497 22.3982 byradius 9000 km | Error: " + e.getMessage());
            }

        }

        jedisPool.close();

    }

    static void printSearchResult(List<GeoRadiusResponse> searchResult, boolean showDistance, boolean showScore) {

        for (GeoRadiusResponse radiusResponse: searchResult) {
            ArrayList<String> result = new ArrayList<>();

            result.add("Member: " + radiusResponse.getMemberByString());

            if (showDistance) {
                result.add("Distance: " + radiusResponse.getDistance());
            }

            if (showScore) {
                result.add("Score: " + radiusResponse.getRawScore());
            }

            if (radiusResponse.getCoordinate() != null) {
                result.add("Longitude: " + radiusResponse.getCoordinate().getLongitude());
                result.add("Latitude: " + radiusResponse.getCoordinate().getLatitude());
            }

//            System.out.println("Hash Code: " + radiusResponse.hashCode());
            System.out.println(result);
        }
    }
}

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 | Result: [Rome, Paris, Bangkok, Hong Kong, Tokyo]

Command: geosearch bigboxcity frommember Paris bybox 21500 20000 km | Result: 
[Member: Rome]
[Member: Paris]
[Member: Bangkok]

Command: geosearch bigboxcity frommember Paris byradius 9700 km | Result: 
[Member: Rome]
[Member: Paris]
[Member: Bangkok]
[Member: Hong Kong]

Command: geosearch bigboxcity frommember Paris byradius 9700 km withcoord withdist withhash | Result: 
[Member: Rome, Distance: 1105.5916, Score: 3480343273965390, Longitude: 12.496366202831268, Latitude: 41.90277959906868]
[Member: Paris, Distance: 0.0, Score: 3663832779125283, Longitude: 2.352219521999359, Latitude: 48.856612203955095]
[Member: Bangkok, Distance: 9445.7597, Score: 3962257436268857, Longitude: 100.50176292657852, Latitude: 13.756330950315082]
[Member: Hong Kong, Distance: 9618.579, Score: 4046429669534462, Longitude: 114.10949438810349, Latitude: 22.396427361990284]

Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash | Result: 
[Member: Bangkok, Distance: 1728.5852, Score: 3962257436268857, Longitude: 100.50176292657852, Latitude: 13.756330950315082]
[Member: Hong Kong, Distance: 0.1972, Score: 4046429669534462, Longitude: 114.10949438810349, Latitude: 22.396427361990284]
[Member: Tokyo, Distance: 2880.1615, Score: 4171231230197033, Longitude: 139.69171196222305, Latitude: 35.68948605865241]

Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2| Result: 
[Member: Hong Kong, Distance: 0.1972, Score: 4046429669534462, Longitude: 114.10949438810349, Latitude: 22.396427361990284]
[Member: Bangkok, Distance: 1728.5852, Score: 3962257436268857, Longitude: 100.50176292657852, Latitude: 13.756330950315082]

Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2 ASC| Result: 
[Member: Hong Kong, Distance: 0.1972, Score: 4046429669534462, Longitude: 114.10949438810349, Latitude: 22.396427361990284]
[Member: Bangkok, Distance: 1728.5852, Score: 3962257436268857, Longitude: 100.50176292657852, Latitude: 13.756330950315082]

Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2 DESC| Result: 
[Member: Tokyo, Distance: 2880.1615, Score: 4171231230197033, Longitude: 139.69171196222305, Latitude: 35.68948605865241]
[Member: Bangkok, Distance: 1728.5852, Score: 3962257436268857, Longitude: 100.50176292657852, Latitude: 13.756330950315082]

Command: geosearch wrongkey frommember Paris bybox 21500 20000 km | Result: 

Command: geosearch bigboxcity frommember wrongmember bybox 21500 20000 km | Error: ERR could not decode requested zset member

Command: geosearch wrongkey frommember wrongmember bybox 21500 20000 km | Result: 

Command: set bigboxstr "some str here" | Result: OK
Command: geosearch bigboxstr fromlonlat 114.109497 22.3982 byradius 9000 km | Error: WRONGTYPE Operation against a key holding the wrong kind of value

NOTES

  • Use method “geosearch” from Jedis package.
  • The signatures of the method are-
    • List<GeoRadiusResponse> geosearch(String key, String member, double radius, GeoUnit unit)
    • List<GeoRadiusResponse> geosearch(String key, String member, double width, double height, GeoUnit unit)
    • List<GeoRadiusResponse> geosearch(String key, GeoCoordinate coord, double radius, GeoUnit unit)
    • List<GeoRadiusResponse> geosearch(String key, GeoCoordinate coord, double width, double height, GeoUnit unit)
    • List<GeoRadiusResponse> geosearch(String key, GeoSearchParam params);
// Redis GEOSEARCH command examples in C#

using StackExchange.Redis;
using System.Text.Json;

namespace GeoSearch
{
    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.SortedSetRangeByRank("bigboxcity", start: 0, stop: -1);

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

            /**
            * Check cities in a certeain size rectagle from Paris
            *
            * Command: geosearch bigboxcity frommember Paris bybox 21500 20000 km
            * Result:
            *      1) "Rome"
            *      2) "Paris"
            *      3) "Bangkok"
            */
            GeoRadiusResult[] searchResult = rdb.GeoSearch("bigboxcity", "Paris", new GeoSearchBox(21_500, 20_000, GeoUnit.Kilometers), options: GeoRadiusOptions.None);

            Console.WriteLine("Command: geosearch bigboxcity frommember Paris bybox 21500 20000 km | Result: " + JsonSerializer.Serialize(searchResult, new JsonSerializerOptions { WriteIndented = true }));

            /**
             * Check cities in 9700KM radius from Paris
             *
             * Command: geosearch bigboxcity frommember Paris byradius 9700 km
             * Result:
             *          1) "Rome"
             *          2) "Paris"
             *          3) "Bangkok"
             *          4) "Hong Kong"
             */
            searchResult = rdb.GeoSearch("bigboxcity", "Paris", new GeoSearchCircle(9700, GeoUnit.Kilometers), options: GeoRadiusOptions.None);

            Console.WriteLine("Command: geosearch bigboxcity frommember Paris byradius 9700 km | Result: " + JsonSerializer.Serialize(searchResult, new JsonSerializerOptions { WriteIndented = true }));

            /**
             * Search location and get additional information like coordinates, distance, width
             *
             * Command: geosearch bigboxcity frommember Paris byradius 9700 km withcoord withdist withhash
             * Result:
             *      1)  1) "Rome"
             *          2) "1105.5914"
             *          3) (integer) 3480343273965391
             *          4)  1) "12.49636620283126831"
             *              2) "41.90278213378983452"
             *
             *      2)  1) "Paris"
             *          2) "0.0000"
             *          3) (integer) 3663832779125283
             *          4)  1) "2.35221952199935913"
             *              2) "48.85661220395509474"
             *
             *      3)  1) "Bangkok"
             *          2) "9445.7597"
             *          3) (integer) 3962257436268857
             *          4)  1) "100.50176292657852173"
             *              2) "13.75633095031508191"
             *
             *      4)  1) "Hong Kong"
             *          2) "9618.5790"
             *          3) (integer) 4046429669534462
             *          4)  1) "114.10949438810348511"
             *              2) "22.39642736199028406"
             */
            searchResult = rdb.GeoSearch("bigboxcity", "Paris", new GeoSearchCircle(9700, GeoUnit.Kilometers), options: GeoRadiusOptions.Default);

            Console.WriteLine("Command: geosearch bigboxcity frommember Paris byradius 9700 km withcoord withdist withhash | Result: " + JsonSerializer.Serialize(searchResult, new JsonSerializerOptions { WriteIndented = true }));
            
            /**
             * Search location by distance from certain longitude and latitude
             *
             * Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash
             * Result:
             *      1)  1) "Bangkok"
             *          2) "1728.5852"
             *          3) (integer) 3962257436268857
             *          4)  1) "100.50176292657852173"
             *              2) "13.75633095031508191"
             *
             *      2)  1) "Hong Kong"
             *          2) "0.1972"
             *          3) (integer) 4046429669534462
             *          4)  1) "114.10949438810348511"
             *              2) "22.39642736199028406"
             *
             *      3)  1) "Tokyo"
             *          2) "2880.1615"
             *          3) (integer) 4171231230197033
             *          4)  1) "139.69171196222305298"
             *              2) "35.68948605865241319"
             */
            searchResult = rdb.GeoSearch("bigboxcity", 114.109497, 22.3982, new GeoSearchCircle(9000, GeoUnit.Kilometers));

            Console.WriteLine("Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash | Result: " + JsonSerializer.Serialize(searchResult, new JsonSerializerOptions { WriteIndented = true }));
            
            /**
             * Use COUNT option to limit the number of results
             *
             * Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2
             * Result:
             *      1)  1) "Hong Kong"
             *          2) "0.1972"
             *          3) (integer) 4046429669534462
             *          4)  1) "114.10949438810348511"
             *              2) "22.39642736199028406"
             *
             *      2)  1) "Bangkok"
             *          2) "1728.5852"
             *          3) (integer) 3962257436268857
             *          4)  1) "100.50176292657852173"
             *              2) "13.75633095031508191"
             */
            searchResult = rdb.GeoSearch("bigboxcity", 114.109497, 22.3982, new GeoSearchCircle(9000, GeoUnit.Kilometers), count: 2);

            Console.WriteLine("Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2| Result: " + JsonSerializer.Serialize(searchResult, new JsonSerializerOptions { WriteIndented = true }));

            /**
             * Use ASC options to order assinding by disance
             *
             * Command: geosearch bigboxcity fromlonlat 114.109497 22.3982  byradius 9000 km withcoord withdist withhash count 2 ASC
             * Result:
             *      1)  1) "Hong Kong"
             *          2) "0.1972"
             *          3) (integer) 4046429669534462
             *          4)  1) "114.10949438810348511"
             *              2) "22.39642736199028406"
             *
             *      2)  1) "Bangkok"
             *          2) "1728.5852"
             *          3) (integer) 3962257436268857
             *          4)  1) "100.50176292657852173"
             *              2) "13.75633095031508191"
             */
            searchResult = rdb.GeoSearch("bigboxcity", 114.109497, 22.3982, new GeoSearchCircle(9000, GeoUnit.Kilometers), count: 2, order: Order.Ascending);

            Console.WriteLine("Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2 ASC| Result: " + JsonSerializer.Serialize(searchResult, new JsonSerializerOptions { WriteIndented = true }));

            /**
             * Use DESC options to order desinding by disance
             *
             * Command: geosearch bigboxcity fromlonlat 114.109497 22.3982  byradius 9000 km withcoord withdist withhash count 2 DESC
             * Result:
             *      1)  1) "Tokyo"
             *          2) "2880.1615"
             *          3) (integer) 4171231230197033
             *          4)  1) "139.69171196222305298"
             *              2) "35.68948605865241319"
             *
             *      2)  1) "Bangkok"
             *          2) "1728.5852"
             *          3) (integer) 3962257436268857
             *          4)  1) "100.50176292657852173"
             *              2) "13.75633095031508191"
             */
            searchResult = rdb.GeoSearch("bigboxcity", 114.109497, 22.3982, new GeoSearchCircle(9000, GeoUnit.Kilometers), count: 2, order: Order.Descending);

            Console.WriteLine("Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2 DESC| Result: " + JsonSerializer.Serialize(searchResult, new JsonSerializerOptions { WriteIndented = true }));

            /**
             * Use non existing key
             * We get empty array
             *
             * Command: geosearch wrongkey frommember Paris bybox 21500 20000 km
             * Result: (empty array)
             */
            searchResult = rdb.GeoSearch("wrongkey", "Paris", new GeoSearchBox(21500, 20000, GeoUnit.Kilometers));

            Console.WriteLine("Command: geosearch wrongkey frommember Paris bybox 21500 20000 km | Result: " + JsonSerializer.Serialize(searchResult));

            /**
             * Use non existing member name
             * We get an error
             *
             * Command: geosearch bigboxcity frommember wrongmember bybox 21500 20000 km
             * Result: (error) ERR could not decode requested zset member
             */
            try
            {
                searchResult = rdb.GeoSearch("bigboxcity", "wrongmember", new GeoSearchBox(21500, 20000, GeoUnit.Kilometers));

                Console.WriteLine("Command: geosearch bigboxcity frommember wrongmember bybox 21500 20000 km | Result: " + JsonSerializer.Serialize(searchResult, new JsonSerializerOptions { WriteIndented = true }));
            }
            catch (Exception e)
            {
                Console.WriteLine("Command: geosearch bigboxcity frommember wrongmember bybox 21500 20000 km | Error: " + e.Message);
            }

            /**
            * Use wrong key and wrong member name
            * We get empty array
            *
            * Command: geosearch wrongkey frommember wrongmember bybox 21500 20000 km
            * Result: (empty array)
            */
            searchResult = rdb.GeoSearch("wrongkey", "wrongmember", new GeoSearchBox(21500, 20000, GeoUnit.Kilometers));

            Console.WriteLine("Command: geosearch wrongkey frommember wrongmember bybox 21500 20000 km | Result: " + JsonSerializer.Serialize(searchResult, new JsonSerializerOptions { WriteIndented = true }));

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

            Console.WriteLine("Command: set bigboxstr \"some str here\" | Result: " + setResult);

            /**
             * Try to use a key that is not a geoindexc#
             * We get an error
             *
             * Command: geosearch bigboxstr fromlonlat 114.109497 22.3982 byradius 9000 km
             * Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
             */
            try
            {
                searchResult = rdb.GeoSearch("bigboxstr", 114.109497, 22.3982, new GeoSearchCircle(9000, GeoUnit.Kilometers));

                Console.WriteLine("Command: geosearch bigboxstr fromlonlat 114.109497 22.3982 byradius 9000 km | Result: " + JsonSerializer.Serialize(searchResult, new JsonSerializerOptions { WriteIndented = true }));
            }
            catch (Exception e)
            {
                Console.WriteLine("Command: geosearch bigboxstr fromlonlat 114.109497 22.3982 byradius 9000 km | Error: " + 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: Rome,Paris,Bangkok,Hong Kong,Tokyo
Command: geosearch bigboxcity frommember Paris bybox 21500 20000 km | Result: [
  {
    "Member": {
      "IsInteger": false,
      "IsNull": false,
      "IsNullOrEmpty": false,
      "HasValue": true
    },
    "Distance": null,
    "Hash": null,
    "Position": null
  },
  {
    "Member": {
      "IsInteger": false,
      "IsNull": false,
      "IsNullOrEmpty": false,
      "HasValue": true
    },
    "Distance": null,
    "Hash": null,
    "Position": null
  }
]
Command: geosearch bigboxcity frommember Paris byradius 9700 km | Result: [
  {
    "Member": {
      "IsInteger": false,
      "IsNull": false,
      "IsNullOrEmpty": false,
      "HasValue": true
    },
    "Distance": null,
    "Hash": null,
    "Position": null
  },
  {
    "Member": {
      "IsInteger": false,
      "IsNull": false,
      "IsNullOrEmpty": false,
      "HasValue": true
    },
    "Distance": null,
    "Hash": null,
    "Position": null
  },
  {
    "Member": {
      "IsInteger": false,
      "IsNull": false,
      "IsNullOrEmpty": false,
      "HasValue": true
    },
    "Distance": null,
    "Hash": null,
    "Position": null
  },
  {
    "Member": {
      "IsInteger": false,
      "IsNull": false,
      "IsNullOrEmpty": false,
      "HasValue": true
    },
    "Distance": null,
    "Hash": null,
    "Position": null
  }
]
Command: geosearch bigboxcity frommember Paris byradius 9700 km withcoord withdist withhash | Result: [
  {
    "Member": {
      "IsInteger": false,
      "IsNull": false,
      "IsNullOrEmpty": false,
      "HasValue": true
    },
    "Distance": 1105.5916,
    "Hash": null,
    "Position": {
      "Latitude": 41.90277959906868,
      "Longitude": 12.496366202831268
    }
  },
  {
    "Member": {
      "IsInteger": false,
      "IsNull": false,
      "IsNullOrEmpty": false,
      "HasValue": true
    },
    "Distance": 0,
    "Hash": null,
    "Position": {
      "Latitude": 48.856612203955095,
      "Longitude": 2.352219521999359
    }
  },
  {
    "Member": {
      "IsInteger": false,
      "IsNull": false,
      "IsNullOrEmpty": false,
      "HasValue": true
    },
    "Distance": 9445.7597,
    "Hash": null,
    "Position": {
      "Latitude": 13.756330950315082,
      "Longitude": 100.50176292657852
    }
  },
  {
    "Member": {
      "IsInteger": false,
      "IsNull": false,
      "IsNullOrEmpty": false,
      "HasValue": true
    },
    "Distance": 9618.579,
    "Hash": null,
    "Position": {
      "Latitude": 22.396427361990284,
      "Longitude": 114.10949438810349
    }
  }
]
Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash | Result: [
  {
    "Member": {
      "IsInteger": false,
      "IsNull": false,
      "IsNullOrEmpty": false,
      "HasValue": true
    },
    "Distance": 1728.5852,
    "Hash": null,
    "Position": {
      "Latitude": 13.756330950315082,
      "Longitude": 100.50176292657852
    }
  },
  {
    "Member": {
      "IsInteger": false,
      "IsNull": false,
      "IsNullOrEmpty": false,
      "HasValue": true
    },
    "Distance": 0.1972,
    "Hash": null,
    "Position": {
      "Latitude": 22.396427361990284,
      "Longitude": 114.10949438810349
    }
  },
  {
    "Member": {
      "IsInteger": false,
      "IsNull": false,
      "IsNullOrEmpty": false,
      "HasValue": true
    },
    "Distance": 2880.1615,
    "Hash": null,
    "Position": {
      "Latitude": 35.68948605865241,
      "Longitude": 139.69171196222305
    }
  }
]
Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2| Result: [
  {
    "Member": {
      "IsInteger": false,
      "IsNull": false,
      "IsNullOrEmpty": false,
      "HasValue": true
    },
    "Distance": 0.1972,
    "Hash": null,
    "Position": {
      "Latitude": 22.396427361990284,
      "Longitude": 114.10949438810349
    }
  },
  {
    "Member": {
      "IsInteger": false,
      "IsNull": false,
      "IsNullOrEmpty": false,
      "HasValue": true
    },
    "Distance": 1728.5852,
    "Hash": null,
    "Position": {
      "Latitude": 13.756330950315082,
      "Longitude": 100.50176292657852
    }
  }
]
Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2 ASC| Result: [
  {
    "Member": {
      "IsInteger": false,
      "IsNull": false,
      "IsNullOrEmpty": false,
      "HasValue": true
    },
    "Distance": 0.1972,
    "Hash": null,
    "Position": {
      "Latitude": 22.396427361990284,
      "Longitude": 114.10949438810349
    }
  },
  {
    "Member": {
      "IsInteger": false,
      "IsNull": false,
      "IsNullOrEmpty": false,
      "HasValue": true
    },
    "Distance": 1728.5852,
    "Hash": null,
    "Position": {
      "Latitude": 13.756330950315082,
      "Longitude": 100.50176292657852
    }
  }
]
Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2 DESC| Result: [
  {
    "Member": {
      "IsInteger": false,
      "IsNull": false,
      "IsNullOrEmpty": false,
      "HasValue": true
    },
    "Distance": 2880.1615,
    "Hash": null,
    "Position": {
      "Latitude": 35.68948605865241,
      "Longitude": 139.69171196222305
    }
  },
  {
    "Member": {
      "IsInteger": false,
      "IsNull": false,
      "IsNullOrEmpty": false,
      "HasValue": true
    },
    "Distance": 1728.5852,
    "Hash": null,
    "Position": {
      "Latitude": 13.756330950315082,
      "Longitude": 100.50176292657852
    }
  }
]
Command: geosearch wrongkey frommember Paris bybox 21500 20000 km | Result: []
Command: geosearch bigboxcity frommember wrongmember bybox 21500 20000 km | Error: ERR could not decode requested zset member
Command: geosearch wrongkey frommember wrongmember bybox 21500 20000 km | Result: []
Command: set bigboxstr "some str here" | Result: True
Command: geosearch bigboxstr fromlonlat 114.109497 22.3982 byradius 9000 km | Error: WRONGTYPE Operation against a key holding the wrong kind of value

NOTES

  • Use the method “GeoSearch” from StackExchange.Redis.
  • Method signatures-
    • GeoRadiusResult[] GeoSearch(RedisKey key, RedisValue member, GeoSearchShape shape, int count = -1, bool demandClosest = true, Order? order = null, GeoRadiusOptions options = GeoRadiusOptions.Default, CommandFlags flags = CommandFlags.None)
    • GeoRadiusResult[] GeoSearch(RedisKey key, double longitude, double latitude, GeoSearchShape shape, int count = -1, bool demandClosest = true, Order? order = null, GeoRadiusOptions options = GeoRadiusOptions.Default, CommandFlags flags = CommandFlags.None)
<?php
// Redis GEOSEARCH command example in PHP

require 'vendor/autoload.php';

use Predis\Command\Argument\Geospatial\ByRadius;
use Predis\Command\Argument\Geospatial\FromLonLat;
use Predis\Command\Argument\Geospatial\FromMember;
use Predis\Command\Argument\Geospatial\ByBox;

// Connect to Redis
$redisClient = new Predis\Client([
    '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 cities in a certeain size rectagle from Paris
 *
 * Command: geosearch bigboxcity frommember Paris bybox 21500 20000 km
 * Result:
 *      1) "Rome"
 *      2) "Paris"
 *      3) "Bangkok"
 */
$commandResult = $redisClient->geosearch("bigboxcity", new FromMember("Paris"), new ByBox(21_500, 20_000, "km"));

echo "Command: geosearch bigboxcity frommember Paris bybox 21500 20000 km | Result: ";
print_r($commandResult);

/**
 * Check cities in 9700KM radius from Paris
 *
 * Command: geosearch bigboxcity frommember Paris byradius 9700 km
 * Result:
 *          1) "Rome"
 *          2) "Paris"
 *          3) "Bangkok"
 *          4) "Hong Kong"
 */
$commandResult = $redisClient->geosearch("bigboxcity", new FromMember("Paris"), new ByRadius(9700, 'km'));

echo "Command: geosearch bigboxcity frommember Paris byradius 9700 km | Result: ";
print_r($commandResult);

/**
 * Search location and get additional information like coordinates, distance, width
 *
 * Command: geosearch bigboxcity frommember Paris byradius 9700 km withcoord withdist withhash
 * Result:
 *      1)  1) "Rome"
 *          2) "1105.5914"
 *          3) (integer) 3480343273965391
 *          4)  1) "12.49636620283126831"
 *              2) "41.90278213378983452"
 *
 *      2)  1) "Paris"
 *          2) "0.0000"
 *          3) (integer) 3663832779125283
 *          4)  1) "2.35221952199935913"
 *              2) "48.85661220395509474"
 *
 *      3)  1) "Bangkok"
 *          2) "9445.7597"
 *          3) (integer) 3962257436268857
 *          4)  1) "100.50176292657852173"
 *              2) "13.75633095031508191"
 *
 *      4)  1) "Hong Kong"
 *          2) "9618.5790"
 *          3) (integer) 4046429669534462
 *          4)  1) "114.10949438810348511"
 *              2) "22.39642736199028406"
 */
$commandResult = $redisClient->geosearch("bigboxcity", new FromMember("Paris"), new ByRadius(9_700, "km"), null, -1, false, true, true, true);

echo "Command: geosearch bigboxcity frommember Paris byradius 9700 km withcoord withdist withhash | Result: ";
print_r($commandResult);

/**
 * Search location by distance from certain longitude and latitude
 *
 * Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash
 * Result:
 *      1)  1) "Bangkok"
 *          2) "1728.5852"
 *          3) (integer) 3962257436268857
 *          4)  1) "100.50176292657852173"
 *              2) "13.75633095031508191"
 *
 *      2)  1) "Hong Kong"
 *          2) "0.1972"
 *          3) (integer) 4046429669534462
 *          4)  1) "114.10949438810348511"
 *              2) "22.39642736199028406"
 *
 *      3)  1) "Tokyo"
 *          2) "2880.1615"
 *          3) (integer) 4171231230197033
 *          4)  1) "139.69171196222305298"
 *              2) "35.68948605865241319"
 */
$commandResult = $redisClient->geosearch("bigboxcity", new FromLonLat(114.109497, 22.3982), new ByRadius(9000, "km"), null, -1, false, true, true, true);

echo "Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash | Result: ";
print_r($commandResult);

/**
 * Use COUNT option to limit the number of results
 *
 * Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2
 * Result:
 *      1)  1) "Hong Kong"
 *          2) "0.1972"
 *          3) (integer) 4046429669534462
 *          4)  1) "114.10949438810348511"
 *              2) "22.39642736199028406"
 *
 *      2)  1) "Bangkok"
 *          2) "1728.5852"
 *          3) (integer) 3962257436268857
 *          4)  1) "100.50176292657852173"
 *              2) "13.75633095031508191"
 */
$commandResult = $redisClient->geosearch("bigboxcity", new FromLonLat(114.109497, 22.3982), new ByRadius(9000, "km"), null, 2, false, true, true, true);

echo "Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2| Result: ";
print_r($commandResult);

/**
 * Use ASC options to order assinding by disance
 *
 * Command: geosearch bigboxcity fromlonlat 114.109497 22.3982  byradius 9000 km withcoord withdist withhash count 2 ASC
 * Result:
 *      1)  1) "Hong Kong"
 *          2) "0.1972"
 *          3) (integer) 4046429669534462
 *          4)  1) "114.10949438810348511"
 *              2) "22.39642736199028406"
 *
 *      2)  1) "Bangkok"
 *          2) "1728.5852"
 *          3) (integer) 3962257436268857
 *          4)  1) "100.50176292657852173"
 *              2) "13.75633095031508191"
 */
$commandResult = $redisClient->geosearch("bigboxcity", new FromLonLat(114.109497, 22.3982), new ByRadius(9000, "km"), "asc", 2, false, true, true, true);

echo "Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2 ASC| Result: ";
print_r($commandResult);

/**
 * Use DESC options to order desinding by disance
 *
 * Command: geosearch bigboxcity fromlonlat 114.109497 22.3982  byradius 9000 km withcoord withdist withhash count 2 DESC
 * Result:
 *      1)  1) "Tokyo"
 *          2) "2880.1615"
 *          3) (integer) 4171231230197033
 *          4)  1) "139.69171196222305298"
 *              2) "35.68948605865241319"
 *
 *      2)  1) "Bangkok"
 *          2) "1728.5852"
 *          3) (integer) 3962257436268857
 *          4)  1) "100.50176292657852173"
 *              2) "13.75633095031508191"
 */
$commandResult = $redisClient->geosearch("bigboxcity", new FromLonLat(114.109497, 22.3982), new ByRadius(9000, "km"), "desc", 2, false, true, true, true);

echo "Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2 DESC| Result: ";
print_r($commandResult);

/**
 * Use non existing key
 * We get empty array
 *
 * Command: geosearch wrongkey frommember Paris bybox 21500 20000 km
 * Result: (empty array)
 */
$commandResult = $redisClient->geosearch("wrongkey", new FromMember("Paris"), new ByBox(21500, 20000, "km"));

echo "Command: geosearch wrongkey frommember Paris bybox 21500 20000 km | Result: ";
print_r($commandResult);

/**
 * Use non existing member name
 * We get an error
 *
 * Command: geosearch bigboxcity frommember wrongmember bybox 21500 20000 km
 * Result: (error) ERR could not decode requested zset member
 */
try {
    $commandResult = $redisClient->geosearch("bigboxcity", new FromMember("wrongmember"), new ByBox(21_500, 20_000, "km"));

    echo "Command: geosearch bigboxcity frommember wrongmember bybox 21500 20000 km | Result: ";
    print_r($commandResult);
} catch (\Exception $e) {
    echo "Command: geosearch bigboxcity frommember wrongmember bybox 21500 20000 km | Error: " . $e->getMessage() . "\n";
}

/**
 * Use wrong key and wrong member name
 * We get empty array
 *
 * Command: geosearch wrongkey frommember wrongmember bybox 21500 20000 km
 * Result: (empty array)
 */
$commandResult = $redisClient->geosearch("wrongkey", new FromMember("wrongmember"), new ByBox(21_500, 20_000, "km"));

echo "Command: geosearch wrongkey frommember wrongmember bybox 21500 20000 km | Result: ";
print_r($commandResult);

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

echo "Command: set bigboxstr \"some str here\" | Result: " . $commandResult . "\n";

/**
 * Try to use a key that is not a geoindex
 * We get an error
 *
 * Command: geosearch bigboxstr fromlonlat 114.109497 22.3982 byradius 9000 km
 * Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
 */
try {
    $commandResult = $redisClient->geosearch("bigboxstr", new FromLonLat(114.109497, 22.3982), new ByRadius(9_000, 'km'));

    echo "Command: geosearch bigboxstr fromlonlat 114.109497 22.3982 byradius 9000 km | Result: ";
    print_r($commandResult);
} catch (\Exception $e) {
    echo "Command: geosearch bigboxstr fromlonlat 114.109497 22.3982 byradius 9000 km | Error: " . $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: geosearch bigboxcity frommember Paris bybox 21500 20000 km | Result: Array
(
    [0] => Rome
    [1] => Paris
    [2] => Bangkok
)
Command: geosearch bigboxcity frommember Paris byradius 9700 km | Result: Array
(
    [0] => Rome
    [1] => Paris
    [2] => Bangkok
    [3] => Hong Kong
)
Command: geosearch bigboxcity frommember Paris byradius 9700 km withcoord withdist withhash | Result: Array
(
    [Rome] => Array
        (
            [dist] => 1105.5914
            [hash] => 3480343273965391
            [lng] => 12.49637
            [lat] => 41.90278
        )

    [Paris] => Array
        (
            [dist] => 0
            [hash] => 3663832779125283
            [lng] => 2.35222
            [lat] => 48.85661
        )

    [Bangkok] => Array
        (
            [dist] => 9445.7597
            [hash] => 3962257436268857
            [lng] => 100.50176
            [lat] => 13.75633
        )

    [Hong Kong] => Array
        (
            [dist] => 9618.579
            [hash] => 4046429669534462
            [lng] => 114.10949
            [lat] => 22.39643
        )

)
Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash | Result: Array
(
    [Bangkok] => Array
        (
            [dist] => 1728.5852
            [hash] => 3962257436268857
            [lng] => 100.50176
            [lat] => 13.75633
        )

    [Hong Kong] => Array
        (
            [dist] => 0.1972
            [hash] => 4046429669534462
            [lng] => 114.10949
            [lat] => 22.39643
        )

    [Tokyo] => Array
        (
            [dist] => 2880.1615
            [hash] => 4171231230197033
            [lng] => 139.69171
            [lat] => 35.68949
        )

)
Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2| Result: Array
(
    [Hong Kong] => Array
        (
            [dist] => 0.1972
            [hash] => 4046429669534462
            [lng] => 114.10949
            [lat] => 22.39643
        )

    [Bangkok] => Array
        (
            [dist] => 1728.5852
            [hash] => 3962257436268857
            [lng] => 100.50176
            [lat] => 13.75633
        )

)
Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2 ASC| Result: Array
(
    [Hong Kong] => Array
        (
            [dist] => 0.1972
            [hash] => 4046429669534462
            [lng] => 114.10949
            [lat] => 22.39643
        )

    [Bangkok] => Array
        (
            [dist] => 1728.5852
            [hash] => 3962257436268857
            [lng] => 100.50176
            [lat] => 13.75633
        )

)
Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2 DESC| Result: Array
(
    [Tokyo] => Array
        (
            [dist] => 2880.1615
            [hash] => 4171231230197033
            [lng] => 139.69171
            [lat] => 35.68949
        )

    [Bangkok] => Array
        (
            [dist] => 1728.5852
            [hash] => 3962257436268857
            [lng] => 100.50176
            [lat] => 13.75633
        )

)
Command: geosearch wrongkey frommember Paris bybox 21500 20000 km | Result: Array
(
)
Command: geosearch bigboxcity frommember wrongmember bybox 21500 20000 km | Error: ERR could not decode requested zset member
Command: geosearch wrongkey frommember wrongmember bybox 21500 20000 km | Result: Array
(
)
Command: set bigboxstr "some str here" | Result: OK
Command: geosearch bigboxstr fromlonlat 114.109497 22.3982 byradius 9000 km | Error: WRONGTYPE Operation against a key holding the wrong kind of value

NOTES

  • Use the method “geosearch” of predis.
  • Signature of the method is-
    • geosearch(string $key, FromInterface $from, ByInterface $by, ?string $sorting = null, int $count = -1, bool $any = false, bool $withCoord = false, bool $withDist = false, bool $withHash = false): array
# Redis GEOSEARCH 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 cities in a certeain size rectagle from Paris
# Command: geosearch bigboxcity frommember Paris bybox 21500 20000 km
# Result:
#      1) "Rome"
#      2) "Paris"
#      3) "Bangkok"
commandResult = redisClient.geosearch("bigboxcity", member= "Paris", width= 21_500, height= 20_000, unit= "km")

print("Command= geosearch bigboxcity frommember Paris bybox 21500 20000 km | Result: {}".format(commandResult))

# Check cities in 9700KM radius from Paris
# Command: geosearch bigboxcity frommember Paris byradius 9700 km
# Result:
#          1) "Rome"
#          2) "Paris"
#          3) "Bangkok"
#          4) "Hong Kong"
commandResult = redisClient.geosearch("bigboxcity", member= "Paris", radius= 9700, unit= 'km')

print("Command: geosearch bigboxcity frommember Paris byradius 9700 km | Result: {}".format(commandResult))

# Search location and get additional information like coordinates, distance, width
# Command: geosearch bigboxcity frommember Paris byradius 9700 km withcoord withdist withhash
# Result:
#      1)  1) "Rome"
#          2) "1105.5914"
#          3) (integer) 3480343273965391
#          4)  1) "12.49636620283126831"
#              2) "41.90278213378983452"
#      2)  1) "Paris"
#          2) "0.0000"
#          3) (integer) 3663832779125283
#          4)  1) "2.35221952199935913"
#              2) "48.85661220395509474"
#      3)  1) "Bangkok"
#          2) "9445.7597"
#          3) (integer) 3962257436268857
#          4)  1) "100.50176292657852173"
#              2) "13.75633095031508191"
#      4)  1) "Hong Kong"
#          2) "9618.5790"
#          3) (integer) 4046429669534462
#          4)  1) "114.10949438810348511"
#              2) "22.39642736199028406"
commandResult = redisClient.geosearch("bigboxcity", member= "Paris", radius= 9_700, unit= "km", withcoord= True, withdist= True, withhash= True)

print("Command: geosearch bigboxcity frommember Paris byradius 9700 km withcoord withdist withhash | Result: {}".format(commandResult))

# Search location by distance from certain longitude and latitude
# Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash
# Result:
#      1)  1) "Bangkok"
#          2) "1728.5852"
#          3) (integer) 3962257436268857
#          4)  1) "100.50176292657852173"
#              2) "13.75633095031508191"
#      2)  1) "Hong Kong"
#          2) "0.1972"
#          3) (integer) 4046429669534462
#          4)  1) "114.10949438810348511"
#              2) "22.39642736199028406"
#      3)  1) "Tokyo"
#          2) "2880.1615"
#          3) (integer) 4171231230197033
#          4)  1) "139.69171196222305298"
#              2) "35.68948605865241319"
commandResult = redisClient.geosearch("bigboxcity", longitude= 114.109497, latitude= 22.3982, radius= 9000, unit= "km", withcoord= True, withdist= True, withhash= True)

print("Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash | Result: {}".format(commandResult))

# Use COUNT option to limit the number of results
# Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2
# Result:
#      1)  1) "Hong Kong"
#          2) "0.1972"
#          3) (integer) 4046429669534462
#          4)  1) "114.10949438810348511"
#              2) "22.39642736199028406"
#      2)  1) "Bangkok"
#          2) "1728.5852"
#          3) (integer) 3962257436268857
#          4)  1) "100.50176292657852173"
#              2) "13.75633095031508191"
commandResult = redisClient.geosearch("bigboxcity", longitude= 114.109497, latitude= 22.3982, radius= 9000, unit= "km", count= 2, withcoord= True, withdist= True, withhash= True)

print("Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2| Result: {}".format(commandResult))

# Use ASC options to order assinding by disance
# Command: geosearch bigboxcity fromlonlat 114.109497 22.3982  byradius 9000 km withcoord withdist withhash count 2 ASC
# Result:
#      1)  1) "Hong Kong"
#          2) "0.1972"
#          3) (integer) 4046429669534462
#          4)  1) "114.10949438810348511"
#              2) "22.39642736199028406"
#      2)  1) "Bangkok"
#          2) "1728.5852"
#          3) (integer) 3962257436268857
#          4)  1) "100.50176292657852173"
#              2) "13.75633095031508191"
commandResult = redisClient.geosearch("bigboxcity", longitude= 114.109497, latitude= 22.3982, radius= 9000, unit= "km", sort= "asc", count= 2, withcoord= True, withdist= True, withhash= True)

print("Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2 ASC| Result: {}".format(commandResult))

# Use DESC options to order desinding by disance
# Command: geosearch bigboxcity fromlonlat 114.109497 22.3982  byradius 9000 km withcoord withdist withhash count 2 DESC
# Result:
#      1)  1) "Tokyo"
#          2) "2880.1615"
#          3) (integer) 4171231230197033
#          4)  1) "139.69171196222305298"
#              2) "35.68948605865241319"
#      2)  1) "Bangkok"
#          2) "1728.5852"
#          3) (integer) 3962257436268857
#          4)  1) "100.50176292657852173"
#              2) "13.75633095031508191"
commandResult = redisClient.geosearch("bigboxcity", longitude= 114.109497, latitude= 22.3982, radius= 9000, unit= "km", sort= "desc", count= 2, withcoord= True, withdist= True, withhash= True)

print("Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2 DESC| Result: {}".format(commandResult))

# Use non existing key
# We get empty array
# Command: geosearch wrongkey frommember Paris bybox 21500 20000 km
# Result: (empty array)
commandResult = redisClient.geosearch("wrongkey", member= "Paris", width= 21500, height= 20000, unit= "km")

print("Command: geosearch wrongkey frommember Paris bybox 21500 20000 km | Result: {}".format(commandResult))

# Use non existing member name
# We get an error
# Command: geosearch bigboxcity frommember wrongmember bybox 21500 20000 km
# Result: (error) ERR could not decode requested zset member
try:
    commandResult = redisClient.geosearch("bigboxcity", member= "wrongmember", width= 21_500, height= 20_000, unit= "km")

    print("Command: geosearch bigboxcity frommember wrongmember bybox 21500 20000 km | Result: {}".format(commandResult))
except Exception as error:
    print("Command: geosearch bigboxcity frommember wrongmember bybox 21500 20000 km | Error: ", error)

# Use wrong key and wrong member name
# We get empty array
# Command: geosearch wrongkey frommember wrongmember bybox 21500 20000 km
# Result: (empty array)
commandResult = redisClient.geosearch("wrongkey", member= "wrongmember", width= 21_500, height= 20_000, unit= "km")

print("Command: geosearch wrongkey frommember wrongmember bybox 21500 20000 km | Result: {}".format(commandResult))

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

print("Command: set bigboxstr \"some str here\" | Result: {}".format(commandResult))

# Try to use a key that is not a geoindex
# We get an error
# Command: geosearch bigboxstr fromlonlat 114.109497 22.3982 byradius 9000 km
# Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
try:
    commandResult = redisClient.geosearch("bigboxstr", longitude= 114.109497, height= 22.3982, radius= 9_000, unit= 'km')

    print("Command: geosearch bigboxstr fromlonlat 114.109497 22.3982 byradius 9000 km | Result: {}".format(commandResult))
except Exception as error:
    print("Command: geosearch bigboxstr fromlonlat 114.109497 22.3982 byradius 9000 km | Error: ", 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= geosearch bigboxcity frommember Paris bybox 21500 20000 km | Result: ['Rome', 'Paris', 'Bangkok']
Command: geosearch bigboxcity frommember Paris byradius 9700 km | Result: ['Rome', 'Paris', 'Bangkok', 'Hong Kong']
Command: geosearch bigboxcity frommember Paris byradius 9700 km withcoord withdist withhash | Result: [['Rome', 1105.5914, 3480343273965391, (12.496366202831268, 41.902782133789835)], ['Paris', 0.0, 3663832779125283, (2.352219521999359, 48.856612203955095)], ['Bangkok', 9445.7597, 3962257436268857, (100.50176292657852, 13.756330950315082)], ['Hong Kong', 9618.579, 4046429669534462, (114.10949438810349, 22.396427361990284)]]
Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash | Result: [['Bangkok', 1728.5852, 3962257436268857, (100.50176292657852, 13.756330950315082)], ['Hong Kong', 0.1972, 4046429669534462, (114.10949438810349, 22.396427361990284)], ['Tokyo', 2880.1615, 4171231230197033, (139.69171196222305, 35.68948605865241)]]
Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2| Result: [['Hong Kong', 0.1972, 4046429669534462, (114.10949438810349, 22.396427361990284)], ['Bangkok', 1728.5852, 3962257436268857, (100.50176292657852, 13.756330950315082)]]
Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2 ASC| Result: [['Hong Kong', 0.1972, 4046429669534462, (114.10949438810349, 22.396427361990284)], ['Bangkok', 1728.5852, 3962257436268857, (100.50176292657852, 13.756330950315082)]]
Command: geosearch bigboxcity fromlonlat 114.109497 22.3982 byradius 9000 km withcoord withdist withhash count 2 DESC| Result: [['Tokyo', 2880.1615, 4171231230197033, (139.69171196222305, 35.68948605865241)], ['Bangkok', 1728.5852, 3962257436268857, (100.50176292657852, 13.756330950315082)]]
Command: geosearch wrongkey frommember Paris bybox 21500 20000 km | Result: []
Command: geosearch bigboxcity frommember wrongmember bybox 21500 20000 km | Error:  could not decode requested zset member
Command: geosearch wrongkey frommember wrongmember bybox 21500 20000 km | Result: []
Command: set bigboxstr "some str here" | Result: True
Command: geosearch bigboxstr fromlonlat 114.109497 22.3982 byradius 9000 km | Error:  GEOSEARCH must have member or longitude and latitude 

NOTES

  • Use method “geosearch” from redis-py.
  • Signature of the method is –
    • def geosearch(
              self,
              name: KeyT,
              member: Union[FieldT, None] = None,
              longitude: Union[float, None] = None,
              latitude: Union[float, None] = None,
              unit: str = "m",
              radius: Union[float, None] = None,
              width: Union[float, None] = None,
              height: Union[float, None] = None,
              sort: Union[str, None] = None,
              count: Union[int, None] = None,
              any: bool = False,
              withcoord: bool = False,
              withdist: bool = False,
              withhash: bool = False,
      ) -> ResponseT
# todo
# GEOSEARCH command support is not availabe in the redis-rb gem
# Example will be added as soon as the command support is added in the gem

Output:

# todo

NOTES

  • @todo – GEOSEARCH command support is not avaialbe in the redis-rb gem

Source Code

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

Related Commands

CommandDetails
GEOADD Command Details
GEOHASH Command Details
ZRANGE Command Details

Leave a Comment


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