Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redis: Find keys matching a pattern

How I can find keys matching a pattern like this:

Eg:

I have some keys:

abc:parent1

abc:parent2

abc:parent1:child1

abc:parent2:child2

How can I find only

abc:parent1

abc:parent2

like image 213
Hoang Tuan Avatar asked Sep 09 '15 08:09

Hoang Tuan


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 key-value pair?

Basic Operations As a dictionary, Redis allows you to set and retrieve pairs of keys and values. Think of a “key” as a unique identifier (string, integer, etc.) and a “value” as whatever data you want to associate with that key. Values can be strings, integers, floats, booleans, binary, lists, arrays, dates, and more.

How can I get total number of keys in Redis?

Get Number of Keys using DBSIZE command. The first command you can use to get the total number of keys in a Redis database is the DBSIZE command. This simple command should return the total number of keys in a selected database as an integer value.


1 Answers

Keys is specifically noted as a command not to be run in production due to the way it works. What you need here is to create an index of your keys. Use a set for storing the key names of the pattern you want. When you add a new we key, add the name of it to the set. For example:

Set abc:parent1:child1 breakfast Sadd abc:parent1:index abc:parent1 

Then when you need the list:

Smembers abc:parent1:index 

Will give you the list, without the penalties and problems associated with using the "evil" keys command. Additionally you would remove an entry with sremove on key deletion. You also get as a benefit the ability to know how many keys are in the index with a single call.

If you absolutely, positively, MUST avoid using an index use SCAN instead of keys. The only time you should even consider keys is if you are running a debug slave where the only process using it is your debugging process.

like image 160
The Real Bill Avatar answered Sep 17 '22 13:09

The Real Bill