Lin Du
Lin Du

Reputation: 102587

node-redis, How to get list of hash object?

I use node_redis and I have some hash data store in redis, like this:

127.0.0.1:6379> keys *
1) "posts:list"
2) "posts:page.view"
3) "slug.to.id"
4) "posts:count"
5) "post:1002"
6) "post:1001"
7) "post:3"
8) "post:2"
9) "post:1000"
127.0.0.1:6379> type post:2
hash

I want to get these posts by id, so I write a function like this:

function getPostsByPage(page = 1, pageSize = 10) {
    const start = (page - 1) * pageSize;
    const end = page * pageSize - 1;
    return client.lrangeAsync('posts:list', start, end).then(postIds => {
      const multi = client.multi();
      postIds.forEach(postId => {
        multi.hgetall(`post:${postId}`);
      });
      return multi.execAsync();
    });
  }

For now, I use redis.multi() method to handle the multiple querys from redis server.

so I can get a post array.

Is this the correct way for handling multiple querys from redis server?

I hear that there also another ways, one is pipeline, the other is lua script?

Which one is best and suitable way for my case in real world project?

Upvotes: 0

Views: 606

Answers (1)

Sripathi Krishnan
Sripathi Krishnan

Reputation: 31538

Yes, what you are doing is the right thing. Multi will batch all the hgetall commands and execute them in one batch. It is an efficient way to get the data from the redis server. AFAIK, multi is the way client libraries ensure your commands are sent as a pipeline to the server.

Since you are only reading from the server, your code is appropriate. However, if you had to mix reads and writes, such that your write command depends on the output of a previous read command - then the multi approach would not work. In that cases, writing a lua script would be the only option.

Upvotes: 1

Related Questions