redis/hget

Get Hash Field

Retrieve the value of a specific field from a hash.

redis
hash
data-structure
read

Command

HGET key field

Explanation

The `HGET` command fetches a single field’s value from a hash. It is analogous to accessing an object’s property in an object-oriented language. If either the hash or the field is missing, Redis returns `(nil)`.

Common Use Cases

  • Reading a specific attribute of an object (e.g., user’s name or balance)
  • Fetching partial information without loading the full hash
  • Accessing dynamic configuration parameters

Best Practices

  • Always verify field existence using `HEXISTS` before relying on `HGET` results
  • Use `HGETALL` or `HMGET` when you need multiple fields at once

Common Mistakes to Avoid

  • Trying to use `GET` on a hash key instead of `HGET`
  • Expecting `HGET` to return multiple fields

Troubleshooting

Problem: Returned value is nil

Solution: Check if the field or hash exists using `HEXISTS key field` or `EXISTS key`.

Problem: Unexpected data type error

Solution: Ensure the key refers to a hash, not another data type (use `TYPE key`).

Examples

Get 'name' field from hash 'user:1000'

HGET user:1000 name

Get product price from hash

HGET product:1 price