random members from sorted set range

1,426 views
Skip to first unread message

Chris Ochs

unread,
Dec 29, 2011, 3:57:51 PM12/29/11
to redi...@googlegroups.com
Hoping someone has an idea I haven't thought of on how to do this.


There is a sorted set with scores ranging from 1 to 300.  Say here are 10 million members.   I want 20 random members who's score is between X and Y.

If zrangebyscore also returned the zero based index of where the member is in the entire set, I could do everything I want.  I could make two calls to get the start and end entires in the range, and having the index I could then generate random numbers between those two indexes to get the indexes of my random members.

Another way I was thinking might work is to do one zrangebyscore call for each score that is between X and Y, and use limit with a random offset.  Most of the time the difference between X and Y will be small.  For each score I would also do a zcount so I know what the valid range is for the offset.  I could also use this method to create temporary buckets of users that I pull random members from, and just update the bucket every so often.

Any other ideas I'm not thinking of?

Chris








Salvatore Sanfilippo

unread,
Dec 29, 2011, 4:08:06 PM12/29/11
to redi...@googlegroups.com
Hello

I think you can do this if you use ZRANGEBYSCORE with LIMIT to get the
first element with the min score, then ZREVRANGEBYSCORE to get the
last element with the max score, get the position of both with ZRANK,
then calculate a random number between this two positions, and finally
get it with ZRANGE.

Did not tried it but should work. Otherwise of course 2.6 and
scripting can solve that as well, but internally you would a trick
similar to this, just with scripting that would be faster, and would
use a single round-time-trip.

Salvatore

> --
> You received this message because you are subscribed to the Google Groups "Redis DB" group.
> To view this discussion on the web visit https://groups.google.com/d/msg/redis-db/-/rfyEpFGMBbQJ.
> To post to this group, send email to redi...@googlegroups.com.
> To unsubscribe from this group, send email to redis-db+u...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/redis-db?hl=en.


--
Salvatore 'antirez' Sanfilippo
open source developer - VMware

http://invece.org
"We are what we repeatedly do. Excellence, therefore, is not an act,
but a habit." -- Aristotele

Reply all
Reply to author
Forward
0 new messages