有序集合zset:和set很像,都是字符串的集合,都不允许重复的成员出现在一个set中。他们的区别在于有序集合中每一个成员都有一个分数(score)与之关联,redis正是通过分数来对集合里的成员进行从小到大的排序。尽管有序集合中的成员必须是惟一的,但是分数(score)却可以重复。
应用场景:可以用于一个大型的在线游戏积分排行榜,当玩家的积分发生变化时,可以执行zadd更新玩家分数(score),此后再通过自然可获取top ten的用户信息。
- 添加元素(包括评分和值,排序是按评分从小到大)
127.0.0.1:6379> zadd zset1 5 a 4 b 6 c
(integer) 3
127.0.0.1:6379> zrange zset1 0 -1
1) "b"
2) "a"
3) "c"
- 删除元素
127.0.0.1:6379> zrem zset1 b
(integer) 1
127.0.0.1:6379> zrange zset1 0 -1
1) "a"
2) "c"
- zcard查看集合里元素个数
127.0.0.1:6379> zcard zset1
(integer) 2
- zrange是查找元素 -1代表最后一个元素
(1) withscores 把评分也显示出来
127.0.0.1:6379> zrange zset1 0 -1 withscores
1) "a"
2) "5"
3) "c"
4) "6"
(2) zrevrange降序排列
127.0.0.1:6379> zadd zsort1 11 f 28 g 18 h 35 p
(integer) 4
127.0.0.1:6379> zrevrange zset1 0 -1 withscores
1) "p"
2) "35"
3) "g"
4) "28"
5) "h"
6) "18"
7) "f"
8) "11"
9) "e"
10) "10"
(3)zrangebyscore 根据评分范围来查找元素
127.0.0.1:6379> zremrangebyscore zsort1 10 20
(integer) 3
127.0.0.1:6379> zrange zset1 0 -1 withscores
1) "g"
2) "28"
3) "p"
4) "35"
(4)limit 限定查找起始 类似分页
127.0.0.1:6379> zrange zset1 0 -1 withscores
1) "z"
2) "13"
3) "g"
4) "28"
5) "p"
6) "35"
7) "n"
8) "39"
9) "h"
10) "58"
11) "r"
12) "66"
127.0.0.1:6379> zrangebyscore zset1 10 30 withscores limit 0 2
1) "z"
2) "13"
3) "g"
4) "28"
127.0.0.1:6379> zrangebyscore zset1 10 15 withscores limit 0 2
1) "z"
2) "13"
- 修改已有元素的评分
127.0.0.1:6379> zadd zset1 7 b
(integer) 0
- 获取b的评分
127.0.0.1:6379> zscore zset1 b
"7"
(1)zremrangebyrank 根据排名来删除元素 删除3个
127.0.0.1:6379> zrange zset1 0 -1
1) "a"
2) "f"
3) "c"
4) "e"
127.0.0.1:6379> zremrangebyrank zset1 0 2
(integer) 3
127.0.0.1:6379> zrange zset1 0 -1
1) "e"
(2)zremrangebyscore 根据具体评分范围来删除元素
127.0.0.1:6379> zrevrange zset1 0 -1 withscores
1) "p"
2) "35"
3) "g"
4) "28"
5) "h"
6) "18"
7) "f"
8) "11"
9) "e"
10) "10"
127.0.0.1:6379> zremrangebyscore zset1 10 20
(integer) 3
127.0.0.1:6379> zrange zset1 0 -1 withscores
1) "g"
2) "28"
3) "p"
4) "35"
- zincrby 给指定元素加分
127.0.0.1:6379> zrange zset1 0 -1 withscores
1) "z"
2) "13"
3) "g"
4) "28"
5) "p"
6) "35"
7) "n"
8) "39"
9) "h"
10) "58"
11) "r"
12) "66"
127.0.0.1:6379> zincrby zset1 10 z
"23"
- zcount 查找指定评分范围的元素个数
127.0.0.1:6379> zrange zset1 0 -1 withscores
1) "z"
2) "23"
3) "g"
4) "28"
5) "p"
6) "35"
7) "n"
8) "39"
9) "h"
10) "58"
11) "r"
12) "66"
127.0.0.1:6379> zcount zset1 20 30
(integer) 2