What is Hash in Redis?
Hash in Redis is a "key → value" structure inside a single Redis key.
Essentially, it's a mini-object or a dictionary, where several field:value pairs can be stored under one Redis key.
Main properties
- It's an associative array (a map, a dictionary).
- Every element is a
field:valuepair. - It fits storing objects, user profiles, settings.
- Values are strings (Redis String).
Example
bash
HSET user:1 name "Anna" age "27" city "Moscow"
HGETALL user:1Result:
javascript
1) "name"
2) "Anna"
3) "age"
4) "27"
5) "city"
6) "Moscow"The user:1 key holds three fields: name, age, city.
Main commands
| Command | Description |
|---|---|
HSET key field value [field value ...] | set one or several fields |
HGET key field | get a field's value |
HGETALL key | get every field and value |
HDEL key field [field ...] | remove a field |
HEXISTS key field | check whether a field exists |
HKEYS key | get the list of every field |
HVALS key | get the list of every value |
HLEN key | the number of fields |
HINCRBY key field increment | increment a field's numeric value |
HSETNX key field value | set a field only if it doesn't already exist |
An update-and-count example
bash
HSET user:2 name "Ivan" points "100"
HINCRBY user:2 points 50
HGET user:2 pointsResult:
javascript
"150"Internal structure
Redis stores a Hash in two formats:
- Ziplist, if there are few fields (up to ~512) and they're short; it saves memory.
- Hashtable, if there's a lot of data or the fields are long; it provides fast access.
Redis automatically picks the format based on size.
Uses
- Storing user data, a profile, a session.
- Caching objects from a database.
- Counters and state inside microservices.
- Fast access to individual fields without loading the whole object.
An example used as a cache
bash
HSET product:42 name "Phone" price "899" stock "24"
HGET product:42 priceResult:
javascript
"899"This is how a hash can represent a row of SQL data inside Redis's memory.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.