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
- Be mindful of using the delete operation in production applications, as it may affect performance, especially if the number of keys is large.
- It's recommended to use scan operations (like
scan_iter
) instead of thekeys
command for finding keys by pattern, askeys
can block the server when called on large databases.
Common Mistakes
- A common mistake is to accidentally delete keys without ensuring the correct pattern. Always double-check your key patterns before deleting.
- Using the
keys
method instead ofscan_iter
could lead to performance issues. Thekeys
method retrieves all keys and can be slow in large databases.
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
Free System Design on AWS E-Book
Download this early release of O'Reilly's latest cloud infrastructure e-book: 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