Redis ZREMRANGEBYRANK in Python (Detailed Guide w/ Code Examples)

Use Case(s)

The ZREMRANGEBYRANK command in Redis is used to remove all elements in a sorted set stored at key with ranks between start and stop. Common use cases include:

  • Maintaining leaderboards and removing lower ranked entries automatically.
  • Managing time-series data where only top N records are necessary.

Code Examples

Let’s explore how to use ZREMRANGEBYRANK in Python using the redis-py library.

Example 1: Basic Usage of ZREMRANGEBYRANK

import redis # Connect to Redis client = redis.Redis(host='localhost', port=6379, db=0) # Add some members to the sorted set client.zadd('scores', {'Alice': 100, 'Bob': 200, 'Charlie': 300}) # Remove members by rank (e.g., remove bottom two members) client.zremrangebyrank('scores', 0, 1) # Fetch and print all members to see the changes print(client.zrange('scores', 0, -1, withscores=True))

In this example, we have removed the lowest two scores from the sorted set named "scores". The output will show the remaining members of the sorted set.

Example 2: Dynamic Rank Removal

Suppose you want to always maintain only the top three scores in a dynamic gaming leaderboard scenario:

# Assuming client is already defined and connected as shown above # Function to maintain top N scores in the leaderboard def maintain_top_n_scores(key, max_count): current_count = client.zcard(key) if current_count > max_count: client.zremrangebyrank(key, 0, current_count - max_count - 1) # Add new score client.zadd('scores', {'Dave': 250}) # Maintain only top 3 scores maintain_top_n_scores('scores', 3) # Print updated scores print(client.zrange('scores', 0, -1, withscores=True))

This function checks the total count of scores and removes the lowest scores keeping only the top three on the list.

Best Practices

  • Ensure proper handling of indices as they are zero-based.
  • Validate the number of elements in the sorted set before attempting to remove elements to avoid unnecessary operations.

Common Mistakes

  • Not checking if the sorted set exists or if it has enough members before attempting to remove elements by rank, which can lead to unexpected results.


Q: What happens if the specified rank range is out of the existing range? A: If the range specified does not intersect with the actual ranks of elements within the sorted set, no elements are removed, and the operation is a no-op.

Q: Is ZREMRANGEBYRANK an atomic operation? A: Yes, like most Redis operations, ZREMRANGEBYRANK is atomic, meaning once it starts executing, it will not be interrupted by other Redis commands.

Was this content helpful?

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.