Skip to content

Step 1 of 3 · Reading · ~2 min

Managing Hashes

Hashes

Rounding out hashes: delete, dump, inspect

This lesson finishes the hash command set with the operations you need to remove fields, bulk-read a whole hash, and inspect it without fetching values.

HDEL

Delete one or more fields and report how many actually existed:

python

That last if not h: del hashes[key] mirrors the auto-delete rule from LPOP/RPOP: a hash with zero fields is not a valid Redis value, so the key must disappear entirely once its last field is removed. Forgetting this means EXISTS/TYPE will lie about a key that logically no longer holds anything.

HGETALL — a flat array, not nested

The tricky part of HGETALL isn't the logic (just iterate dict.items()), it's the wire encoding. RESP arrays don't nest key/value pairs — they're flattened into one array alternating field, value, field, value:

python

For {"name": "Alice", "age": "30"} the reply is a 4-element array: *4\r\n$4\r\nname\r\n$5\r\nAlice\r\n$3\r\nage\r\n$2\r\n30\r\n. A client reconstructs the map on its end by reading pairs. Note: dict iteration order in Python 3.7+ is insertion order — that's convenient for deterministic test output, but don't rely on any particular order being semantically meaningful; Redis makes no ordering guarantee for hash fields either.

HEXISTS and HLEN

Both are simple lookups, but keep the reply types straight:

python

HEXISTS replies with a RESP integer (:1\r\n/:0\r\n), not a boolean-flavored bulk string — a very common encoding mistake since Python's True/False don't map onto RESP directly. Always convert to 1/0 explicitly before encoding.

Testing checklist

  • HGETALL on a missing key → empty array *0\r\n, not an error.
  • HDEL removing every remaining field deletes the key (verify with a follow-up TYPE).
  • HLEN on a missing key → 0, not an error.
  • Field ordering in HGETALL matches insertion order so test assertions are deterministic.
Up nextSADD, SMEMBERS & SISMEMBERSets & Sorted Sets

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…