Redis SRANDMEMBER – How to get random elements from a set in redis
4 days 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 :-
redis host:post> SRANDMEMBER <key name> [count]
-(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.
- If count > 0 and count <= size of set, it returns an array of count distinct elements of set.
- If count > 0 and count > size of set, it returns an array containing all the elements of set.
- If count < 0, it returns an array of count elements of set, here array can contain duplicate elements.
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.