How to Use HMSET in Redis: Syntax and Examples
Use the
HMSET command in Redis to set multiple fields and their values in a hash at once. The syntax is HMSET key field1 value1 field2 value2 .... This command stores all specified fields in the hash stored at key.Syntax
The HMSET command sets multiple fields in a hash stored at a given key. It takes the key name followed by pairs of field names and their values.
- key: The name of the hash.
- field1, field2, ...: The fields inside the hash.
- value1, value2, ...: The values to assign to each field.
All fields and values are set in one command.
redis
HMSET myhash field1 "Hello" field2 "World" field3 "123"
Output
"OK"
Example
This example shows how to create a hash named user:1000 with fields name, age, and email using HMSET. It sets all fields in one command.
redis
HMSET user:1000 name "Alice" age "30" email "alice@example.com" HGETALL user:1000
Output
OK
1) "name"
2) "Alice"
3) "age"
4) "30"
5) "email"
6) "alice@example.com"
Common Pitfalls
One common mistake is using HMSET with an odd number of arguments, which causes an error because fields and values must come in pairs.
Also, note that HMSET is considered deprecated in newer Redis versions; HSET now supports multiple field-value pairs and is preferred.
redis
HMSET myhash field1 "value1" field2 # This will cause an error because field2 has no value # Correct usage: HMSET myhash field1 "value1" field2 "value2"
Output
(error) ERR wrong number of arguments for 'hmset' command
"OK"
Quick Reference
| Command | Description | Example |
|---|---|---|
| HMSET key field value [field value ...] | Set multiple fields in a hash | HMSET myhash name "Bob" age "25" |
| HSET key field value [field value ...] | Set a single field in a hash (also supports multiple fields in Redis 4.0+) | HSET myhash name "Bob" age "25" |
| HGETALL key | Get all fields and values in a hash | HGETALL myhash |
Key Takeaways
Use HMSET to set multiple fields in a Redis hash in one command.
Fields and values must be provided in pairs; an odd number of arguments causes errors.
HMSET is deprecated; prefer HSET for setting multiple fields in newer Redis versions.
Always verify your hash contents with HGETALL after setting fields.