redis/hset

Set Hash Field

Set a specific field in a hash to a given value.

redis
hash
data-structure
write

Command

HSET key field value

Explanation

Redis `HSET` allows you to store multiple related key-value pairs under a single hash key. Hashes are ideal for representing objects or structured data like users, sessions, or configurations. The command can set one or multiple field-value pairs in one call.

Common Use Cases

  • Storing structured user profiles (e.g., name, email, age)
  • Maintaining product data or configuration settings
  • Updating specific object properties without overwriting the entire record

Best Practices

  • Use hashes for objects with multiple attributes
  • Avoid excessive nesting; Redis hashes are flat structures
  • Use consistent naming patterns (e.g., `user:1000:name`)

Common Mistakes to Avoid

  • Confusing `HSET` with `SET` — hashes store multiple fields, not single values
  • Using `HSET` for large JSON objects instead of structured fields

Troubleshooting

Problem: Cannot retrieve field value

Solution: Ensure you use `HGET` instead of `GET` for hash fields.

Problem: Unexpected overwrite

Solution: Check if another process modifies the same hash fields concurrently.

Examples

Set 'name' field in hash 'user:1000'

HSET user:1000 name "Alice"

Set 'age' field in hash 'user:1000'

HSET user:1000 age 30

Set multiple fields at once

HSET product:1 price 49.99 stock 100