Concept Flow - Hash vs string for objects
Start: Store object data
String
End
This flow shows how storing an object in Redis can use either a single string or a hash with fields, affecting how data is stored, retrieved, and updated.
SET user:1 "name:John,age:30,city:NY" HSET user:1 name John age 30 city NY GET user:1 HGET user:1 name
| Step | Command | Action | Result |
|---|---|---|---|
| 1 | SET user:1 "name:John,age:30,city:NY" | Store entire object as one string | OK |
| 2 | HSET user:1 name John age 30 city NY | Store object fields separately in hash | 3 (fields set) |
| 3 | GET user:1 | Retrieve whole string value | "name:John,age:30,city:NY" |
| 4 | HGET user:1 name | Retrieve single field 'name' from hash | "John" |
| 5 | HGET user:1 age | Retrieve single field 'age' from hash | "30" |
| 6 | SET user:1 "name:Jane,age:31,city:LA" | Overwrite whole string with new data | OK |
| 7 | HSET user:1 city LA | Update only 'city' field in hash | 1 (field updated) |
| 8 | GET user:1 | Retrieve updated whole string | "name:Jane,age:31,city:LA" |
| 9 | HGET user:1 city | Retrieve updated 'city' field from hash | "LA" |
| Key | Start | After Step 1 | After Step 2 | After Step 6 | After Step 7 |
|---|---|---|---|---|---|
| user:1 (string) | null | "name:John,age:30,city:NY" | "name:John,age:30,city:NY" | "name:Jane,age:31,city:LA" | "name:Jane,age:31,city:LA" |
| user:1 (hash) | empty | {name: John, age: 30, city: NY} | {name: John, age: 30, city: NY} | {name: John, age: 30, city: NY} | {name: John, age: 30, city: LA} |
Redis stores objects as either strings or hashes. Strings hold the whole object as one text value. Hashes store each field separately as key-value pairs. Strings require full overwrite to update. Hashes allow updating individual fields easily. Use hashes for flexible field access and updates.