ddark13
ddark13

Reputation: 47

How to iterate a Redis sorted set(ZADD/ ZRANGEBYSCORE) in JavaScript?

The data I am working with requires me to cache and manipulate it in Redis, which will store the Unix time in an ordered list that I need to iterate over later. But I could not find that much information on how to iterate over a Redis sorted set (in this case ZRANGEBYSCORE). So I wanted some advice on how it should be done. The score used in data is in milliseconds. I wrote down the pseudo-code but if anyone knows a better way, please let me know. Below is some of the logic I have so far in Node.js.

redis.ZADD(`my-sorted-set`, Date.now() + 10*60*1000, 'member1');
redis.ZADD(`my-sorted-set`, Date.now() + 20*60*1000, 'member2');
redis.ZADD(`my-sorted-set`, Date.now() + 30*60*1000, 'member3');
Here is the pseudo code on what kind of logic I want to implement...
redis.ZRANGEBYSCORE(`my-sorted-set`, 0,Date.now()+ 100*60*1000,'withscores',function(err,result){
  //  iterate through members.... like an array 
  // remove oldest member 
  // add newest member
});

Upvotes: 2

Views: 1595

Answers (1)

Ankit Sahay
Ankit Sahay

Reputation: 2043

If the timestamps are generated using the script, you don't really need to worry about maintaining the order of the timestamps since they are going to be generated in ascending order, and so you can use a list to store the generated timestamps.

Everytime a timestamp is generated, append it in the redis list using 'RPUSH' command, and you can fetch that list from redis using the 'LRANGE' command.

var redis = require("redis");
var client = redis.createClient();

current_ts = Date.now();
client.rpush('DEMO_LIST', current_ts);

current_ts = Date.now();
client.rpush('DEMO_LIST', current_ts);

current_ts = Date.now();
client.rpush('DEMO_LIST', current_ts);

client.lrange("DEMO_LIST", 0, -1, function(err, redis_list) {
  console.log(redis_list);
});

Output:

[ '1609513808868',
  '1609513869541',
  '1609566462802' ]

The generated timestamp (which is ever increasing) gets appended to the list and the list has timestamps in ascending order.

Upvotes: 2

Related Questions