The Redis HMGET
command allows us to get multiple values from a hash. It returns the value/s associated with the specified field/s in the hash at the specified key.
Syntax
The syntax goes like this:
HMGET key field [field ...]
Example
Suppose we set the following hash:
HSET customer firstname "Rob" lastname "Banks" age 37
Result:
(integer) 3
Now let’s use HMGET
to get two values from that key:
HMGET customer firstname age
Result:
1) "Rob" 2) "37"
The result is an array reply containing the values associated with the given fields.
Change the Order
The values are returned in the same order as they are requested. Therefore, we can change the order like this:
HMGET customer age firstname
Result:
1) "37" 2) "Rob"
Non-Existent Fields
If the field doesn’t exist, nil
is returned:
HMGET customer lastname height
Result:
1) "Banks" 2) (nil)
Non-Existent Keys
Running the command against a key that doesn’t exist results in nil
being returned:
HMGET nonexistentkey firstname
Result:
1) (nil)
Passing the Wrong Number of Arguments
Passing the wrong number of arguments results in an error:
HMGET customer
Result:
(error) ERR wrong number of arguments for 'hmget' command