Skip to the workspace
Pebellslearn by building
Hashes  ›  Capstone Project

Hash Use Cases and Choosing a Data Type

Usecases 12 minPick the Redis type from the question you will ask: strings for single values and counters, hashes for records, lists for order, sets for membership and sorted sets for ranking.

redis / Hash Use Cases and Choosing a Data Type

Explore each scene at your own pace.

01 · The rule

The rule

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"
  • HINCRBY is INCRBY for one field: atomic, and a missing field starts at 0.
  • HMGET reads chosen fields, with (nil) for missing ones, in order.
  • HLEN counts fields; HKEYS and HVALS list 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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.