Deleting Redis keys by a pattern is commonly used when you need to remove multiple keys that share a common naming scheme. Typical examples would be session keys prefixed by user id or cache keys with a common prefix.
Let's assume we have a Redis instance and connection established via Predis client:
Example 1: Delete keys matching a certain pattern:
In this example, we first get all keys matching the pattern 'pattern*' and then delete each key individually.
Example 2: If you want to delete keys across different databases (if your Redis setup has multiple databases), you need to select each database and perform the deletion operation:
keyscommand in a production environment because it can potentially block the server while it's retrieving keys, especially when you have many keys.
del, consider using
unlinkwhich is a non-blocking delete operation in Redis.
keyscommand in production, it's better to use
scanfor large datasets to avoid blocking the server.
Q: Can I delete keys by pattern in one command?
A: Redis does not provide an atomic operation to delete keys by pattern. You need to get all keys by pattern first using
scan, then delete them individually.