0
0
RedisHow-ToBeginner · 3 min read

How to Use HMGET in Redis: Syntax and Examples

Use the HMGET command in Redis to get the values of multiple fields from a hash in a single call. The syntax is HMGET key field1 field2 ..., which returns an array of values for the specified fields.
📐

Syntax

The HMGET command retrieves the values of one or more specified fields from a hash stored at a given key.

  • key: The name of the hash.
  • field1, field2, ...: The fields whose values you want to get.

The command returns an array of values corresponding to the requested fields. If a field does not exist, its value in the array will be null.

redis
HMGET key field1 field2 ...
💻

Example

This example shows how to use HSET to create a hash and then HMGET to retrieve multiple fields from it.

redis
127.0.0.1:6379> HSET user:1000 name "Alice" age "30" city "New York"
(integer) 3
127.0.0.1:6379> HMGET user:1000 name age city
1) "Alice"
2) "30"
3) "New York"
Output
1) "Alice" 2) "30" 3) "New York"
⚠️

Common Pitfalls

Common mistakes when using HMGET include:

  • Requesting fields from a key that does not exist returns an array of null values.
  • Requesting fields that do not exist in the hash returns null for those fields.
  • Confusing HMGET with HGETALL, which returns all fields and values.

Example of wrong and right usage:

redis
127.0.0.1:6379> HMGET user:999 name age
1) (nil)
2) (nil)

# Correct usage with existing key and fields
127.0.0.1:6379> HMGET user:1000 name age
1) "Alice"
2) "30"
Output
1) (nil) 2) (nil) 1) "Alice" 2) "30"
📊

Quick Reference

Summary tips for HMGET:

  • Use HMGET to fetch multiple hash fields in one command.
  • Returns an array with values or null for missing fields.
  • Does not create keys or fields; use HSET to add data.

Key Takeaways

HMGET retrieves multiple fields from a Redis hash in a single call.
It returns an array of values, with null for any missing fields.
Use HSET to add or update hash fields before using HMGET.
Requesting fields from a non-existent key returns null values.
HMGET differs from HGETALL, which returns all fields and values.