Reputation: 11
Example, I want a key (sorted set) to store only 200 elements. If a new element is added (always with highscore) to the set, an element with lowest score in the set should be deleted automatically, maintaining the cardinality of sorted set a constant.
Upvotes: 1
Views: 257
Reputation: 49942
No, there's no such feature per se, but it's very easy to achieve just that.
First, remember that members are unique so there could be a situation (unless in your use case this isn't so) where adding a new member with a new (high) score will actually update the score of an existing member. So, after each ZADD
to your key, do ZCARD
, e.g.:
c = redis.zcard('key')
If ZCARD
's response is > 200, use the difference to trim the sorted set by rank with ZREMRANGEBYRANK
:
if c > 200:
r.zremrangebyrank('key', 0, c - 200 -1)
(BTW, if you're only adding one member at a, the above will always remove just one [the lowest ranked] member)
Upvotes: 2