Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit count of items in Redis sorted sets

In my case I upload a lot of records to Redis sorted set, but I need to store only 10 highest scored items. I don't have ability to influence on the data which is uploaded (to sort and to limit it before uploading).

Currently I just execute

ZREMRANGEBYRANK key 0 -11

after uploading finish, but such approach looks not very optimal (it's slow and it will be better if Redis could handle that).

So does Redis provide something out of the box to limit count of items in sorted sets?

like image 688
Gleb Avatar asked Apr 11 '18 08:04

Gleb


People also ask

How does Redis sorted sets work?

A Redis sorted set is a collection of unique strings (members) ordered by an associated score. When more than one string has the same score, the strings are ordered lexicographically. Some use cases for sorted sets include: Leaderboards.

What does Redis use to sort the elements of a sorted set?

In Redis, sorted sets are a data type similar to sets in that both are non repeating groups of strings. The difference is that each member of a sorted set is associated with a score, allowing them to be sorted from the smallest score to the largest.

How do you find the intersection of two sorted sets in Redis?

@write , @sortedset , @slow. Computes the intersection of numkeys sorted sets given by the specified keys, and stores the result in destination . It is mandatory to provide the number of input keys ( numkeys ) before passing the input keys and the other (optional) arguments.

What is Zrange in Redis?

Redis ZRANGE command returns the specified range of elements in the sorted set stored at the key. The elements are considered to be ordered from the lowest to the highest score. Lexicographical order is used for elements with an equal score.


1 Answers

Nopes, redis does not provide any such functionality apart from ZREMRANGEBYRANK .

There is a similar problem about keeping a redis list of constant size, say 10 elements only when elements are being pushed from left using LPUSH.

The solution lies in optimizing the pruning operation.

Truncate your sorted set, once a while, not everytime

Methods:

  1. Run a ZREMRANGEBYRANK with 1/5 probability everytime, using a random integer.

  2. Use redis pipeline or Lua scripting to achieve this , this would even save the two network calls happening at almost every 5th call.

This is optimal enough for the purpose mentioned.

Algorithm example:

ZADD key member1 score1
random_int = some random number between 1-5
if random_int == 1:  # trim sorted set with 1/5 chance
   ZREMRANGEBYRANK key 0 -11
like image 180
DhruvPathak Avatar answered Nov 04 '22 17:11

DhruvPathak