(10-7)redis -Sorted set 数据类型
启动redis:
[root@baozi ~]# redis-server /etc/redis.conf
[root@baozi ~]# redis-cli
127.0.0.1:6379>
redis数据类型--sorted set
1、有序集合,在集合类型的基础上为集合中的每一个元素都关联了一个分数,这样可以很方便的获取分数最高的N个元素(topN);
常用命令:
1、zadd/zscore/zrange/zrevrange
2、zrangebyscore
3、zincrby/zcard/zcount
4、zrem/zremrangebyrank/zremrangebyscore
扩展: +inf(正无穷) -inf(负无穷)
//增加元素
127.0.0.1:6379> zadd sset1 10 a
(integer) 1
127.0.0.1:6379> zadd sset1 20 b
(integer) 1
127.0.0.1:6379> zadd sset1 5 c
(integer) 1
//遍历元素
127.0.0.1:6379> zrange sset1 0 -1
1) "c"
2) "a"
3) "b"
//遍历元素附带分值
127.0.0.1:6379> zrange sset1 0 -1 withscores
1) "c"
2) "5"
3) "a"
4) "10"
5) "b"
6) "20"
127.0.0.1:6379>
//查看某个元素的分值
127.0.0.1:6379> zscore sset1 a
"10"
//倒叙遍历所有元素
127.0.0.1:6379> zrevrange sset1 0 -1
1) "b"
2) "a"
3) "c"
//倒叙遍历所有元素,附带分值
127.0.0.1:6379> zrevrange sset1 0 -1 withscores
1) "b"
2) "20"
3) "a"
4) "10"
5) "c"
6) "5"
127.0.0.1:6379>
//显示指定分数段的元素,左闭右闭
127.0.0.1:6379> zrangebyscore sset1 10 20
1) "a"
2) "b"
//左开右闭
127.0.0.1:6379> zrangebyscore sset1 (10 20
1) "b"
//显示指定分数段的元素,左闭右闭,附带分数
127.0.0.1:6379> zrangebyscore sset1 10 20 withscores
1) "a"
2) "10"
3) "b"
4) "20"
//显示指定分数段的元素,左闭右闭,从角标为1开始显示2个
127.0.0.1:6379> zrangebyscore sset1 10 20 limit 1 2
1) "b"
//显示指定分数段的元素,左闭右闭,从角标为0开始显示2个
127.0.0.1:6379> zrangebyscore sset1 10 20 limit 0 2
1) "a"
2) "b"
127.0.0.1:6379>
//增加指定元素的分值
127.0.0.1:6379> zincrby sset1 4 c
"9"
127.0.0.1:6379> zrevrange sset1 0 -1 withscores
1) "b"
2) "20"
3) "a"
4) "10"
5) "c"
6) "9"
//获得集合元素个数
127.0.0.1:6379> zcard sset1
(integer) 3
//获取指定分数段元素的个数
127.0.0.1:6379> zcount sset1 9 20
(integer) 3
127.0.0.1:6379> zcount sset1 (9 20
(integer) 2
127.0.0.1:6379>
//删除指定元素
127.0.0.1:6379> zrem sset1 a
(integer) 1
127.0.0.1:6379> zrange sset1 0 -1 withscores
1) "c"
2) "9"
3) "b"
4) "20"
127.0.0.1:6379>
127.0.0.1:6379> zrange sset1 0 -1 withscores
1) "c"
2) "9"
3) "a"
4) "10"
5) "b"
6) "20"
7) "d"
8) "25"
//删除指定角标范围的元素
127.0.0.1:6379> zremrangebyrank sset1 0 0
(integer) 1
127.0.0.1:6379> zrange sset1 0 -1 withscores
1) "a"
2) "10"
3) "b"
4) "20"
5) "d"
6) "25"
//删除指定分数段的元素
127.0.0.1:6379> zremrangebyscore sset1 5 15
(integer) 1
127.0.0.1:6379> zrange sset1 0 -1 withscores
1) "b"
2) "20"
3) "d"
4) "25"
127.0.0.1:6379>
//正无穷大
127.0.0.1:6379> zadd sset1 +inf x
(integer) 1
127.0.0.1:6379> zrange sset1 0 -1 withscores
1) "b"
2) "20"
3) "d"
4) "25"
5) "x"
6) "inf"
//负无穷大
127.0.0.1:6379> zadd sset1 -inf y
(integer) 1
127.0.0.1:6379> zrange sset1 0 -1 withscores
1) "y"
2) "-inf"
3) "b"
4) "20"
5) "d"
6) "25"
7) "x"
8) "inf"
127.0.0.1:6379>