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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With