Dragonfly Cloud is now available in the AWS Marketplace - learn more

Getting All Keys Matching a Pattern in Redis using Python (Detailed Guide w/ Code Examples)

Use Case(s)

Retrieving keys matching a specific pattern is often useful in various scenarios where you need to manipulate or analyze a group of related data. For example, if your application uses Redis as a cache, you might want to find all keys that match a certain pattern to delete them at once.

Code Examples

To retrieve keys from a Redis database matching a pattern in Python, you can use the scan_iter() function from the redis-py client. This function returns an iterator yielding keys that match the given pattern.

Here's an example:

import redis r = redis.Redis(host='localhost', port=6379, db=0) for key in r.scan_iter('pattern*'): print(key)

In this example, we're connecting to Redis and scanning for keys that start with 'pattern'. Each matching key is printed.

Note: The pattern follows glob-style syntax. You can use '*' to match any number of characters, '?' to match a single character, and '[]' to match any character within the brackets.

Best Practices

  1. Be cautious when using KEYS command (or its equivalent methods in clients) especially in production environments because this command can negatively affect performance if it returns a large number of keys. It's generally better to use scan-based commands like scan_iter.

  2. Always close the redis connection when it's no longer needed.

Common Mistakes

  • Avoid using the KEYS command to fetch keys on large databases as it may block the server until it's completed.

FAQs

Q: Can I use wildcard characters in search patterns?

A: Yes, you can. '*' matches any number of characters, '?' matches exactly one character, and '[]' matches a character set.

Was this content helpful?

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