5

I am using Redis hash set to store data in the following format:

hset b1.b2.b3 name test

Now I want to delete this key so I am using the following format:

del b1.b2.*

But it not working so how I delete the Redis key using a pattern?

Dan Atkinson
  • 11,391
  • 14
  • 81
  • 114
Suraj Dalvi
  • 988
  • 1
  • 20
  • 34
  • 1
    Does this answer your question? [How to atomically delete keys matching a pattern using Redis](https://stackoverflow.com/questions/4006324/how-to-atomically-delete-keys-matching-a-pattern-using-redis) – Mohammad Yaser Ahmadi Jan 31 '21 at 23:07

3 Answers3

7

Redis does not provide any method to delete bulk keys. But redis-cli along with xargs can be used to achieve what you are trying to do. See the commands below:

127.0.0.1:6379> hset b1.b2.b3 name test
(integer) 1
127.0.0.1:6379> hgetall b1.b2.b3
1) "name"
2) "test"
$ redis-cli --scan --pattern b1.b2.* | xargs redis-cli del
(integer) 1
$ redis-cli
127.0.0.1:6379> hgetall b1.b2.b3
(empty list or set)

We are scanning redis for a pattern using '--scan' and the output is given to redis-cli again using the xargs method whcih combines all the keys in the scan result and finally we delete all of them using 'del' command.

Ankit Sahay
  • 1,710
  • 8
  • 14
  • 1
    how we can implement this using Redis node js module. – Suraj Dalvi Feb 01 '21 at 08:14
  • Please accept the answer or edit your question. It doesn’t say you have to implement this in nodejs – Ankit Sahay Feb 01 '21 at 08:16
  • As an addendum to this, I would recommend using [`unlink`](https://redis.io/commands/unlink/) instead of [`del`](https://redis.io/commands/del/). The key difference is that an `unlink` command is non-blocking. – Dan Atkinson Feb 23 '23 at 13:32
1

If you'd like to do this via the redis-cli in bulk, you could consider expiring all the keys based on a specified pattern:

EVAL 'for i, name in ipairs(redis.call("KEYS", <pattern>)) do redis.call("EXPIRE", name, 1); end' 0

Effectively it sets the expiration to 1 second so this should do the trick!

originalhat
  • 1,676
  • 16
  • 18
  • Works great! Should be a built-in command, glarily missing for some reason... they got every other damn thing in that api, tho! – RealityExpander Aug 24 '23 at 02:54
-2

You can do it using the pattern above @Ankit answered.

you can do a SCAN and then delete the keys until nothing left (cursor is 0)

https://redis.io/commands/scan

Tuan Anh Tran
  • 6,807
  • 6
  • 37
  • 54