Redis SRANDMEMBER – How to get random elements from a set in redis

5 years ago Lalit Bhagtani 0

In this tutorial, we will learn about how to get one or more random elements from a set value stored at a key. For this we will use a COMMAND – SRANDMEMBER in redis-cli. The syntax of redis SRANDMEMBER command is as follows :- 

Syntax :-

redis host:post> SRANDMEMBER <key name> [count]

Output :- 

-(string value) if Key exists and Count argument is not given.
-(nil), if Key does not exists and Count argument is not given.
-(array value) if Key exists and Count argument is given.
-(empty array), if Key does not exist and Count argument is given.
-(error), if Key exist and value stored at the key is not a set.

When SRANDMEMBER command is called with only Key argument, a single random element is returned from the set value but when it is called with both Key and Count arguments, three different results can be returned depending upon the value of count passed as an argument.

  1. If count > 0 and count <= size of set, it returns an array of count distinct elements of set.
  2. If count > 0 and count > size of set, it returns an array containing all the elements of set.
  3. If count < 0, it returns an array of count elements of set, here array can contain duplicate elements.

Example :-

Redis SRANDMEMBER

References :-

  1. SRANDMEMBER Command Docs

That’s all for how to get one or more random elements from a set value stored in redis datastore. If you liked it, please share your thoughts in comments section and share it with others too.