PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, September 5, 2022

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

 September 05, 2022     redis, sortedset     No comments   

Issue

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)


Answered By - roser137
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing