Search code examples
redisredis-py

Trimming sorted set by score


In a Django app, I use redis to maintain a global sorted set where user ids are stored with the score of current time since epoch.

After every 11 minutes, I am to run an asynchronous task that trims the sorted set to solely values that were saved in the previous 10 minutes, nothing beyond.

Would the following accomplish this? I'm unsure about edge cases (e.g. will this ensure all old values are deleted or will some leak, etc.):

time_now = time.time() #current time since epoch
ten_mins_ago = time_now - (10*60)
eleven_mins_ago = time_now - (11*60)
my_redis_server.zremrangebyscore(sorted_set,eleven_mins_ago,ten_mins_ago)

Solution

  • Replace eleven_mins_ago with the string value -inf to delete everything that's older than 10 minutes and to avoid any "leak"age. Refer to the Exclusive intervals and infinity section of the ZRANGE's documentation page for full details and explanation.