Skip to the workspace
Pebellslearn by building
Hashes  ›  Lesson

HSET and HGET

HSET 12 minHSET writes one or more field-value pairs into a hash and replies with how many fields were new, and HGET reads one field's value.

redis / HSET and HGET

Explore each scene at your own pace.

01 · The rule

The rule

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, level already existed and was overwritten, so only city counted: (integer) 1.
  • HGET key field returns 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.

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