0
0
RedisHow-ToBeginner · 3 min read

How to Use HSET in Redis: Syntax and Examples

Use the HSET command in Redis to set one or more fields in a hash stored at a key. The syntax is HSET key field value [field value ...], which adds or updates fields in the hash.
📐

Syntax

The HSET command sets the value of one or more fields in a hash stored at a given key.

  • key: The name of the hash.
  • field: The field name inside the hash.
  • value: The value to assign to the field.
  • You can set multiple field value pairs in one command.
plaintext
HSET key field value [field value ...]
💻

Example

This example shows how to create a hash called user:1000 with fields name and age. It sets the values and then retrieves the hash.

redis
127.0.0.1:6379> HSET user:1000 name "Alice" age 30
(integer) 2
127.0.0.1:6379> HGETALL user:1000
1) "name"
2) "Alice"
3) "age"
4) "30"
Output
(integer) 2 1) "name" 2) "Alice" 3) "age" 4) "30"
⚠️

Common Pitfalls

Common mistakes when using HSET include:

  • Using HSET on a key that holds a non-hash type, which causes an error.
  • Forgetting that HSET overwrites existing fields without warning.
  • Confusing HSET with SET, which works on strings, not hashes.

Always check the key type before using HSET to avoid errors.

redis
127.0.0.1:6379> SET mykey "hello"
OK
127.0.0.1:6379> HSET mykey field1 value1
(error) WRONGTYPE Operation against a key holding the wrong kind of value

-- Correct usage:
127.0.0.1:6379> HSET myhash field1 value1
(integer) 1
Output
(error) WRONGTYPE Operation against a key holding the wrong kind of value (integer) 1
📊

Quick Reference

CommandDescriptionReturn Value
HSET key field valueSet field in hash, create hash if not exists1 if new field, 0 if updated
HSET key field1 value1 field2 value2Set multiple fields in one commandNumber of fields added
HGETALL keyGet all fields and values in hashList of fields and values

Key Takeaways

Use HSET to add or update fields in a Redis hash stored at a key.
You can set multiple field-value pairs in one HSET command.
HSET overwrites existing fields without warning.
Avoid using HSET on keys holding non-hash data types to prevent errors.
Use HGETALL to retrieve all fields and values from a hash.