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

I am writing algo to output the user with the least workload. Based on the type / complexity of the tasks being created, I will narrow down the list of users who can perform it. Now I need to find a user who currently has fewer tasks assigned. I use redis sorted set to store members / users in the account, indicating the number of tasks assigned to them. Is there a way to get the member with the least points given the subset of members?

+8
source share
3 answers

Member with a minimum score:

ZRANGEBYSCORE myset -inf +inf WITHSCORES LIMIT 0 1 

Member with maximum score:

 ZREVRANGEBYSCORE myset +inf -inf WITHSCORES LIMIT 0 1 
+25
source

I hope I understand the structure of your sorted set:

 members/users => score 

So, you have several ways to resolve your issue. But there is no solution to do this on a single redis team.

  • Get data with a 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 a subset of the participants to the sorted into the tempera set with ZADD and ZINTERSTORE temp sorted set with your sorted set. Then get the results with ZRANGE . This can be done using MULTI .

     ADD tmp 0 "user1" ADD tmp 0 "user2" ZINTERSTORE out 2 tmp yourDataSortedSetKey ZRANGE out 0 -1 WITHSCORES 

    This is a clear "redis path" with algorithmic complexity O (N * K) + O (M * log (M)).

ps If you are using redis> = 2.6, you can write a LUA stored procedure to optimize both given patterns.

0
source

Sorted set of items with the lowest rating:
ZRANGE key 0 0 WITHSCORES

Sorted items with the most points:
ZREVRANGE key 0 0 WITHSCORES

Time complexity: O (log (N) + M), where N is the number of elements in the sorted set, and M is the number of returned elements.

Documents: https://redis.io/commands/zrange ; https://redis.io/commands/zrevrange

0
source

Source: https://habr.com/ru/post/958192/


All Articles