HSET and HGET
Asha's Wordcraft profile has a name, a level, a coin total and a city. You could store four separate string keys, player:asha:name, player:asha:level and so on, but they would be scattered, and deleting or expiring the profile would mean handling four keys. A hash keeps them together under one key.
The rule
One key, many fields: HSET counts only the new fields.
A hash is a key whose value is a small map of fields to values, like one row of a table or one object in code. Field values are strings, just like string keys.
127.0.0.1:6379> HSET player:asha name Asha level 6 coins 120
(integer) 3
127.0.0.1:6379> HGET player:asha level
"6"
127.0.0.1:6379> HSET player:asha level 7 city Pune
(integer) 1
127.0.0.1:6379> HGET player:asha level
"7"
127.0.0.1:6379> HGET player:asha email
(nil)HSET key field value [field value ...]writes one or more pairs, creating the hash if needed.- Its reply is how many fields were added, not how many were written. In the second
HSET,levelalready existed and was overwritten, so onlycitycounted:(integer) 1. HGET key fieldreturns one value, or(nil)if the field or the whole key is missing.
Older code uses HMSET to set several fields; it still works but is deprecated, because HSET now does the same job.
Hashes and strings do not mix: HSET on a string key, or GET on a hash, replies with a WRONGTYPE error.
Why a hash beats scattered keys. The profile is one key, so one DEL or one EXPIRE handles all of it, one HGETALL reads it all, and Redis stores small hashes very compactly.
The shortcut
To predict an HSET reply, tick each field in the command against what is already there: new fields score 1, existing fields score 0. Add up the score.
What exists?
player:ravidoes not exist yet, so every field starts as new.
Drills
Answer fast — trust the rule.
player:tom does not exist. What does HSET player:tom name Tom coins 90 reply?
player:asha has name, level, coins and city. What does HSET player:asha coins 150 reply?
What does HGET player:asha email reply when the hash has no email field?
word:today is a string. What does HSET word:today lang en reply?
Remember
- One key, many fields: HSET counts only the new fields.
- Score each field: new is 1, existing is 0; the sum is the reply.
- A missing field or key reads as nil; the wrong type is an error.
