The HMGET
command in Redis is used when we need to retrieve multiple field values from a hash stored in Redis. This is particularly useful in cases where a single key is associated with numerous field-value pairs, such as storing user profiles where a username might be linked to attributes like email, age, and address.
Let's say you have a hash in Redis that represents a user profile with the key 'user:1' and fields 'name', 'email', and 'age'. Here's how you can retrieve these details using HMGET
in PHP:
<?php $redis = new Redis(); $redis->connect('127.0.0.1', 6379); // Fetches 'name', 'email', and 'age' of 'user:1' $fields = $redis->hMGet('user:1', array('name', 'email', 'age')); print_r($fields); ?>
This script will return an associative array containing the requested fields and their respective values.
HMGET
over multiple HGET
commands for efficiency when retrieving multiple fields.HMGET
will return null
for non-existing keys or fields.null
for those fields. Make sure the key and fields exist before fetching.HMGET
only works on hashes. Trying to use it on other data types will result in an error.Q: What's the difference between HGET
and HMGET
in Redis?
A: While both are used to retrieve values from hashes, HGET
returns the value of a specific field, while HMGET
can return the values of multiple fields.
Q: Can I use HMGET
with keys that aren't hashes?
A: No, HMGET
is specifically designed for hash keys. Using it with other data types will result in an error.
Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.