0
0
Redisquery~15 mins

HKEYS and HVALS in Redis - Deep Dive

Choose your learning style9 modes available
Overview - HKEYS and HVALS
What is it?
HKEYS and HVALS are Redis commands used to work with hash data structures. HKEYS returns all the field names (keys) in a hash, while HVALS returns all the values stored in those fields. Hashes in Redis are like small dictionaries or maps that store key-value pairs under a single main key.
Why it matters
These commands help you quickly see what data is stored inside a hash without fetching the entire content. Without them, you would have to retrieve and parse the whole hash manually, which is inefficient and slow. They make managing and inspecting structured data in Redis simple and fast.
Where it fits
Before learning HKEYS and HVALS, you should understand basic Redis data types and commands, especially hashes. After mastering these, you can explore more advanced hash commands like HGETALL, HMGET, and how to use hashes in real applications for caching or session storage.
Mental Model
Core Idea
HKEYS lists all the field names in a Redis hash, and HVALS lists all the values, letting you peek inside the hash's structure quickly.
Think of it like...
Imagine a filing cabinet drawer labeled with a person's name (the Redis hash). HKEYS is like pulling out all the folder labels inside that drawer, and HVALS is like pulling out all the papers inside those folders without their labels.
Redis Hash: user:1000
┌─────────────┬───────────────┐
│ Field (HKEYS) │ Value (HVALS) │
├─────────────┼───────────────┤
│ name        │ Alice         │
│ age         │ 30            │
│ city        │ Paris         │
└─────────────┴───────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding Redis Hashes Basics
🤔
Concept: Introduce what a Redis hash is and how it stores data as field-value pairs under one key.
A Redis hash is like a mini-database inside Redis that holds multiple key-value pairs. For example, a hash named 'user:1000' might store fields like 'name', 'age', and 'city' with their respective values. This lets you group related data under one main key.
Result
You know that hashes group multiple pieces of data under one key, making it easier to organize related information.
Understanding hashes is crucial because HKEYS and HVALS operate specifically on this data structure, not on simple strings or lists.
2
FoundationBasic Redis Commands for Hashes
🤔
Concept: Learn how to add and retrieve individual fields in a Redis hash using HSET and HGET.
Use HSET to add a field and value to a hash: HSET user:1000 name Alice. Use HGET to get a value by field: HGET user:1000 name returns 'Alice'. These commands let you work with one field at a time.
Result
You can store and fetch single pieces of data inside a hash.
Knowing how to manipulate individual fields sets the stage for understanding commands that list all fields or values.
3
IntermediateUsing HKEYS to List All Fields
🤔Before reading on: do you think HKEYS returns values or field names? Commit to your answer.
Concept: HKEYS returns all the field names (keys) inside a hash, letting you see what data categories exist.
If you run HKEYS user:1000, Redis returns ['name', 'age', 'city']. This shows all the fields stored in that hash without their values.
Result
You get a list of all field names inside the hash.
Understanding that HKEYS returns only field names helps you inspect the structure of your data quickly without fetching values.
4
IntermediateUsing HVALS to List All Values
🤔Before reading on: do you think HVALS returns field names or values? Commit to your answer.
Concept: HVALS returns all the values stored in the fields of a hash, letting you see the data content without field names.
Running HVALS user:1000 returns ['Alice', '30', 'Paris']. This shows all the values stored in the hash fields.
Result
You get a list of all values inside the hash.
Knowing that HVALS returns only values helps when you want to process or display data without caring about field names.
5
IntermediateDifference Between HKEYS, HVALS, and HGETALL
🤔Before reading on: does HGETALL return fields, values, or both? Commit to your answer.
Concept: HGETALL returns both field names and values as pairs, while HKEYS and HVALS return only one side each.
HGETALL user:1000 returns ['name', 'Alice', 'age', '30', 'city', 'Paris']. This is a flat list alternating fields and values. HKEYS returns only ['name', 'age', 'city'], and HVALS returns only ['Alice', '30', 'Paris'].
Result
You understand when to use each command based on whether you need fields, values, or both.
Knowing the difference prevents unnecessary data fetching and helps optimize Redis queries.
6
AdvancedPerformance Considerations with Large Hashes
🤔Before reading on: do you think HKEYS and HVALS are fast or slow on very large hashes? Commit to your answer.
Concept: HKEYS and HVALS scan the entire hash, so their performance depends on hash size; large hashes can cause delays.
If a hash has thousands of fields, running HKEYS or HVALS returns all of them at once, which can be slow and block Redis. For very large hashes, consider using HSCAN to iterate in smaller chunks.
Result
You learn to avoid performance pitfalls by choosing the right command for large data.
Understanding command cost helps you write efficient Redis code and avoid slowdowns in production.
7
ExpertInternal Data Structure Behind HKEYS and HVALS
🤔Before reading on: do you think Redis stores hashes as simple lists or optimized structures? Commit to your answer.
Concept: Redis stores hashes internally as either ziplist or hashtable depending on size, affecting how HKEYS and HVALS work.
Small hashes use a compact ziplist for memory efficiency, making HKEYS and HVALS fast and memory-light. Large hashes switch to hashtables for speed. This internal choice affects iteration speed and memory use.
Result
You understand why Redis behaves differently with small vs large hashes and how it optimizes storage.
Knowing internal storage helps you predict command performance and memory usage, guiding better data modeling.
Under the Hood
When you run HKEYS or HVALS, Redis accesses the hash stored under the given key. Internally, Redis uses either a ziplist or a hashtable to store the hash fields and values. HKEYS iterates over the internal structure to collect all field names, while HVALS collects all values. The commands return these lists to the client in a single response.
Why designed this way?
Redis hashes are designed to be memory efficient and fast. Using ziplist for small hashes saves memory, while hashtables for large hashes improve speed. Separating HKEYS and HVALS allows clients to fetch only what they need, reducing data transfer and processing.
Redis Hash Storage
┌───────────────┐
│ Redis Key     │
│ (e.g., user:1000) │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Internal Hash │
│ ┌───────────┐ │
│ │ Ziplist   │ │  (small hashes)
│ └───────────┘ │
│ or            │
│ ┌───────────┐ │
│ │ Hashtable │ │  (large hashes)
│ └───────────┘ │
└──────┬────────┘
       │
       ├─> HKEYS: iterate fields
       └─> HVALS: iterate values
Myth Busters - 4 Common Misconceptions
Quick: Does HKEYS return values or field names? Commit to your answer.
Common Belief:HKEYS returns the values stored in the hash fields.
Tap to reveal reality
Reality:HKEYS returns only the field names (keys), not the values.
Why it matters:Confusing fields with values leads to wrong data handling and bugs when processing Redis hashes.
Quick: Does HVALS return field names or values? Commit to your answer.
Common Belief:HVALS returns the field names of the hash.
Tap to reveal reality
Reality:HVALS returns only the values stored in the hash fields.
Why it matters:Misusing HVALS when you need field names causes incomplete or incorrect data retrieval.
Quick: Does HKEYS or HVALS return data in any guaranteed order? Commit to your answer.
Common Belief:HKEYS and HVALS return fields and values in the order they were added.
Tap to reveal reality
Reality:Redis does not guarantee any order for fields or values returned by HKEYS or HVALS.
Why it matters:Assuming order can cause bugs when matching fields to values or displaying data.
Quick: Are HKEYS and HVALS efficient on very large hashes? Commit to your answer.
Common Belief:HKEYS and HVALS are always fast regardless of hash size.
Tap to reveal reality
Reality:For very large hashes, these commands can be slow and block Redis because they return all fields or values at once.
Why it matters:Using these commands on large hashes without care can cause performance problems in production.
Expert Zone
1
Redis switches internal hash encoding from ziplist to hashtable automatically based on size and field length, affecting HKEYS/HVALS performance.
2
HKEYS and HVALS return arrays without guaranteed order, so pairing fields and values requires careful handling or using HGETALL instead.
3
Using HSCAN instead of HKEYS/HVALS for large hashes allows incremental iteration, preventing blocking and improving responsiveness.
When NOT to use
Avoid using HKEYS and HVALS on very large hashes because they return all data at once, which can block Redis. Instead, use HSCAN to iterate fields or values in smaller batches. For fetching specific fields, use HMGET or HGET to reduce data transfer.
Production Patterns
In production, HKEYS and HVALS are often used for debugging or small hashes. For large datasets, developers use HSCAN for pagination or incremental processing. Hashes are commonly used for user sessions, configurations, or caching objects, where quick field or value listing helps maintain or audit data.
Connections
Dictionary Data Structure
HKEYS and HVALS operate on Redis hashes, which are similar to dictionaries in programming languages.
Understanding dictionaries helps grasp how Redis hashes store key-value pairs and why listing keys or values separately is useful.
Pagination in APIs
HSCAN provides incremental iteration over hash fields, similar to paginating results in APIs.
Knowing pagination concepts helps understand why HSCAN is preferred over HKEYS/HVALS for large data to avoid blocking.
Relational Database Table Columns and Rows
Fields in a Redis hash are like columns, and values are like row entries, with HKEYS listing columns and HVALS listing row data.
This analogy helps relate Redis hashes to familiar database concepts, aiding understanding of data organization.
Common Pitfalls
#1Fetching all fields and values separately and assuming order matches.
Wrong approach:HKEYS user:1000 HVALS user:1000 -- then pairing results by index
Correct approach:HGETALL user:1000
Root cause:HKEYS and HVALS do not guarantee order, so pairing by index can mismatch fields and values.
#2Using HKEYS or HVALS on very large hashes without considering performance.
Wrong approach:HKEYS huge_hash HVALS huge_hash
Correct approach:Use HSCAN huge_hash 0 MATCH * COUNT 100 to iterate in chunks
Root cause:HKEYS and HVALS return all data at once, causing blocking on large hashes.
#3Expecting HKEYS or HVALS to return data in insertion order.
Wrong approach:Assuming HKEYS user:1000 returns fields in the order they were added.
Correct approach:Treat HKEYS and HVALS output as unordered; use HGETALL or sorted structures if order matters.
Root cause:Redis hash internal storage does not preserve insertion order.
Key Takeaways
HKEYS returns all field names in a Redis hash, while HVALS returns all values.
These commands help inspect the structure or content of hashes quickly but do not guarantee order.
For large hashes, using HSCAN is better to avoid blocking Redis with large data returns.
Understanding Redis internal hash encoding explains performance differences between small and large hashes.
Avoid pairing HKEYS and HVALS results by index; use HGETALL to get fields and values together safely.