Working with Hashes

1. Setting Hash Fields

CommandDescription
HSET key f v [f v ...]Returns count of new fields
HMSET key f v ...DEPRECATED use HSET

2. Getting Hash Fields

CommandReturns
HGET key fieldValue or nil
HMGET key f1 f2 ...Array (preserves order)

3. Getting All Fields

CommandReturns
HGETALL keyFlat array of f/v pairs
HKEYS keyField names only
HVALS keyValues only

4. Checking Field Existence

CommandReturns
HEXISTS key field1 or 0

5. Deleting Hash Fields

CommandDescription
HDEL key f [f ...]Returns removed field count; deletes hash if empty

6. Getting Field Count

CommandReturns
HLEN keyNumber of fields

7. Setting if Field Not Exists

CommandReturns
HSETNX key field value1 set, 0 exists

8. Incrementing Hash Values

CommandDescription
HINCRBY key field nInteger increment
HINCRBYFLOAT key field amtFloat increment

9. Getting String Length of Field

CommandReturns
HSTRLEN key fieldByte length, 0 if missing

10. Getting Random Fields

CommandOptions
HRANDFIELD key [count [WITHVALUES]]+count unique, -count with repetition 6.2+

11. Scanning Hash Fields

CommandOptions
HSCAN key cursor [MATCH p] [COUNT n] [NOVALUES]NOVALUES returns only fields 7.4+

12. Setting Field Expiration

CommandDescription
HEXPIRE key seconds [NX|XX|GT|LT] FIELDS n f1 ...Per-field TTL 7.4+
HPEXPIRE key ms ... FIELDS n f1 ...Millisecond resolution
HEXPIREAT / HPEXPIREATAbsolute timestamps
HTTL / HPTTLGet field TTL
HPERSIST key FIELDS n f1 ...Remove field TTL

Example: Per-field expiration on session hash

HSET session:42 token "abc" csrf "xyz"
HEXPIRE session:42 600 FIELDS 1 csrf
HTTL session:42 FIELDS 1 csrf