Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redis randomKey from from a specific value?

Tags:

redis

I have many different keys. some start with "user USERNAME" and many others.

is there a way to get a random key from the "user *" ?

if so, how can i get like 5 different users?

like image 624
maria Avatar asked Oct 14 '25 09:10

maria


2 Answers

If you put all the usernames into a Redis set, then you could use the SRANDMEMBER command to randomly gets usernames from the set. Example from the documentation:

redis> SADD myset one two three
(integer) 3
redis> SRANDMEMBER myset
"three"
redis> SRANDMEMBER myset 2
1) "three"
2) "two"

The set seems to be the only Redis data type that can return random elements from the collection. You might have to process your data a little differently to do this.

like image 179
Sunil D. Avatar answered Oct 18 '25 07:10

Sunil D.


You can definitely use a Set and store all your "user*" key names in it, as suggested by @Sunil D.

Alternatively, you could use a dedicated Redis database for your "user*" keys and then use the RANDOMKEY command to fetch keys from it. The nice thing about this is that you don't have to manage the Set of key names (i.e. add and remove to it whenever a key is created or deleted, respectively).

Note, however, that with both approaches, you'll have to check that the result you got wasn't returned earlier after each call to SRANDMEMBER or RANDOMKEY since both do not ensure that you'll get a different answer each time you invoke it.

like image 21
Itamar Haber Avatar answered Oct 18 '25 08:10

Itamar Haber