Hash Use Cases and Choosing a Data Type
Wordcraft now needs a place for profiles, counters, a chat feed, badges and a scoreboard. Redis offers a different structure for each, and picking the wrong one means fighting it forever: sorting in your app what a sorted set would keep sorted, or scanning a list for something a set could check instantly.
The rule
Choose the type from the question you will ask it.
The five core types, and the question each one answers best:
| Type | Shape | Best question |
|---|---|---|
| String | one value | "What is it?" or "Add one to it." |
| Hash | named fields | "What is this record's field?" |
| List | ordered items | "What came first or last?" |
| Set | unique members | "Is this in it?" or "What do two groups share?" |
| Sorted set | members with scores | "Who is top?" or "What is my rank?" |
TYPE key tells you which one a key holds: string, hash, list, set, zset, or none if the key is missing.
Where hashes shine. Anything that looks like a record: a user profile, a product card, a session with several fields, per-object settings. A few more hash commands make them practical:
127.0.0.1:6379> HINCRBY player:asha coins 30
(integer) 150
127.0.0.1:6379> HMGET player:asha name coins email
1) "Asha"
2) "150"
3) (nil)
127.0.0.1:6379> HLEN player:asha
(integer) 3
127.0.0.1:6379> HKEYS player:asha
1) "name"
2) "level"
3) "coins"HINCRBYisINCRBYfor one field: atomic, and a missing field starts at 0.HMGETreads chosen fields, with(nil)for missing ones, in order.HLENcounts fields;HKEYSandHVALSlist only the fields or only the values.
Where hashes do not fit. A hash cannot hold a list or another hash inside a field, and you cannot sort or rank by a field. For "top players by coins", keep the coins in a sorted set as well.
The shortcut
Turn the feature into its most frequent question, then match the question's key word: "is it in" → set, "top or rank" → sorted set, "first or latest" → list, "field of a record" → hash, "one value or count" → string.
Write the question
"Who were Asha's last five opponents, newest first?"
Drills
Answer fast — trust the rule.
Which type should hold the set of words a player has already guessed today, checked on every guess?
player:asha has coins 150. What does HINCRBY player:asha coins -20 reply?
What does TYPE leaderboard reply when the key holds a sorted set?
The feature is "show the 20 highest-rated words". Which type fits best?
Remember
- Choose the type from the question you will ask it.
- Key words: in → set, rank → sorted set, latest → list, field → hash, count → string.
- Hashes are records: HINCRBY, HMGET and HLEN make them practical.
