zset类型详解

zset类型详解

zset 有序数组 zset中每个数据都对应一个score值,用来排序

添加和获取数据

127.0.0.1:6379[3]> flushdb
OK
127.0.0.1:6379[3]> zadd myzset 1 one # 在第一个位置添加one
(integer) 1
127.0.0.1:6379[3]> zadd myzset 2 two 2 three
(integer) 2
127.0.0.1:6379[3]> zrange myzset 0 -1
1) "one"
2) "three"
3) "two"
127.0.0.1:6379[3]> zadd myzset 3 five 4 fore
(integer) 2
127.0.0.1:6379[3]> zrange myzset 0 -1
1) "one"
2) "three"
3) "two"
4) "five"
5) "fore"
127.0.0.1:6379[3]> zadd myzset 0 zero
(integer) 1
127.0.0.1:6379[3]> zrange myzset 0 -1
1) "zero"
2) "one"
3) "three"
4) "two"
5) "five"
6) "fore"
127.0.0.1:6379[3]> zrange myzset 0 -1 withscores
 1) "zero"
 2) "0"
 3) "one"
 4) "1"
 5) "three"
 6) "2"
 7) "two"
 8) "2"
 9) "five"
10) "3"
11) "fore"
12) "4"

排序

# zrangebyscore 选取一定score范围内的数据排序
127.0.0.1:6379[3]> zrangebyscore myzset -inf inf # 显示所有值并显示score
1) "zero"
2) "one"
3) "three"
4) "two"
5) "five"
6) "fore"
127.0.0.1:6379[3]> zrangebyscore myzset inf -inf
(empty list or set)
127.0.0.1:6379[3]> zrangebyscore myzset -inf inf withscores # 显示所有值并显示score
 1) "zero"
 2) "0"
 3) "one"
 4) "1"
 5) "three"
 6) "2"
 7) "two"
 8) "2"
 9) "five"
10) "3"
11) "fore"
12) "4"
127.0.0.1:6379[3]> zrangebyscore myzset -inf 3 withscores # 显示所有score在-inf到3的值并显示score
 1) "zero"
 2) "0"
 3) "one"
 4) "1"
 5) "three"
 6) "2"
 7) "two"
 8) "2"
 9) "five"
10) "3"
127.0.0.1:6379[3]> zrange salary 0 -1 # 从小到大排
1) "xiaohong"
2) "ohmydream"
127.0.0.1:6379[3]> zrevrange salary 0 -1 # 从大到小排
1) "ohmydream"
2) "xiaohong"

zrangezrangebyscore的区别

# zrange 传入的范围是索引值,因此1 2 指的是第二个数和第三个数;
# zrangebyscore 传入的范围是score范围,因此score在这个范围内的值都会被筛选出来
127.0.0.1:6379[3]> zadd myset 1 one
(integer) 1
127.0.0.1:6379[3]> zadd myset 2 two
(integer) 1
127.0.0.1:6379[3]> zadd myset 2 three
(integer) 1
127.0.0.1:6379[3]> zadd myset 1.1 onepointone
(integer) 1
127.0.0.1:6379[3]> zrange myset 1 2
1) "onepointone"
2) "three"
127.0.0.1:6379[3]> zrange myset 0 -1
1) "one"
2) "onepointone"
3) "three"
4) "two"
127.0.0.1:6379[3]> zrangebyscore myset 1 2
1) "one"
2) "onepointone"
3) "three"
4) "two"

移除

# zrem
127.0.0.1:6379[3]> zrange salary 0 -1
1) "xiaoming"
2) "xiaohong"
3) "ohmydream"
127.0.0.1:6379[3]> zrem salary xiaoming
(integer) 1
127.0.0.1:6379[3]> zrange salary 0 -1
1) "xiaohong"
2) "ohmydream"

获取有序集合中的个数

# zcard
127.0.0.1:6379[3]> zcard salary
(integer) 2

计数

# zcount 获取score范围内的数据数量
127.0.0.1:6379[3]> zadd salary 500 xiaoming 200 xiaohong 2000 ohmydream
(integer) 3
127.0.0.1:6379[3]> zcount salary 200 201
(integer) 1
127.0.0.1:6379[3]> zcount salary 0 -1
(integer) 0
127.0.0.1:6379[3]> zcount salary 0 1

其余的多查看官网:https://redis.io/commands#sorted-set

案例:

  • set排序 存储班级成绩表 工资表排序!
  • 普通消息1 重要消息2 带权重进行判断!
  • 排行榜应用实现,取TopN测试!
posted @ 2022-02-25 11:17  Oh,mydream!  阅读(600)  评论(0编辑  收藏  举报