how to get a member with maximum (or minimum ) score from redis sorted set given a subset of members?
Question
I am writing a algo for deducing the user with the least amount of work load. Based on the type/complexity of the tasks being created, i narrow down on the list of the users that are capable of performing it. Now, I need to find the user who has the least number tasks currently assigned to him/her. I am using redis sorted set to store the members/users along the score indicating the number of the tasks assigned to them. Is there a way to get a member with least score given a subset of members?
Solution
Member with minimum score:
ZRANGEBYSCORE myset -inf +inf WITHSCORES LIMIT 0 1
Member with maximum score:
ZREVRANGEBYSCORE myset +inf -inf WITHSCORES LIMIT 0 1
OTHER TIPS
Hope, i understand the structure of your sorted set:
members/users => score
So you have some different ways to solve your question. But there is no solution for make this on one redis command.
Catch data with set of
ZSCORE
calls. PHP with phpredis lib sample with O(N) complexity.$subsetOfUsers = ['user1', 'user2']; $multi = $redis->multi(); foreach ($subsetOfUsers as $user) { $redis->zScore('yourKey', $user); } $result = $multi->exec();
Using
ZINTERSTORE
. Add your subset of members to temportary sorted set withZADD
andZINTERSTORE
temp sorted set with your sorted set. Next get your results withZRANGE
. This can be executed withMULTI
.ADD tmp 0 "user1" ADD tmp 0 "user2" ZINTERSTORE out 2 tmp yourDataSortedSetKey ZRANGE out 0 -1 WITHSCORES
It`s a clear "redis way" with O(N*K) + O(M*log(M)) algorithmic complexity.
p.s. If you are using redis >= 2.6 you can write LUA stored procudure for optimize both of given samples.
Sorted set element with lowest score:
ZRANGE key 0 0 WITHSCORES
Sorted set element with highest score:
ZREVRANGE key 0 0 WITHSCORES
Time complexity: O(log(N)+M) with N being the number of elements in the sorted set and M the number of elements returned.
Docs: https://redis.io/commands/zrange; https://redis.io/commands/zrevrange