Master Redis 5: Using ZPOPMAX, ZPOPMIN, BZPOPMAX and BZPOPMIN
Redis 5 introduces four new sorted‑set commands—ZPOPMAX, ZPOPMIN, BZPOPMAX, and BZPOPMIN—allowing you to pop elements with the highest or lowest scores, optionally in a blocking fashion, with examples demonstrating their syntax, behavior, and usage patterns.
Redis 5 has been released, adding four new sorted‑set commands:
ZPOPMAX
ZPOPMIN
BZPOPMAX
BZPOPMIN
Below are the purpose and usage of each command.
ZPOPMAX
Command: ZPOPMAX key [count] Effect:
Removes and returns the count elements with the highest scores from the specified sorted set. If count is omitted, the default is 1. When count > 1, the returned elements are ordered by score, highest first.
Example:
# Add elements
redis> ZADD myzset 1 "one"
(integer) 1
redis> ZADD myzset 2 "two"
(integer) 1
redis> ZADD myzset 3 "three"
(integer) 1
# View set with scores
redis> ZRANGE myzset 0 -1 WITHSCORES
1) "one"
2) "two"
3) "three"
# Pop two highest‑score elements
redis> ZPOPMAX myzset 2
1) "three"
2) "two"ZPOPMIN
Command: ZPOPMIN key [count] Effect:
Same as ZPOPMAX but returns the elements with the lowest scores.
BZPOPMAX
Command: BZPOPMAX key [key ...] timeout Effect:
BZPOPMAX is the blocking version of ZPOPMAX; it behaves like ZPOPMAX but blocks when the target set is empty, waiting up to timeout seconds (0 means block indefinitely).
Example:
In window 1:
# Add elements to a set
redis> ZADD myzset2 1 "one" 2 "two"
(integer) 2
# View set with scores
redis> ZRANGE myzset2 0 -1 WITHSCORES
1) "one"
2) "two"
# Pop the highest‑score element, leaving one element
redis> BZPOPMAX myzset2 0
1) "two"In window 2, add another element:
redis> ZADD myzset2 3 "tree"
(integer) 1View window 1:
redis> BZPOPMAX myzset2 0
1) "tree"BZPOPMIN
Command: BZPOPMIN key [key ...] timeout Effect:
Same as BZPOPMAX but returns the element with the lowest score.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
