Redis ZREMRANGEBYRANK命令

Redis ZREMRANGEBYRANK命令教程

Redis 的 ZREMRANGEBYRANK 命令用于移除 有序集 KEY 中,指定排名(rank)区间内的所有成员。区间分别以下标参数 start 和 stop 指出,包含 start 和 stop 在内。

下标参数 start 和 stop 都以 0 为底,也就是说,以 0 表示有序集第一个成员,以 1 表示有序集第二个成员,以此类推。

也可以使用负数下标,以 -1 表示最后一个成员, -2 表示倒数第二个成员,以此类推。

Redis ZREMRANGEBYRANK命令详解

语法

192.168.98.70:6379> ZREMRANGEBYRANK KEY start stop

参数

参数 描述
KEY 有序集合的键。
start 要移除成员的开始区间。
stop 要移除成员的结束区间

返回值

被移除成员的数量。

时间复杂度

O(log(N)+M), N 为有序集的基数,而 M 为被移除成员的数量。

可用版本

>= 2.0.0

案例

元素存在

元素存在,移除成功

192.168.98.70:6379> ZADD haicoder 100 Redis 50 Mongo 200 Mysql 10 SqlServer (integer) 4 192.168.98.70:6379> ZRANGE haicoder 0 -1 1) "SqlServer" 2) "Mongo" 3) "Redis" 4) "Mysql" 192.168.98.70:6379> ZREMRANGEBYRANK haicoder 0 1 (integer) 2 192.168.98.70:6379> ZRANGE haicoder 0 -1 1) "Redis" 2) "Mysql" 192.168.98.70:6379> DEL haicoder (integer) 1

我们首先,使用 ZADD 命令,向键为 haicoder 的集合中批量插入元素。接着,我们使用 ZREMRANGEBYRANK 命令,删除集合 haicoder 中的索引 0 到 1 的元素。

最后,我们使用 ZRANGE 命令,获取集合中的所有数据,元素 SqlServer 和元素 Mongo 已被删除。

负数索引

负数索引,表示从列表尾开始获取元素

192.168.98.70:6379> ZADD haicoder 100 Redis 50 Mongo 200 Mysql 10 SqlServer (integer) 4 192.168.98.70:6379> ZRANGE haicoder 0 -1 1) "SqlServer" 2) "Mongo" 3) "Redis" 4) "Mysql" 192.168.98.70:6379> ZREMRANGEBYRANK haicoder 0 -2 (integer) 3 192.168.98.70:6379> ZRANGE haicoder 0 -1 1) "Mysql" 192.168.98.70:6379> DEL haicoder (integer) 1

我们首先,使用 ZADD 命令,向键为 haicoder 的集合中批量插入元素。接着,使用 ZREMRANGEBYRANK 命令,删除集合 haicoder 中的索引 0 到 -2 的元素,即删除第一个元素到倒数第二个元素。

最后,我们使用 ZRANGE 命令,获取集合中的所有数据,此时只剩下原集合中的最后一个元素。

索引越界

stop 索引越界,自动被截取为集合的最大索引

192.168.98.70:6379> ZADD haicoder 100 Redis 50 Mongo 200 Mysql 10 SqlServer (integer) 4 192.168.98.70:6379> ZRANGE haicoder 0 -1 1) "SqlServer" 2) "Mongo" 3) "Redis" 4) "Mysql" 192.168.98.70:6379> ZREMRANGEBYRANK haicoder 1 100 (integer) 3 192.168.98.70:6379> ZRANGE haicoder 0 -1 1) "SqlServer" 192.168.98.70:6379> DEL haicoder (integer) 1

我们首先,使用 ZADD 命令,向键为 haicoder 的集合中批量插入元素。

接着,我们使用 ZREMRANGEBYRANK 命令,删除集合 haicoder 中的索引 1 到 100 的元素,此时索引 100 已超过集合的最大索引,自动被截取为集合的最大索引。

最后,我们使用 ZRANGE 命令,获取集合中的所有数据,此时只剩下原集合中的第一个元素。

Redis ZREMRANGEBYRANK命令总结

Redis 的 ZREMRANGEBYRANK 命令用于移除有序集 KEY 中,指定排名(rank)区间内的所有成员。Redis ZREMRANGEBYRANK 命令语法:

192.168.98.70:6379> ZREMRANGEBYRANK KEY start stop