Skip to content

Redis - Hashes

Redis Hashes are a data type that maps string fields to string values. They are the perfect data structure for representing objects, such as a user profile, a product, or any entity with multiple properties. A single hash can store over 4 billion field-value pairs.

Instead of storing each property of an object as a separate top-level key (e.g., user:1001:name, user:1001:email), you can group them into a single hash. This is far more memory-efficient and logically organized.

We’ll use the modern HSET command, which can set multiple fields at once. The key user:1001 represents our object, and the subsequent pairs are its fields and values.

127.0.0.1:6379> HSET user:1001 name "Jane Doe" email "jane.doe@example.com" plan "premium" visits 150
(integer) 4
127.0.0.1:6379> HGETALL user:1001
1) "name"
2) "Jane Doe"
3) "email"
4) "jane.doe@example.com"
5) "plan"
6) "premium"
7) "visits"
8) "150"

Note: HMSET was used in older versions of Redis but is now deprecated in favor of HSET with multiple field/value arguments.

Below is a table of essential commands for working with Hashes.

CommandDescription
HSET key field value [field value …]Sets one or more field-value pairs in a hash. Creates the hash if it doesn’t exist.
HGET key fieldGets the value of a specific field from a hash.
HMGET key field [field …]Gets the values of multiple specified fields from a hash.
HGETALL keyGets all fields and their values from a hash. Use with caution on very large hashes.
HDEL key field [field …]Deletes one or more fields from a hash.
HKEYS keyGets all the field names (keys) in a hash.
HVALS keyGets all the values in a hash.
HLEN keyGets the number of fields in a hash.
HEXISTS key fieldDetermines if a field exists in a hash. Returns 1 if it exists, 0 otherwise.
HINCRBY key field incrementIncrements the integer value of a hash field by a given number. In our example, we could run HINCRBY user:1001 visits 1.
HINCRBYFLOAT key field incrementIncrements the float value of a hash field by a given amount.
HSETNX key field valueSets the value of a field, only if the field does not already exist.
HMSET key field value [field value …]DEPRECATED since Redis 4.0.0. Use HSET instead.