tet
tet

Reputation: 1407

Is it possible to use multiple keys with lrange?

I would like to list two different groups of messages on the same web page, but I have been failing to do so.

It is easy if I want to list only one group of messages like the follows.

router.get("/index", function(req, res) {
  redisClient.lrange('chat:messages', 0, -1, function(err, messages) {
    if (err) {
      console.log(err);
    } else {
      var message_list = [];
      messages.forEach(function(message, i) {
        message_list.push(message);
      });
      res.render("index", { messages: message_list });
    }
  });
});

But, I want to list two groups of messages, so what I really want to do is like the follows.

router.get("/index", function(req, res) {
  redisClient.lrange(['chat:messages1', 'chat:messages2'], 0, -1, function(err, messages) {
    if (err) {
      console.log(err);
    } else {
      var message_list1 = [];
      var message_list2 = [];
      messages[0].forEach(function(message, i) {
        message_list1.push(message);
      });
      messages[1].forEach(function(message, i) {
        message_list2.push(message);
      });
      res.render("index", { messages1: message_list1, messages2: message_list2 });
    }
  });
});

This code doesn't work, but I hope I was able to give you an idea of what I want to do.

Is it possible to list two groups of messages on the same page?

If so, how should I tweak my code to make it work?

Upvotes: 2

Views: 1297

Answers (1)

Tague Griffith
Tague Griffith

Reputation: 4183

The lrange command only takes a single key plus indexes. Is it reasonable to rewrite your logic using a multi-block:

 redisClient.multi()
     .lrange('chat:messages1', 0, -1)
     .lrange('chat:messages2', 0, -1)
     .exec(function (err, replies) {
         replies.forEach(function (reply, index) {
            // do your computation
     });

Upvotes: 4

Related Questions