how to get a member with maximum (or minimum ) score from redis sorted set given a subset of members?

StackOverflow https://stackoverflow.com//questions/20017255

  •  21-12-2019
  •  | 
  •  

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?

Was it helpful?

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.

  1. 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();
    
  2. Using ZINTERSTORE. Add your subset of members to temportary sorted set with ZADD and ZINTERSTORE temp sorted set with your sorted set. Next get your results with ZRANGE. This can be executed with MULTI.

    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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top