Dragonfly

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

Use Case(s)

The ZRANGE command in Redis is used to retrieve a range of members from a sorted set stored at a specified key, with scores ordered from lowest to highest. Common use cases include:

Code Examples

Example 1: Basic Usage of ZRANGE

This example demonstrates how to use ZRANGE to get members from a sorted set between two indices.

import redis

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

# Add some members to a sorted set
client.zadd('scores', {'Alice': 50, 'Bob': 70, 'Charlie': 90})

# Get members in the sorted set from index 0 to 1
members = client.zrange('scores', 0, 1)
print(members)  # Output: [b'Alice', b'Bob']

Example 2: Retrieving With Scores

To retrieve members along with their scores, you can use the withscores=True parameter.

members_with_scores = client.zrange('scores', 0, -1, withscores=True)
print(members_with_scores)  # Output: [(b'Alice', 50.0), (b'Bob', 70.0), (b'Charlie', 90.0)]

Best Practices

Common Mistakes

FAQs

Q: Can I use ZRANGE to get members based on score range?
A: No, ZRANGE is used for indexed ranges. To get members based on score ranges, use ZRANGEBYSCORE.

Q: Is it possible to limit the number of returned items in ZRANGE?
A: Directly limiting via ZRANGE isn't possible; however, you can specify start and stop indices to control the range. For more complex querying like pagination with limits, use ZSCAN or script a Lua solution.

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