Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to atomically delete keys matching a pattern using Redis

Tags:

redis

In my Redis DB I have a number of prefix:<numeric_id> hashes.

Sometimes I want to purge them all atomically. How do I do this without using some distributed locking mechanism?

like image 358
Alexander Gladysh Avatar asked Oct 23 '10 22:10

Alexander Gladysh


People also ask

How do I delete all keys matching a pattern in Redis?

Redis does not offer a way to bulk delete keys. You can however use redis-cli and a little bit of command line magic to bulk delete keys without blocking redis. This command will delete all keys matching users:* If you are in redis 4.0 or above, you can use the unlink command instead to delete keys in the background.

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.

Does Redis delete keys?

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.

Which command is used to delete the key in Redis?

Redis - Keys Del Command Redis DEL command is used to delete the existing key in Redis.


1 Answers

Execute in bash:

redis-cli KEYS "prefix:*" | xargs redis-cli DEL 

UPDATE

Ok, i understood. What about this way: store current additional incremental prefix and add it to all your keys. For example:

You have values like this:

prefix_prefix_actuall = 2 prefix:2:1 = 4 prefix:2:2 = 10 

When you need to purge data, you change prefix_actuall first (for example set prefix_prefix_actuall = 3), so your application will write new data to keys prefix:3:1 and prefix:3:2. Then you can safely take old values from prefix:2:1 and prefix:2:2 and purge old keys.

like image 173
3 revs, 2 users 94% Avatar answered Sep 27 '22 19:09

3 revs, 2 users 94%