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:
const redis = require('redis'); const client = redis.createClient(); let cursor = '0'; do { client.scan(cursor, 'MATCH', 'yourpattern*', 'COUNT', '100', function(err, reply) { if (err) throw err; cursor = reply[0]; reply[1].forEach(function(key) { client.del(key, function(err, reply) { console.log('Key deleted:', key); }); }); }); } while (cursor !== '0');
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.
Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.