Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete keys with spaces

I am trying to delete multiple keys from my remote Redis db using the following command.

redis-cli -h <host> -p 6379 KEYS "myprefix:*" | xargs redis-cli -h <host> -p 6379 DEL

It has deleted all the matching keys except the ones having spaces in them.

For e.g.

Deleted:

  • myprefix:abc
  • myprefix:def
  • myprefix:ghi

Not deleted:

  • myprefix:jkl mno
  • myprefix:pqr stu
  • myprefix:vwx yza

What should be my query pattern so that these get deleted too? I tried googling but was unable to find any solution.

like image 497
Sagar Gopale Avatar asked Jun 12 '18 11:06

Sagar Gopale


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.

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.

How do I delete all data from Redis?

To clear data of a DCS Redis 4.0 or 5.0 instance, you can run the FLUSHDB or FLUSHALL command in redis-cli, use the data clearing function on the DCS console, or run the FLUSHDB command on Web CLI. To clear data of a Redis Cluster instance, run the FLUSHDB or FLUSHALL command on every shard of the instance.

How do I get all Redis keys?

To list the keys in the Redis data store, use the KEYS command followed by a specific pattern. Redis will search the keys for all the keys matching the specified pattern. In our example, we can use an asterisk (*) to match all the keys in the data store to get all the keys.


2 Answers

The issue is with xargs, not your KEYS query. If you run your query, you will notice that it correctly returns the keys with spaces in them. The problem is that by default xargs splits the strings piped into it by blanks and newlines. To change this behaviour so that it only delimits by newlines, add the -d "\n" option. For example:

redis-cli -h <host> -p 6379 keys "myprefix:*" | xargs -d "\n" redis-cli -h <host> -p 6379 del
like image 71
cbp Avatar answered Sep 24 '22 10:09

cbp


For anyone using Mac OS xargs (BSD) instead of linux (GNU) xargs the following works

redis-cli -h <host> -p 6379 keys "myprefix:*" | xargs -I% redis-cli -h <host> -p 6379 del %

or for other weird characters like speech marks this works

redis-cli -h <host> -p 6379 --scan --pattern "myprefix:*" | tr '\n' '\0' | xargs -0 -I% redis-cli -h <host> -p 6379 del %

like image 39
uosjead Avatar answered Sep 24 '22 10:09

uosjead