Dragonfly

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

Use Case(s)

The ZREMRANGEBYSCORE command in Redis is used to remove all elements in a sorted set stored at a specific key, within the given scores (inclusive). It's useful for scenarios such as:

Code Examples

Example 1: Removing Transactions Within a Score Range

Suppose you have a sorted set "transactions" where the score represents the transaction timestamp. You want to delete transactions that occurred before a certain timestamp.

import redis

# Connect to Redis
client = redis.Redis(host='localhost', port=6379, db=0)

# Define the min and max scores
min_score = "-inf"  # Negative infinity: start from the lowest possible score
max_score = "1609459199"  # Timestamp up to which transactions are to be removed

# Remove transactions
removed_count = client.zremrangebyscore("transactions", min_score, max_score)
print(f"Removed {removed_count} transactions.")

Example 2: Moderating a Real-Time Leaderboard

In a gaming scenario, remove players' scores from a leaderboard if they fall below a certain threshold, say to only keep top performances.

import redis

# Connect to Redis
client = redis.Redis(host='localhost', port=6379, db=0)

# Threshold score to remove lesser scores
threshold_score = 50

# Remove players with scores below the threshold
removed_count = client.zremrangebyscore("leaderboard", "-inf", threshold_score)
print(f"Removed {removed_count} players from the leaderboard.")

Best Practices

Common Mistakes

FAQs

Q: What happens if there are no elements within the specified score range?
A: The command will successfully execute but will return 0 indicating that no elements were removed.

Q: Is ZREMRANGEBYSCORE atomic?
A: Yes, Redis commands, including ZREMRANGEBYSCORE, are atomic, meaning the operation is performed entirely or not at all without any interference.

Was this content helpful?

Similar Code Examples

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book

Switch & save up to 80% 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost