How to extract N random non-repeating elements from SET in Redis?

Asked bydawn friemel

There is a SET c 1000 id, you need to choose 3 random and non-repeating.

The decision "in the forehead" - make SRANDMEMBER 3 times, but there is no guarantee that there will be no repetitions.

You can - control replays at the client level and cycle the SRANDMEMBER cycle until the received set is unique, but this is also somewhat clumsy.

Sort by random value (something in the spirit of SORT ... BY RAND LIMIT 3 INTO ...) Redis does not know how.

As a result, SORT ... INTO ... the resulting list will be of type LIST and you cannot make SPOP from there several times.

Suddenly someone knows an elegant way?

Answers

chris blocker
Elegant and fast, but not the easiest - to make a redis branch on github, implement SRANDMEMBERS, which will receive the number of returned results as a parameter, then use it and offer to include it in the main branch.
Now the dictGetRandomKey function is used in the following cases: when expiring, when receiving a random key from the database, when checking whether the element can be swapped and when receiving a random element of the set.
Or in the forehead. SPOP with a large load - you need to configure so that redis does not start to constantly re-save data on the screw due to constantly changing data, and IMHO is an additional risk of losing it.
hstewart01
3 times SPOP then 3 times add
Replies:
I think with a large load it will not be a quick decision + deleting data from the combat base is not safe. - leafsfan68
Promise Time complexity O (1). The rest is not sure. - tiffunee
How to legally sell software in Ukraine? :: Analog logwatch under Windows? :: Platform for articles :: How to organize IP telephony in my office? :: image formats in PDF
Leave Repply forHow to extract N random non-repeating elements from SET in Redis?
Useful Links