Redis - Hashes
Redis - Hashes
Section titled “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.
Use Case: Modeling Objects
Section titled “Use Case: Modeling Objects”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.
Example
Section titled “Example”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:10011) "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.
Common Hash Commands
Section titled “Common Hash Commands”Below is a table of essential commands for working with Hashes.
| Command | Description |
|---|---|
| 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 field | Gets the value of a specific field from a hash. |
| HMGET key field [field …] | Gets the values of multiple specified fields from a hash. |
| HGETALL key | Gets 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 key | Gets all the field names (keys) in a hash. |
| HVALS key | Gets all the values in a hash. |
| HLEN key | Gets the number of fields in a hash. |
| HEXISTS key field | Determines if a field exists in a hash. Returns 1 if it exists, 0 otherwise. |
| HINCRBY key field increment | Increments 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 increment | Increments the float value of a hash field by a given amount. |
| HSETNX key field value | Sets 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. |