Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there anyway to retrieve all keys that start with a particular string in redis?

Is there anyway to retrieve all keys that start with a particular string in redis?

I want to do something like storing:

'thing1:userid1' : ' ';
'thing1:userid2' : ' ';
'thing2:userid1' : ' ';
'thing2:userid2' : ' ';

and retrieve every thing1 without having to know every user.

like image 487
fancy Avatar asked Sep 18 '11 17:09

fancy


2 Answers

REDIS.keys("thing1:*")

However, you might want to consider using a map.

REDIS.hset("thing1", "user1", "")
REDIS.hset("thing1", "user2", "")
REDIDS.hgetall("thing1")

Do be careful with this in production. Redis can only process one command at a time, and KEYS is very slow. It has to look at every key in the entire database.

like image 114
ABentSpoon Avatar answered Sep 25 '22 10:09

ABentSpoon


You can also keep track of the ids in a List and then retrieve the values of all keys ( or hashes ) using SORT http://redis.io/commands/SORT.

It's a bit more complicated than "KEYS" but it can do more as well ( :

I read somewhere that hgetall can give you problems if you have too many fields in a hash, unfortunately i can't find the reference atm.

like image 38
kroe Avatar answered Sep 25 '22 10:09

kroe