Bird
Raised Fist0
Redisquery~15 mins

HSET and HGET for fields in Redis - Deep Dive

Choose your learning style10 modes available
Overview - HSET and HGET for fields
What is it?
HSET and HGET are commands in Redis used to work with hashes, which are like small dictionaries inside Redis. HSET adds or updates a field with a value inside a hash, and HGET retrieves the value of a specific field from that hash. This lets you store and access related pieces of information together under one key.
Why it matters
Without HSET and HGET, you would have to store each piece of related data as separate keys, making it harder to organize and slower to access. These commands help keep data grouped logically, improving speed and simplicity when working with structured data in Redis.
Where it fits
Before learning HSET and HGET, you should understand basic Redis keys and string commands. After mastering these, you can explore more complex hash commands, other data types like lists and sets, and how to use Redis in real applications.
Mental Model
Core Idea
HSET and HGET let you store and retrieve named fields inside a single Redis key, like labeled boxes inside one container.
Think of it like...
Imagine a filing cabinet drawer labeled with a person's name (the Redis key). Inside the drawer, there are folders labeled with different topics (fields), and each folder holds papers (values). HSET puts papers into a folder, and HGET finds the papers in a folder.
┌───────────────┐
│ Redis Key     │
│ (e.g., 'user1')│
│               │
│ ┌───────────┐ │
│ │ Field:    │ │
│ │ 'name'    │ │
│ │ Value:    │ │
│ │ 'Alice'   │ │
│ └───────────┘ │
│ ┌───────────┐ │
│ │ Field:    │ │
│ │ 'age'     │ │
│ │ Value:    │ │
│ │ '30'      │ │
│ └───────────┘ │
└───────────────┘
Build-Up - 6 Steps
1
FoundationUnderstanding Redis Hashes
🤔
Concept: Hashes are a data type in Redis that store multiple field-value pairs under one key.
In Redis, a hash is like a small dictionary or map. Instead of storing one value per key, you can store many fields and their values inside a single key. This helps organize related data together. For example, a user profile with name, age, and email can be stored as fields inside one hash key.
Result
You can think of a Redis hash as a container holding many labeled values under one name.
Understanding hashes is essential because HSET and HGET operate on these structures, enabling efficient grouping of related data.
2
FoundationBasic Use of HSET Command
🤔
Concept: HSET adds or updates a field with a value inside a Redis hash key.
The HSET command syntax is: HSET key field value This command creates the hash if it doesn't exist and sets the field to the given value. If the field already exists, it updates the value. Example: HSET user1 name Alice HSET user1 age 30
Result
The hash 'user1' now has fields 'name' with 'Alice' and 'age' with '30'.
Knowing that HSET can create or update fields inside a hash helps you manage grouped data efficiently without separate keys.
3
IntermediateRetrieving Data with HGET
🤔Before reading on: do you think HGET returns the whole hash or just one field's value? Commit to your answer.
Concept: HGET fetches the value of a specific field inside a Redis hash key.
The HGET command syntax is: HGET key field It returns the value stored in the given field of the hash. If the field or key does not exist, it returns nil. Example: HGET user1 name → returns 'Alice' HGET user1 age → returns '30' HGET user1 email → returns nil (field missing)
Result
You get the exact value stored in the requested field or nil if missing.
Understanding that HGET targets a single field inside a hash prevents confusion about retrieving data and helps you access only what you need.
4
IntermediateDifference Between HSET and SET Commands
🤔Before reading on: do you think HSET and SET commands store data the same way? Commit to your answer.
Concept: HSET works on hashes with multiple fields, while SET stores a single string value per key.
SET key value stores one value per key. HSET key field value stores multiple fields inside one key. Example: SET user1 'Alice' stores just 'Alice' under 'user1'. HSET user1 name 'Alice' stores 'Alice' under field 'name' inside 'user1'. This means HSET lets you organize data better when you have many related pieces.
Result
You can choose between simple key-value or structured hash storage depending on your needs.
Knowing this difference helps you pick the right Redis command for your data structure and avoid messy or inefficient storage.
5
AdvancedAtomicity and Performance of HSET/HGET
🤔Before reading on: do you think HSET and HGET commands are atomic and fast? Commit to your answer.
Concept: HSET and HGET are atomic operations and very fast because Redis stores hashes efficiently in memory.
Redis executes each command fully before the next starts, so HSET and HGET are atomic. This means no partial updates or reads happen. Hashes are stored in a way that accessing or updating a field is very quick, even with many fields. This makes hashes ideal for real-time applications needing fast, consistent data access.
Result
You get reliable and speedy updates and reads on hash fields.
Understanding atomicity and performance ensures you trust these commands in critical, concurrent environments.
6
ExpertMemory Optimization and Internal Encoding
🤔Before reading on: do you think Redis always stores hashes the same way internally? Commit to your answer.
Concept: Redis uses different internal encodings for hashes depending on their size to optimize memory and speed.
Small hashes (few fields, small values) are stored in a compact ziplist format to save memory. When hashes grow large or fields/values are big, Redis switches to a hashtable encoding for faster access. This switch is automatic and invisible to users but affects memory use and performance. Knowing this helps when designing data models to keep hashes small for efficiency.
Result
Redis balances memory and speed by adapting hash storage internally.
Knowing internal encoding helps experts optimize Redis usage and troubleshoot unexpected memory or speed issues.
Under the Hood
Redis stores hashes as either ziplists or hashtables internally. When you run HSET, Redis checks if the hash exists and adds or updates the field in the internal structure. HGET looks up the field in this structure and returns the value. These operations happen in memory with O(1) or near O(1) time complexity, making them very fast. Redis commands are atomic, so each HSET or HGET completes fully before another command runs.
Why designed this way?
Redis was designed for speed and simplicity. Using hashes lets users group related data under one key, reducing the number of keys and network calls. The dual internal encoding balances memory use and access speed, adapting automatically to data size. Atomic commands prevent race conditions in concurrent environments, ensuring data consistency.
┌─────────────┐
│ Redis Server│
│             │
│ ┌─────────┐ │
│ │ Hash    │ │
│ │ Key:    │ │
│ │ 'user1' │ │
│ └─────────┘ │
│    │        │
│    ▼        │
│ ┌─────────┐ │
│ │ Internal│ │
│ │ Storage │ │
│ │ (ziplist│ │
│ │ or      │ │
│ │ hashtable)│
│ └─────────┘ │
│    │        │
│ ┌─────────┐ │
│ │ Fields  │ │
│ │ 'name'  │ │
│ │ 'age'   │ │
│ └─────────┘ │
└─────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does HGET return all fields in a hash or just one? Commit to your answer.
Common Belief:HGET returns the entire hash with all fields and values.
Tap to reveal reality
Reality:HGET returns only the value of one specified field inside the hash.
Why it matters:Expecting the whole hash causes inefficient code and confusion when only one field is returned.
Quick: Can HSET create a new hash if the key doesn't exist? Commit to your answer.
Common Belief:HSET only updates existing hashes and fails if the key is missing.
Tap to reveal reality
Reality:HSET creates the hash automatically if the key does not exist.
Why it matters:Knowing this prevents unnecessary checks or extra commands to create hashes before setting fields.
Quick: Does Redis store all hashes the same way internally? Commit to your answer.
Common Belief:All hashes are stored as hashtables regardless of size.
Tap to reveal reality
Reality:Small hashes use a compact ziplist encoding, switching to hashtables only when large.
Why it matters:Ignoring this can lead to inefficient memory use or unexpected performance if hashes grow too big.
Quick: Is HSET atomic and safe to use in concurrent environments? Commit to your answer.
Common Belief:HSET might cause race conditions if multiple clients update the same hash simultaneously.
Tap to reveal reality
Reality:Redis commands, including HSET, are atomic, so updates happen fully without interference.
Why it matters:Misunderstanding atomicity can lead to overcomplicated locking or transaction code.
Expert Zone
1
Redis switches hash encoding automatically based on size, but you can configure thresholds to optimize memory or speed.
2
HSET returns 1 if a new field was added and 0 if an existing field was updated, which can be used to track changes.
3
Using hashes reduces keyspace size, which improves Redis performance and memory fragmentation compared to many separate keys.
When NOT to use
Avoid hashes when fields or values are very large or when you need to frequently access many fields at once; in such cases, consider using Redis strings or other data types like JSON modules or external databases.
Production Patterns
In real systems, hashes store user profiles, session data, or configuration settings. Developers use HSET to update individual fields without overwriting the entire object and HGET to fetch only needed data, minimizing network traffic and memory use.
Connections
Key-Value Stores
HSET/HGET build on the key-value model by adding field-level granularity inside a key.
Understanding simple key-value storage helps grasp how hashes extend this model to organize related data efficiently.
JSON Objects
Hashes in Redis are similar to JSON objects with named fields and values.
Knowing JSON helps understand how hashes group data, but Redis hashes are faster and simpler for small structured data.
Hash Tables in Computer Science
Redis hashes use hash tables internally for fast field lookup.
Understanding hash tables explains why HGET and HSET are very fast operations.
Common Pitfalls
#1Trying to get a whole hash with HGET instead of one field.
Wrong approach:HGET user1
Correct approach:HGET user1 name
Root cause:Misunderstanding that HGET requires both key and field arguments.
#2Using SET to store multiple related fields instead of HSET.
Wrong approach:SET user1 'name:Alice,age:30'
Correct approach:HSET user1 name Alice HSET user1 age 30
Root cause:Not knowing hashes allow structured storage inside one key.
#3Assuming HSET overwrites the entire hash instead of just one field.
Wrong approach:HSET user1 'name:Alice,age:30'
Correct approach:HSET user1 name Alice HSET user1 age 30
Root cause:Confusing HSET syntax and thinking it accepts multiple fields in one call.
Key Takeaways
HSET and HGET let you store and retrieve individual fields inside a single Redis hash key, organizing related data efficiently.
HSET creates or updates fields atomically, while HGET fetches the value of one field, never the whole hash.
Redis stores small hashes compactly and switches encoding automatically to balance memory and speed.
Using hashes reduces the number of keys and network calls, improving performance and data organization.
Understanding these commands helps you design fast, scalable Redis data models for real-world applications.

Practice

(1/5)
1. What does the Redis command HSET do?
easy
A. Stores or updates a field and its value inside a hash key
B. Retrieves the value of a field from a hash key
C. Deletes a field from a hash key
D. Lists all keys in the database

Solution

  1. Step 1: Understand the purpose of HSET

    The HSET command is used to store or update a field-value pair inside a Redis hash key, organizing related data together.
  2. Step 2: Differentiate from other commands

    HGET retrieves values, HDEL deletes fields, and KEYS lists keys, so they do not match the description of HSET.
  3. Final Answer:

    Stores or updates a field and its value inside a hash key -> Option A
  4. Quick Check:

    HSET stores/updates field = A [OK]
Hint: HSET adds or changes a field inside a hash key [OK]
Common Mistakes:
  • Confusing HSET with HGET
  • Thinking HSET deletes fields
  • Mixing HSET with key listing commands
2. Which of the following is the correct syntax to set field name to John in hash key user:1 using Redis?
easy
A. HSET user:1 name John
B. HGET user:1 name John
C. SET user:1 name John
D. HSET name user:1 John

Solution

  1. Step 1: Recall HSET syntax

    The correct syntax is HSET key field value. Here, key is user:1, field is name, and value is John.
  2. Step 2: Check each option

    HSET user:1 name John matches the syntax exactly. HGET user:1 name John uses HGET which is for retrieval. SET user:1 name John uses SET which is for string keys, not hashes. HSET name user:1 John swaps field and key, which is incorrect.
  3. Final Answer:

    HSET user:1 name John -> Option A
  4. Quick Check:

    HSET key field value = C [OK]
Hint: Remember: HSET key field value order [OK]
Common Mistakes:
  • Using HGET instead of HSET to set values
  • Swapping field and key positions
  • Using SET for hash fields
3. Given these Redis commands executed in order:
HSET user:2 age 30
HSET user:2 city London
HGET user:2 age
What is the output of the last command?
medium
A. London
B. 30
C. user:2
D. nil

Solution

  1. Step 1: Analyze the HSET commands

    The first command sets field age to 30 in user:2. The second sets city to London.
  2. Step 2: Understand HGET command

    HGET user:2 age retrieves the value of field age from user:2, which was set to 30.
  3. Final Answer:

    30 -> Option B
  4. Quick Check:

    HGET user:2 age = 30 [OK]
Hint: HGET returns the value of the requested field [OK]
Common Mistakes:
  • Confusing field names and values
  • Expecting HGET to return the key name
  • Assuming HGET returns all fields
4. You run the command HGET user:3 email but get (nil) as output. What could be the reason?
medium
A. The key user:3 is not a hash but a string
B. The Redis server is down
C. The field email does not exist in the hash user:3
D. The syntax of HGET is incorrect

Solution

  1. Step 1: Understand (nil) output in HGET

    When HGET returns (nil), it means the requested field does not exist in the hash key.
  2. Step 2: Evaluate other options

    If the key was not a hash, Redis would return a type error, not (nil). Server down would cause connection errors, and incorrect syntax would cause errors, not (nil).
  3. Final Answer:

    The field email does not exist in the hash user:3 -> Option C
  4. Quick Check:

    HGET nil means field missing = B [OK]
Hint: Nil means field missing, not syntax or server error [OK]
Common Mistakes:
  • Assuming (nil) means server or syntax error
  • Confusing missing field with missing key
  • Ignoring data type errors
5. You want to store user profile data in Redis using a hash key profile:100. You run:
HSET profile:100 name Alice
HSET profile:100 age 0
HGET profile:100 age
What will the last command return and why?
hard
A. Empty string, because age is unset
B. nil, because zero is treated as a missing value
C. Error, because age cannot be zero
D. 0, because Redis stores numeric zero as a valid string value

Solution

  1. Step 1: Understand storing zero in Redis hash

    Redis stores all hash field values as strings. The value 0 is stored as the string "0", which is a valid value.
  2. Step 2: Check HGET behavior for zero value

    HGET returns the exact stored string. Since age was set to 0, it returns "0", not nil or empty.
  3. Final Answer:

    0, because Redis stores numeric zero as a valid string value -> Option D
  4. Quick Check:

    HGET returns stored string '0' = D [OK]
Hint: Zero is stored as string '0', not nil or empty [OK]
Common Mistakes:
  • Thinking zero is treated as missing or false
  • Expecting errors for numeric zero
  • Confusing empty string with zero
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard