当元素被添加到集合中时候,一个元素到score的映射被添加到hash table中,所以给定一个元素获取score的开销是o(1).另一个socre到元素的映射被添加到skip list,并按照score排序,所以就可以有序的获取集合中的元素.添加,删除操作开销都是o(log(N))和skip list的开销一致,redis的skip list实现用的是双向链表,这样就可以逆序从尾部取数据.
sorted set最常用的使用方式应该是作为索引来使用,我么可以把要排序的字段作为score存储,对象的id做元素存储,下面对sorted set相关命令介绍.
127.0.0.1:6379> zadd myzset 1 id1 (integer) 1 127.0.0.1:6379> zadd myzset 2 id2 (integer) 1 127.0.0.1:6379> zadd myzset 3 id3 (integer) 1 127.0.0.1:6379> zrange myzset 0 -1 withscores 1) "id1" 2) "1" 3) "id2" 4) "2" 5) "id3" 6) "3"
zadd添加可以为myzset,member为id1,id2,id3,对应score分别为1,2,3的元素
如果一个member设置两次,那么以最后一次为准
zrange查看key为myzset中存在的元素,如果加上withscores,那么会显示members和score
127.0.0.1:6379> zrange myzset 0 -1 withscores 1) "id1" 2) "1" 3) "id2" 4) "2" 5) "id3" 6) "3" 127.0.0.1:6379> zrem myzset id2 (integer) 1 127.0.0.1:6379> zrange myzset 0 -1 withscores 1) "id1" 2) "1" 3) "id3" 4) "3"
可以看到key为myzset的member为id2的这条记录删除了
127.0.0.1:6379> zrange myzset 0 -1 withscores 1) "id1" 2) "1" 3) "id3" 4) "3" 127.0.0.1:6379> zincrby myzset 2 id1 "3" 127.0.0.1:6379> zincrby myzset 2 id4 "2" 127.0.0.1:6379> zrange myzset 0 -1 withscores 1) "id4" 2) "2" 3) "id1" 4) "3" 5) "id3" 6) "3"
可以看到id4是新增的,id1的score增加了2变为3
127.0.0.1:6379> zrank myzset id1 (integer) 1 127.0.0.1:6379> zrank myzset id3 (integer) 2 127.0.0.1:6379> zrank myzset id4 (integer) 0
下标从0开始的,一次id4最小排在最前面.
127.0.0.1:6379> zrevrank myzset id4 (integer) 2 127.0.0.1:6379> zrevrank myzset id3 (integer) 0 127.0.0.1:6379> zrevrank myzset id1 (integer) 1
127.0.0.1:6379> zrevrange myzset 0 -1 withscores 1) "id3" 2) "3" 3) "id1" 4) "3" 5) "id4" 6) "2" 127.0.0.1:6379> zrevrange myzset 0 1 withscores 1) "id3" 2) "3" 3) "id1" 4) "3"
首先按 score 从大到小排序,再取出全部元素
127.0.0.1:6379> zrangebyscore myzset 2 3 withscores 1) "id4" 2) "2" 3) "id1" 4) "3" 5) "id3" 6) "3" 127.0.0.1:6379> zrangebyscore myzset 3 3 withscores 1) "id1" 2) "3" 3) "id3" 4) "3"
127.0.0.1:6379> zcount myzset 3 3 (integer) 2 127.0.0.1:6379> zcount myzset 2 3 (integer) 3
值为3的有2个,值在2-3的有3个
127.0.0.1:6379> zcard myzset (integer) 3
可以发现key为myzset的集合有3个元素
127.0.0.1:6379> zrange myzset 0 -1 withscores 1) "id4" 2) "2" 3) "id1" 4) "3" 5) "id3" 6) "3" 127.0.0.1:6379> zscore myzset id1 "3"
127.0.0.1:6379> zrange myzset 0 -1 withscores 1) "id4" 2) "2" 3) "id1" 4) "3" 5) "id3" 6) "3" 127.0.0.1:6379> zremrangebyrank myzset 2 2 (integer) 1 127.0.0.1:6379> zrange myzset 0 -1 withscores 1) "id4" 2) "2" 3) "id1" 4) "3"
可以看到排名区间第二到第二的是id3,因此把id3删除掉了
127.0.0.1:6379> zrange myzset 0 -1 withscores 1) "id4" 2) "2" 3) "id1" 4) "3" 127.0.0.1:6379> zremrangebyscore myzset 1 2 (integer) 1 127.0.0.1:6379> zrange myzset 0 -1 withscores 1) "id1" 2) "3"
可以看到score从1-2的只有id4,因此id4被删除了