Delete key array in redis with node-redis

I have arrays of keys such as ["aaa", "bbb", "ccc"], so I want to remove all of these keys from redis with a single command. I do not want to repeat the use of the loop. I read about the redis DEL command and it works on the redis-client terminal, but with nodejs it doesn't work.

Redisclient.del(tokenKeys,function(err,count){ Logger.info("count is ",count) Logger.error("err is ",err) }) 

where tokenKeys = ["aaa", "bbb", "ccc"], this code works if I send one key, for example, tokenKeys = "aaa"

+5
source share
4 answers

You can simply pass the array as follows

 var redis = require("redis"), client = redis.createClient(); client.on("error", function (err) { console.log("Error " + err); }); client.set("aaa", "aaa"); client.set("bbb", "bbb"); client.set("ccc", "ccc"); var keys = ["aaa", "bbb", "ccc"]; client.keys("*", function (err, keys) { keys.forEach(function (key, pos) { console.log(key); }); }); client.del(keys, function(err, o) { }); client.keys("*", function (err, keys) { keys.forEach(function (key, pos) { console.log(key); }); }); 

If you run the above code, you will get the following output

 $ node index.js string key hash key aaa ccc bbb string key hash key 

showing keys printed after installation but not printed after removal

+6
source
Function

del is implemented directly, as in the Redis DB client, That is, redis.del("aaa","bbb","ccc") will delete several elements

To make it work with an array, use a JavaScript approach:

 redis.del.apply(redis, ["aaa","bbb","ccc"]) 
+2
source

Of course, in the current version of node_redis (v2.6.5), you can remove both using a list of keys separated by commas, or using an array of keys. See Tests for here .

 var redis = require("redis"); var client = redis.createClient(); client.set('foo', 'foo'); client.set('apple', 'apple'); // Then either client.del('foo', 'apple'); // Or client.del(['foo', 'apple']); 
+2
source

node-redis doesn't work like that, but if you really have many del commands, it automatically pipelines in contact, so it is probably more efficient than you think to do it in a loop.

You can also try this module with several:

 var redis = require("redis"), client = redis.createClient(), multi; client.multi([ ["del", "key1"], ["del", "key2"] ]).exec(function (err, replies) { console.log(replies); }); 
+1
source

Source: https://habr.com/ru/post/1232526/


All Articles