Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redis: how to delete multiple keys matching pattern?

Tags:

redis

I need to remove 10 000 keys.

  1. What is better way: to exec this kind of script

    EVAL "return redis.call('del', unpack(redis.call('keys', ARGV[1])))" 0 "ROOT"

  2. May be better is to set expiration time and Redis will remove them? But how to do it in console using Lua script?

The script (see above) works because del comman dhas a format:

del key1 key2 ...

But Expire works only for 1 key.

Is it possible to do it in lua script?

For example: my application creates some search results cache and set for every page ttl = 3600. But user wants to clear cache immediately, i.e. delete all matching keys or set smaller expiration for them.

like image 733
ZedZip Avatar asked Jun 24 '15 14:06

ZedZip


People also ask

How do I delete multiple keys in Redis?

We can use keys command like below to delete all the keys which match the given patters “ user*" from the Redis. Note :- Not recommended on production Redis instance. I have written Lua script to delete multiple keys by pattern . Script uses the scan command to delete the Redis cache key in incremental iteration.

How do I delete a key in Redis?

Deleting Keys Deleting a key in Redis is as simple as creating one. We use the DEL command followed by the name of the key we wish to remove. Redis will drop the key and its associated data if the specified key exists in the data store. You can also use the DEL command to remove multiple keys in a single instance.

Is Redis del blocking?

In Redis 4.0, there is a new command UNLINK to delete the keys in Redis memory. This command is very similar to DEL: it removes the specified keys. Just like DEL a key is ignored if it does not exist. However the command performs the actual memory reclaiming in a different thread, so it is not blocking, while DEL is.


1 Answers

You can either use (from redis cli) to delete all keys:

flushall

or run this from your command line (bash)

redis-cli --scan --pattern aihello_user* | xargs redis-cli del 
like image 79
Ganesh Krishnan Avatar answered Nov 21 '22 15:11

Ganesh Krishnan