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.