15 Appendix More Ordered Set Operation Commands

15 Appendix More Ordered Set Operation Commands #

Get the total number of elements in a sorted set #

Syntax: zcard key Example:

127.0.0.1:6379> zcard zset1
(integer) 4

Get the number of elements with scores within a given range #

Syntax: zcount key min max Example:

127.0.0.1:6379> zcount zset1 0 10
(integer) 4

Increment the score of an element #

Syntax: zincrby key increment member Example:

127.0.0.1:6379> zscore zset1 redis # Get the score of "redis" in zset1
"1"
127.0.0.1:6379> zincrby zset1 2 redis # Increment the score
"3"
127.0.0.1:6379> zscore zset1 redis
"3"

Get the reverse rank of an element #

Syntax: zrevrank key member Example:

127.0.0.1:6379> zrevrank zset1 python # Get the reverse rank
(integer) 0
127.0.0.1:6379> zrange zset1 0 -1 # Get the regular list
1) "redis"
2) "java"
3) "golang"
4) "python"

Remove elements by rank #

Syntax: zremrangebyrank key start stop Example:

127.0.0.1:6379> zrange zset1 0 -1 # Get all elements
1) "redis"
2) "java"
3) "golang"
4) "python"
127.0.0.1:6379> zremrangebyrank zset1 0 2 # Remove elements
(integer) 3
127.0.0.1:6379> zrange zset1 0 -1 # Get all elements
1) "python"

Remove elements by score range #

Syntax: zremrangebyscore key min max Example:

127.0.0.1:6379> zscore zset1 python
"4"
127.0.0.1:6379> zremrangebyscore zset1 4 5
(integer) 1
127.0.0.1:6379> zscore zset1 python
(nil)

Copy intersecting elements to a new set #

Syntax: zinterstore destination numkeys key [key …] [WEIGHTS weight] [AGGREGATE SUM|MIN|MAX] Parameter numkeys indicates how many sets should be included in the query. Example:

127.0.0.1:6379> zrange zset1 0 -1
1) "redis"
2) "java"
3) "golang"
4) "python"
127.0.0.1:6379> zrange zset2 0 -1
1) "redis"
2) "db"
127.0.0.1:6379> zinterstore zset3 2 zset1 zset2
(integer) 1
127.0.0.1:6379> zrange zset3 0 -1
1) "redis"

Copy union elements to a new set #

Syntax: zunionstore destination numkeys key [key …] [WEIGHTS weight] [AGGREGATE SUM|MIN|MAX] Example:

127.0.0.1:6379> zrange zset1 0 -1
1) "redis"
2) "java"
3) "golang"
4) "python"
127.0.0.1:6379> zrange zset2 0 -1
1) "redis"
2) "db"
127.0.0.1:6379> zunionstore zset3 2 zset1 zset2
(integer) 5
127.0.0.1:6379> zrange zset3 0 -1
1) "java"
2) "golang"
3) "redis"
4) "python"
5) "db"