0
0
RedisHow-ToBeginner · 3 min read

How to Use HGET in Redis: Syntax and Examples

Use the HGET command in Redis to get the value of a specific field from a hash stored at a key. The syntax is HGET key field, which returns the value or null if the field does not exist.
📐

Syntax

The HGET command retrieves the value associated with a given field in a hash stored at a specified key.

  • key: The name of the hash.
  • field: The specific field within the hash whose value you want.
redis
HGET key field
💻

Example

This example shows how to store a hash with user information and then retrieve the user's email using HGET.

redis
127.0.0.1:6379> HSET user:1000 name "Alice" email "alice@example.com" age "30"
(integer) 3
127.0.0.1:6379> HGET user:1000 email
"alice@example.com"
Output
"alice@example.com"
⚠️

Common Pitfalls

Common mistakes when using HGET include:

  • Trying to get a field from a key that does not exist returns null.
  • Requesting a field that is not in the hash also returns null.
  • Using HGET on a key that is not a hash results in an error.

Always ensure the key exists and is a hash before using HGET.

redis
127.0.0.1:6379> HGET user:1000 phone
(nil)
127.0.0.1:6379> SET notahash "value"
OK
127.0.0.1:6379> HGET notahash field
(error) WRONGTYPE Operation against a key holding the wrong kind of value
Output
(nil) OK (error) WRONGTYPE Operation against a key holding the wrong kind of value
📊

Quick Reference

CommandDescriptionReturn Value
HGET key fieldGet value of field in hash at keyValue or null if field/key missing
HSET key field valueSet field in hash at key1 if new field, 0 if updated
HEXISTS key fieldCheck if field exists in hash1 if exists, 0 if not

Key Takeaways

HGET retrieves the value of a specific field from a hash stored at a key.
If the key or field does not exist, HGET returns null.
Using HGET on a non-hash key causes an error.
Always verify the key is a hash before using HGET to avoid errors.
HGET syntax is simple: HGET key field.