Is there MGET analog for Redis hashes?

Viewed 32292

I'm planning to start using hashes insead of regular keys. But I can't find any information about multi get for hash-keys in Redis wiki. Is this kind of command is supported by Redis?

Thank you.

5 Answers

You can query hashes or any keys in pipeline, i.e. in one request to your redis instance. Actual implementation depends on your client, but with redis-py it'd look like this:

pipe = conn.pipeline()
pipe.hgetall('foo')
pipe.hgetall('bar')
pipe.hgetall('zar')
hash1, hash2, hash3 = pipe.execute()

Client will issue one request with 3 commands. This is the same technique that is used to add multiple values to a set at once.

Read more at http://redis.io/topics/pipelining

There is no command to do it on one shot, but there is a way to do it "nicely", using a list (or sorted set) where you would store you hashKeys, and then retrieve them as bulk using multi.

In PHP:

$redis->zAdd("myHashzSet", 1, "myHashKey:1");
$redis->zAdd("myHashzSet", 2, "myHashKey:2");
$redis->zAdd("myHashzSet", 3, "myHashKey:3");

$members = $redis->zRange("myHashzSet", 0, -1);
$redis->multi();
foreach($members as $hashKey) {
    $redis->hGetAll($hashKey);
}
$results = $redis->exec();

I recommand using a sorted set, where you use the score as an ID for your hash, it allows to take advantages of all score based command.

Related