五大数据类型及应用场景
类型 | 特点 | 使用场景 |
---|---|---|
string | 简单key-value类型,value可为字符串和数字 | 常规计数(微博数, 粉丝数等功能) |
hash | 是一个string类型的field和value的映射表,hash特别适合用于存储对象 | 存储部分可能需要变更的数据(比如用户信息) |
list | 有序可重复列表 | 关注列表,粉丝列表,消息队列等 |
set | 无序不可重复列表 | 存储并计算关系(如微博,关注人或粉丝存放在集合,可通过交集、并集、差集等操作实现如共同关注、共同喜好等功能) |
sorted set | 每个元素带有分值的集合 | 各种排行榜 |
有序集合sortedset
有序集合的交集与并集
# 交集(weights代表权重值,aggregate代表聚合方式 - 先计算权重值,然后再聚合)
ZINTERSTORE destination numkeys key1 key2 WEIGHTS weight AGGREGATE SUM|MIN|MAX
# 并集(weights代表权重值,aggregate代表聚合方式 - 先计算权重值,然后再聚合)
ZUNIONSTORE destination numkeys key [weights 权重值] [AGGREGATE SUM|MIN|MAX]
案例1:网易音乐排行榜
1、每首歌的歌名作为元素
2、每首歌的播放次数作为分值
3、使用ZREVRANGE来获取播放次数最多的歌曲
代码实现
import redis
r = redis.Redis(host='127.0.0.1',port=6379,db=0)
# 有序集合中添加了8首歌曲
r.zadd('ranking',{
'song1':1,'song2':1,'song3':1,'song4':1})
r.zadd('ranking',{
'song5':1,'song6':1,'song7':1,'song8':1})
# 指定成员增加分值
r.zincrby('ranking',50,'song3')
r.zincrby('ranking',60,'song4')
r.zincrby('ranking',70,'song8')
# 获取前3名: [('song8',71),(),()]
rlist = r.zrevrange('ranking',0,2,withscores=True)
i = 1
for name in rlist:
print('第{}名:{} 播放次数:{}'.format(
i,
name[0].decode(),
int(name[1])
))
i += 1
# 第1名:song8 播放次数:71
# 第2名:song4 播放次数:61
# 第3名:song3 播放次数:51
案例2: 京东商品畅销榜
# 第1天
ZADD mobile-001 5000 'huawei' 4000 'oppo' 3000 'iphone'
# 第2天
ZADD mobile-002 5200 'huawei' 4300 'oppo' 3230 'iphone'
# 第3天
ZADD mobile-003 5500 'huawei' 4660 'oppo' 3580 'iphone'
问题:如何获取三款手机的销量排名?
ZUNIONSTORE mobile-001:003 mobile-001 mobile-002 3 mobile-003 # 可否?
# 正确
方法1: ZRANGE mobile-003 0 -1 WITHSCORES
方法2: ZUNIONSTORE mobile-001:003 3 mobile-001 mobile-002 mobile-003 AGGREGATE MAX
python代码实现
import redis
r = redis.Redis(host='127.0.0.1',port=6379,db=0)
day01_dict = {
'huawei':5000,
'oppo':4000,
'iphone':3000
}
day02_dict = {
'huawei':5200,
'oppo':4300,
'iphone':3230
}
day03_dict = {
'huawei':5500,
<