9.Redis 的特殊数据类型之一:geopatial
redis 的 Geo 在 Redis3.2 版本就推出了!这个功能可以推算地理位置的信息,两地之间的距离,方圆几里的人!
只有六个命令:
geoadd添加地理位置
# geoadd key longitude latitude member
127.0.0.1:6379> geoadd city 116.4 39.9 BeiJing
(integer) 1
127.0.0.1:6379> geoadd city 121.4 31.2 ShangHai
(integer) 1
127.0.0.1:6379>
geopos获得当前定位
获得当前定位,一定是一个坐标值
# geopos key member
127.0.0.1:6379> geopos city BeiJing
1) 1) "116.39999896287918091"
2) "39.90000009167092543"
127.0.0.1:6379> geopos city BeiJing ShangHai
1) 1) "116.39999896287918091"
2) "39.90000009167092543"
2) 1) "121.40000134706497192"
2) "31.20000061483705878"
127.0.0.1:6379>
geodist 两地之间的距离
# geodist key member1 member2 m|km|mi|ft
# 默认单位为m
127.0.0.1:6379> geodist city BeiJing ShangHai
"1067742.3622"
127.0.0.1:6379> geodist city BeiJing ShangHai km
"1067.7424"
127.0.0.1:6379>
georadius 找出半径内的元素
以一个经纬度为中心,redius半径内的所有元素
我附近的人
127.0.0.1:6379> georadius city 110 30 1000 km
(empty array)
127.0.0.1:6379> georadius city 110 30 5000 km
1) "ShangHai"
2) "BeiJing"
127.0.0.1:6379> georadius city 110 30 5000 km withdist
1) 1) "ShangHai"
2) "1099.0298"
2) 1) "BeiJing"
2) "1245.2858"
127.0.0.1:6379> georadius city 110 30 5000 km withcoord
1) 1) "ShangHai"
2) 1) "121.40000134706497192"
2) "31.20000061483705878"
2) 1) "BeiJing"
2) 1) "116.39999896287918091"
2) "39.90000009167092543"
127.0.0.1:6379> georadius city 110 30 5000 km withcoord withdist count 1
1) 1) "ShangHai"
2) "1099.0298"
3) 1) "121.40000134706497192"
2) "31.20000061483705878"
127.0.0.1:6379> georadius city 110 30 5000 km withcoord withdist count 2
1) 1) "ShangHai"
2) "1099.0298"
3) 1) "121.40000134706497192"
2) "31.20000061483705878"
2) 1) "BeiJing"
2) "1245.2858"
3) 1) "116.39999896287918091"
2) "39.90000009167092543"
127.0.0.1:6379>
georadiusbymember
以一个元素为中心,找出对应半径内的元素
127.0.0.1:6379> clear
127.0.0.1:6379> georadiusbymember city ShangHai 5000 km
1) "ShangHai"
2) "BeiJing"
127.0.0.1:6379> georadiusbymember city ShangHai 5000 km withdist
1) 1) "ShangHai"
2) "0.0000"
2) 1) "BeiJing"
2) "1067.7424"
127.0.0.1:6379> georadiusbymember city ShangHai 5000 km withcoord withdist
1) 1) "ShangHai"
2) "0.0000"
3) 1) "121.40000134706497192"
2) "31.20000061483705878"
2) 1) "BeiJing"
2) "1067.7424"
3) 1) "116.39999896287918091"
2) "39.90000009167092543"
127.0.0.1:6379> georadiusbymember city ShangHai 5000 km withcoord withdist count 1
1) 1) "ShangHai"
2) "0.0000"
3) 1) "121.40000134706497192"
2) "31.20000061483705878"
127.0.0.1:6379> georadiusbymember city ShangHai 5000 km withcoord withdist count 2
1) 1) "ShangHai"
2) "0.0000"
3) 1) "121.40000134706497192"
2) "31.20000061483705878"
2) 1) "BeiJing"
2) "1067.7424"
3) 1) "116.39999896287918091"
2) "39.90000009167092543"
127.0.0.1:6379>
geo 的底层是 zset
``geo 的底层是 zset,因此可以用 zset 的命令操作 geo``
127.0.0.1:6379> clear
127.0.0.1:6379> zrange city 0 -1
1) "ShangHai"
2) "BeiJing"
127.0.0.1:6379> zrem city ShangHai
(integer) 1
127.0.0.1:6379> zrange city 0 -1
1) "BeiJing"
127.0.0.1:6379>