In a Node.js application backed by Redis, there may be times when you need to delete keys based on a specific pattern. For example, in a caching scenario, you might use key patterns to represent different versions of the same data, and you need to clear out old versions.
To accomplish this, you'll need to use a combination of Redis
SCAN command along with the
DEL command. Here's how it looks:
This script will scan your Redis database for keys that match your pattern (
yourpattern*) and delete them. It does it in a loop until it has scanned all keys.
Q: Can I use this method to delete keys across multiple databases in Redis?
A: No, the
SCAN command only works within the currently selected database.
Q: What if my pattern matches more keys than the count I specified? A: The script will handle this by continuously looping until all matching keys are deleted.