Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 42 ยท Core Data Types

Hashes

Learn Redis hashes: HSET, HGET, HGETALL, HINCRBY, HEXISTS, HSCAN, field-level expiry (HEXPIRE), hashes versus JSON strings, and why small hashes save memory.

A Redis hash is a small dictionary stored under one key: a set of fields, each with a string value. It is the natural way to store an object, such as a user with a name, an email, a plan and a visit counter. Instead of one key per attribute (user:42:name, user:42:email, ...), you keep one key, user:42, and address the pieces by field name.

Hashes are more than a convenience. You can read or change a single field without touching the others, increment a numeric field atomically, and list only the fields you need. This lesson covers the core commands, scanning large hashes, the newer field-level expiry, and when a hash is better than a JSON string. The runnable examples use the JavaScript MiniRedis emulator from What Is Redis?, extended with hash commands and a fake clock. Real syntax is shown in read-only blocks.

Core commands

HSET key field value [field value ...] sets one or more fields and returns how many fields were new (not how many were written). HGET key field reads one field, HMGET several, and HGETALL returns every field and value as a flat list: field1, value1, field2, value2, ....

TEXT
127.0.0.1:6379> HSET user:42 name "Ada" plan "free" visits 0
(integer) 3
127.0.0.1:6379> HGET user:42 name
"Ada"
127.0.0.1:6379> HMGET user:42 name missing
1) "Ada"
2) (nil)
127.0.0.1:6379> HGETALL user:42
1) "name"
2) "Ada"
3) "plan"
4) "free"
5) "visits"
6) "0"

The rest of the family is easy to remember:

Command What it does
HEXISTS key field 1 if the field exists, else 0
HDEL key field [field ...] Remove fields, return how many existed
HLEN key Number of fields
HKEYS key / HVALS key Only the field names / only the values
HSETNX key field value Set only if the field does not exist
HINCRBY key field n Atomic integer add on a field
HINCRBYFLOAT key field x Atomic decimal add

Values are always strings, like Redis strings. HINCRBY treats a field as a 64-bit integer, creates it as 0 if missing, and returns an error if the value is not an integer. As with other collections, a hash with no fields left ceases to exist.

One key, many fields

user:42 One key for the whole object.
Fields name, plan, visits and more.
Values Always strings on the wire.
1 / 2

Try it: build and edit a hash

JS HSET, HGET, HINCRBY and friends

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that the second HSET returned 1: it updated name (not new) and added plan (new), so the reply counts only the new field. HINCRBY on the text field name gives an error, and deleting the last field removed the whole key.

Scanning big hashes with HSCAN

HGETALL is O(N): it returns everything in one reply. On a hash with a handful of fields that is fine, but on one with a million fields it blocks the server and floods the client. HSCAN key cursor [MATCH pattern] [COUNT n] iterates in batches exactly like SCAN from Keys, Expiry and TTL: start at cursor 0, keep calling with the cursor you receive and stop when it returns 0. Each batch is a flat list of field, value pairs. COUNT is a hint, a field can be returned more than once, and MATCH filters after reading.

TEXT
127.0.0.1:6379> HSCAN stats 0 COUNT 100
1) "0"
2) 1) "pageviews"
   2) "10234"
   3) "signups"
   4) "87"
JS Walking a large hash with HSCAN

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The emulator's cursor is only a position in a list, simpler than real Redis's internal order, but the calling loop is identical to what a real client does.

Field-level expiry

A key can have an expiry, but until Redis 7.4 individual hash fields could not. Now they can, which is perfect for sessions, one-time tokens or per-field caches stored beside long-lived data. Redis 8 builds on this feature.

  • HEXPIRE key seconds [NX|XX|GT|LT] FIELDS numfields field [field ...] sets a time to live on the named fields. HPEXPIRE, HEXPIREAT and HPEXPIREAT mirror the key-level commands.
  • HTTL key FIELDS numfields field ... returns the remaining time for each field.
  • HPERSIST key FIELDS numfields field ... removes field expiry.

These commands reply with one number per field. For HEXPIRE: 1 expiry set, 0 condition (NX, XX, GT, LT) not met, -2 no such field (or key) and 2 the field was deleted immediately (a time of zero or in the past). HTTL returns the seconds left, -1 for no expiry and -2 for a missing field. HPERSIST returns 1 when it removed an expiry, -1 when there was none and -2 for a missing field. Redis 8.0 also added combined commands, HSETEX, HGETEX and HGETDEL, which set or read fields and change their expiry in one step.

Expired fields are never visible. When the last field of a hash expires, the whole key disappears.

Try it: expiring fields with a fake clock

JS HEXPIRE, HTTL and HPERSIST

Press Run (or Ctrl + Enter) to see the console output here.

No output.

After 31 seconds the token and csrf fields are gone while user remains. The second NX call returns 0 because user already has an expiry. Expiring the only remaining field with 0 returns 2 and the key vanishes.

Hashes versus JSON strings

You can also store an object as a JSON string with SET and GET. Which is better depends on how you use it.

Hash JSON string
Read one field HGET Fetch all, parse
Update one field HSET, atomic Read, parse, change, write: racy
Atomic counter in the object HINCRBY Not possible without a script
Nested objects, arrays Not supported (flat strings) Natural
Per-field expiry Yes (7.4+) No
Read the whole object HGETALL, flat pairs One GET

Use a hash for flat records you update field by field. Use a JSON string for nested or opaque documents you always read and write whole, or the JSON data type from Redis Stack when you need atomic updates on nested paths.

The race in the "read, parse, change, write" column is real. This example replays it: two clients each change a different field of the same profile, at the same moment.

JS Lost update with JSON, safe with a hash

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Memory efficiency

Redis stores small hashes in a compact format, a single contiguous block rather than a full hash table. By default a hash stays compact while it has at most 128 fields and every field name and value is at most 64 bytes. These limits are configurable:

TEXT
hash-max-listpack-entries 128
hash-max-listpack-value 64

Once a hash exceeds either limit it converts to a regular hash table, which is faster for lookups in large hashes but uses more memory. OBJECT ENCODING key tells you which form a key uses (listpack or hashtable). The practical lesson: a million small objects stored as small hashes usually take noticeably less memory than the same data spread over several million separate string keys, because each key carries its own bookkeeping. Measure with MEMORY USAGE key on your own data rather than trusting a rule of thumb, and see Memory limits and eviction.

Keep hashes to a sensible size. One hash holding an entire table's data becomes a single huge key: slow to scan, impossible to spread across a cluster and costly to delete. Prefer one hash per entity (user:42).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. HSET user:1 name Ada plan pro runs when plan already exists but name does not. What does it return?

    HSET returns the number of fields that were added. Only name is new, so the reply is 1. Updated fields are not counted.
  2. 2. Why is HGETALL a poor choice for a hash with a million fields?

    HGETALL does work proportional to the hash size in one command. Use HSCAN to iterate in small batches.
  3. 3. What does HTTL session:9 FIELDS 1 user return for a field that exists and has no expiry?

    -1 means no expiry, and -2 means the field (or key) does not exist.
  4. 4. Which job is a hash better than a JSON string for?

    HINCRBY updates one field atomically. A JSON string would need a racy read-modify-write cycle.
  5. 5. What happens to the key when the last field of a hash is deleted or expires?

    Like lists, an empty hash is never stored; the key disappears.

Summary

  • A hash stores named fields with string values under one key: ideal for flat objects like users and sessions.
  • HSET returns the number of new fields; HGET, HMGET, HGETALL, HDEL, HEXISTS, HLEN and HINCRBY cover everyday work.
  • Use HSCAN instead of HGETALL on large hashes; both batch rules match SCAN.
  • Redis 7.4 and later support per-field expiry (HEXPIRE, HTTL, HPERSIST), returning one result per field.
  • Prefer a hash to a JSON string when you update fields individually; prefer JSON for nested documents read whole.
  • Small hashes use a compact encoding (default limit 128 fields and 64-byte values) that saves memory.

Next, store unordered collections of unique items in Sets.