有序集合(Sorted sets): 类似于集合,但每个字符串元素都与一个称为score的浮点数值相关联。元素总是按分数排序,因此与集合不同,可以检索一系列元素(例如,您可能会问:给出前10个或后10个)。
1、命令
添加、查询
127.0.0.1:6379> flushdb # 清除当前数据库
OK
127.0.0.1:6379> zadd myset 2 oldfe # 向集合添加一个元素
(integer) 1
127.0.0.1:6379> zadd myset 3 age
(integer) 1
127.0.0.1:6379> zadd myset 0 hello
(integer) 1
127.0.0.1:6379> zrange myset 0 -1 # 获取所有的元素
1) "hello"
2) "oldfe"
3) "age"
排序的实现!!!
这里创建一个有序集合score,我们把存储时设置的下标看作是分数,分数对应的是用户,存储的形式相当于分数-用户
使用命令zrangebyscore
进行排序,就是清晰看到用户的排名。
127.0.0.1:6379> flushdb
OK
127.0.0.1:6379> clear
# 语法:ZADD key [NX|XX] [GT|LT] [CH] [INCR] score member [score member ...]
127.0.0.1:6379> zadd score 60 zhangsan # 添加一个 分数 和 用户
(integer) 1
127.0.0.1:6379> zadd score 36 zhangsan
(integer) 0
127.0.0.1:6379> zadd score 36 lisi
(integer) 1
127.0.0.1:6379> zadd score 86 wangwu
(integer) 1
127.0.0.1:6379> zadd score 99 oldfe
(integer) 1
# 语法:ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count]
127.0.0.1:6379> zrangebyscore score -inf +inf # 通过分数进行升序排序,-inf 表示负无穷, +inf 表示正无穷
1) "lisi"
2) "zhangsan"
3) "wangwu"
4) "oldfe"
127.0.0.1:6379> zrangebyscore score -inf +inf withscores # 加上条件withscores 会带上分数显示
1) "lisi"
2) "36"
3) "zhangsan"
4) "36"
5) "wangwu"
6) "86"
7) "oldfe"
8) "99"
# 语法:ZREVRANGEBYSCORE key max min [WITHSCORES] [LIMIT offset count]
127.0.0.1:6379> zrevrangebyscore score +inf -inf # 通过分数进行降序排序
1) "oldfe"
2) "wangwu"
3) "zhangsan"
4) "lisi"
# 语法:ZREVRANGE key start stop [WITHSCORES]
127.0.0.1:6379> zrevrange score 0 -1
1) "oldfe"
2) "wangwu"
3) "zhangsan"
4) "lisi"
127.0.0.1:6379> zrangebyscore score 60 100 withscores # 获取指定区间[60,100]内的用户和分数
1) "wangwu"
2) "86"
3) "oldfe"
4) "99"
127.0.0.1:6379> zrangebyscore score (36 100 # 获取指定区间(60,100]内的用户和分数
1) "wangwu"
2) "oldfe"
127.0.0.1:6379> zrangebyscore score -inf 60 # 获取负无穷的60的用户,相当于获取用户小于分数60的升序排序
1) "lisi"
2) "zhangsan"
移除
127.0.0.1:6379> zrange score 0 -1
1) "lisi"
2) "zhangsan"
3) "wangwu"
4) "oldfe"
# 语法 ZREM key member [member ...]
127.0.0.1:6379> zrem score lisi wangwu # 移除集合中一个或多个指定的元素
(integer) 2
127.0.0.1:6379> zrange score 0 -1
1) "zhangsan"
2) "oldfe"
# 语法:ZCARD key
127.0.0.1:6379> zcard score # 获取元素个数
(integer) 2
统计区间个数
127.0.0.1:6379> flushdb
OK
127.0.0.1:6379> zadd myset 1 one 3 three 4 four 6 six # 同时set 多个值
(integer) 4
127.0.0.1:6379> zcount myset 2 5 # 统计区间内的个数
(integer) 2
2、总结!
Zset 就是加了排序的Set,可以存储班级成绩表、员工工资表等等进行排序!
可以实现排行榜的应用。
图片来自redis中文网: