Skip to the workspace
Pebellslearn by building
Hashes  ›  Lesson

HGETALL, HDEL and HEXISTS

HGETALL 12 minHGETALL returns every field and value of a hash, HDEL removes fields and replies with how many it removed, and HEXISTS replies 1 or 0 for one field.

redis / HGETALL, HDEL and HEXISTS

Explore each scene at your own pace.

01 · The rule

The rule

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. email was never there, so only city counted.
  • HEXISTS key field replies 1 if the field is present and 0 if 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.

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