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.
hash over a string to store data?age to 30 in a hash named user:1?HSET command sets a field in a hash key.SET is for strings, HMSET is deprecated but similar to HSET, SETFIELD is invalid.HSET user:2 name "Alice" age 25 HSET user:2 city "Paris" GET user:2
GET user:2 command?HSET creates a hash key user:2. GET works only on string keys.GET on a hash key causes a type error in Redis.user:2 is a hash, not a string. -> Option DHSET user:3 name "Bob" age 40 SET user:3 "simple string"
user:3 key type conflicts; delete key before SET. -> Option Aname, age, and email in Redis. You also want to efficiently update individual fields without rewriting the whole object. Which approach is best and why?Pass the test and this pattern moves unknown