In Node.js applications using Redis as a cache or session store, you may need to delete all keys in scenarios such as:
flushdb
command:const redis = require('redis'); const client = redis.createClient(); client.flushdb((err, succeeded) => { console.log(succeeded); // will be true if success });
flushdb
is a Redis command that deletes all keys from the current database. This method is handy when you want to clear your entire cache.
keys
and del
commands:const redis = require('redis'); const client = redis.createClient(); client.keys('*', (err, keys) => { if (err) return console.log(err); for(let i = 0; i < keys.length; i++) { client.del(keys[i], function(err, reply) { console.log(reply); }); } });
In this example, we first call the keys
command with the wildcard '*' to fetch all keys in the database. After that, we loop over the keys and delete each one using the del
command.
UNLINK
command, which is a non-blocking alternative to DEL
.flushdb
, del
, or keys
commands.Q: Can I delete keys matching a specific pattern?
A: Yes, in the second code example, replace '' in the keys
method with your pattern. For example, 'session:' will match all keys that start with 'session:'.
Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.