Dragonfly

Delete Redis Keys by Prefix in Python (Detailed Guide w/ Code Examples)

Use Case(s)

Deleting keys by prefix in Redis is a common task when working with cache invalidation or data synchronization scenarios. It can be used to remove all keys that match a certain pattern, for example, delete all keys that start with 'user_profile' when user's profile information changes.

Code Examples

Let's assume we're using the redis-py client for Python.

import redis

r = redis.Redis(host='localhost', port=6379, db=0)

for key in r.scan_iter('user_profile*'):
    r.delete(key)

In this example, scan_iter is used to iteratively find keys that match the 'user_profile*' pattern. For each such key, we call delete method to remove it from Redis.

Best Practices

Common Mistakes

FAQs

Q: Can I undo a delete operation in Redis?

A: No, once a key is deleted, it cannot be recovered. Make sure to use the delete operation cautiously.

Q: What's the difference between keys and scan_iter commands?

A: The keys command retrieves all keys in the database at once and can block the server if the database is large. On the other hand, scan_iter uses a cursor to iteratively scan through the database, which is more efficient and recommended.

Was this content helpful?

Help us improve by giving us your feedback.

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.

System Design on AWS

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