Search code examples
redissortedset

How do I keep first 10 members and delete rest of a Redis sorted set?


I want to keep the result of my last 10 queries in Redis sorted set. I use timestamps as the score. I need to keep top 10 members by score and delete the rest. I basically need ZREMRANGEBYREVSCORE or ZREMRANGEBYREVRANK but these commands do not exist. Is there a way around this?


Solution

  • I find a workaround with using negative scores with zremrangebyrank. I am not sure this is the right way but works for me.

    counter = 0;
    // temp data
    setInterval(async () => {
        counter += 1;
        val = (new Date()).toString() + " " + counter;
        score = -1 * (new Date() / 1000);
        res = await client.zaddAsync("myset", score, val)
    }, 1000)
    
    // remove other than top50
    setInterval(async () => {
        res = await client.zremrangebyrankAsync("myset", 50, -1);
        console.log("myset zremrangebyrank" + " " + res + " " + val);    
    }, 5000)
    
    // log
    setInterval(async () => {
        res = await client.zrangeAsync("myset", 0, 5);
        console.log(res);
    
        res = await client.zcardAsync("myset");
        console.log("myset zcard" + " " + res);      
    }, 2000)