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.