Redis数据库的遍历
以hash数据类型为例:典型的键值对,前期通过hmset()方法进行多数据插入,存入到Redis中的结构类似于
key:{
key1:value1,
key2:value2,
key3:value3
}
使用的是Redis模块中的scan_iter()方法,该方法可以获得Redis库中所有的key值,通过遍历key值可以通过hget得到需要的key*的value值,并且这些value值可以通过筛选条件或者排序条件进行排序或筛选。
注意:得到的value值都是String数据类型,如果要和数值进行比较,需要将Str转换为小数,使用的方式是decimal模块中的Decimal方法,比如:
unixtime = Decimal(unixtime)
if 112.345 < unixtime:
print(unixtime)
这样就可以实现从redis中遍历所有数值并且进行筛选
总结:
-
遍历所有key的方法
for key in r.scan_iter(): lon_d = r.hmget(key,"Lon_d","Lat_d","Speed") print(lon_d)
-
Str类型转换为浮点进行比较
unixtime = Decimal(unixtime) if 112.345 < unixtime: print(unixtime)
-
获取特定时间的时间戳
times = time.mktime(time.strptime("2020-06-15 00:00:00","%Y-%m-%d %H:%M:%S")) print(times)
代码展示:
import redis
r = redis.Redis(host='localhost', port=6379, decode_responses=True,db = 1)
for key in r.scan_iter():
lon_d = r.hmget(key,"Lon_d","Lat_d","Speed")
unixtime = r.hget(key,"UnixTime")
unixtime = Decimal(unixtime)
if 112.345 < unixtime:
print(unixtime)
print(lon_d)