HGETALL, HDEL and HEXISTS
The Wordcraft profile screen needs every field of player:asha at once. The settings page needs to know whether Asha has chosen a city yet, and a "remove city" button needs to delete just that one field. Three hash commands cover the whole job.
The rule
HGETALL reads all, HDEL removes some, HEXISTS answers yes or no.
127.0.0.1:6379> HGETALL player:asha
1) "name"
2) "Asha"
3) "level"
4) "7"
5) "coins"
6) "120"
7) "city"
8) "Pune"
127.0.0.1:6379> HEXISTS player:asha city
(integer) 1
127.0.0.1:6379> HDEL player:asha city email
(integer) 1
127.0.0.1:6379> HEXISTS player:asha city
(integer) 0
127.0.0.1:6379> HGETALL player:nobody
(empty array)- HGETALL returns a flat list that alternates field, value, field, value. Four fields give eight lines. A missing key gives an empty list, not an error. Do not rely on the order of the fields.
- HDEL key field [field ...] removes fields and replies with how many it actually removed.
emailwas never there, so onlycitycounted. - HEXISTS key field replies
1if the field is present and0if not, without sending the value.
Empty hashes vanish. Redis never keeps an empty hash. When HDEL removes the last field, the key itself is deleted, and EXISTS on it replies 0. The next HSET simply creates it again. (Lists, sets and sorted sets behave the same way.)
Use HGETALL on small hashes. It returns everything in one reply, which is perfect for a profile of a few fields. For a hash with tens of thousands of fields it becomes a large, slow reply; read just the fields you need with HGET or HMGET instead.
The shortcut
For HGETALL, halve the line count to get the number of fields; for HDEL, count only the fields that were really there.
Look first
HGETALL player:tomreturns 4 lines:name,Tom,coins,90. Four lines, so two fields.
HEXISTS is the right tool when you only need a yes or no, such as "has this player set a city?". Fetching the value with HGET and testing it for nil works too, but it sends the value over the network for nothing. For a whole-record check, EXISTS player:asha tells you whether the hash exists at all.
Drills
Answer fast — trust the rule.
HGETALL player:ravi returns 6 lines. How many fields does the hash have?
player:asha has name, level and coins. What does HDEL player:asha level city reply?
What does HEXISTS player:asha name reply when the field exists?
A hash has one field left and you HDEL it. What does TYPE on that key reply afterwards?
Remember
- HGETALL reads all, HDEL removes some, HEXISTS answers yes or no.
- Halve HGETALL's lines to count fields; HDEL counts only real removals.
- Removing the last field deletes the whole key.
