The easiest way to delete keys from a template is to use the keys
command to get the keys matching the template and then delete them one at a time, which is similar to the command line example you provided. Here is an example implemented with ioredis:
var Redis = require('ioredis'); var redis = new Redis(); redis.keys('sample_pattern:*').then(function (keys) {
However, when your database has a large set of keys (say, a million), keys
will lock the database for several seconds. In this case, scan
more useful. ioredis has a scanStream
function that helps you easily sort through a database:
var Redis = require('ioredis'); var redis = new Redis(); // Create a readable stream (object mode) var stream = redis.scanStream({ match: 'sample_pattern:*' }); stream.on('data', function (keys) { // `keys` is an array of strings representing key names if (keys.length) { var pipeline = redis.pipeline(); keys.forEach(function (key) { pipeline.del(key); }); pipeline.exec(); } }); stream.on('end', function () { console.log('done'); });
Be sure to check out the official documentation for the scan
command for more information: http://redis.io/commands/scan .
source share