How to Use HINCRBY in Redis: Increment Hash Field Values
Use the
HINCRBY command in Redis to increment the integer value of a field inside a hash by a specified amount. The syntax is HINCRBY key field increment, where increment can be positive or negative. This command returns the new value after incrementing.Syntax
The HINCRBY command increments the integer value of a field in a hash stored at a given key.
- key: The name of the hash.
- field: The field inside the hash whose value you want to increment.
- increment: The integer amount to add (can be negative to decrement).
redis
HINCRBY key field increment
Example
This example shows how to create a hash with a field and increment its value using HINCRBY. It demonstrates incrementing by positive and negative numbers.
redis
127.0.0.1:6379> HSET user:1000 visits 10 (integer) 1 127.0.0.1:6379> HINCRBY user:1000 visits 5 (integer) 15 127.0.0.1:6379> HINCRBY user:1000 visits -3 (integer) 12 127.0.0.1:6379> HGET user:1000 visits "12"
Output
(integer) 1
(integer) 15
(integer) 12
"12"
Common Pitfalls
Common mistakes when using HINCRBY include:
- Trying to increment a field that holds a non-integer value causes an error.
- Using
HINCRBYon a key that is not a hash results in an error. - Forgetting that the increment must be an integer, not a float.
Always ensure the field contains an integer or does not exist (which will be treated as 0).
redis
127.0.0.1:6379> HSET user:1000 name "Alice" (integer) 1 127.0.0.1:6379> HINCRBY user:1000 name 1 (error) ERR hash value is not an integer
Output
(integer) 1
(error) ERR hash value is not an integer
Quick Reference
| Parameter | Description |
|---|---|
| key | Name of the hash key |
| field | Field inside the hash to increment |
| increment | Integer amount to add (positive or negative) |
| Return | New value of the field after increment |
Key Takeaways
HINCRBY increments an integer field inside a Redis hash by a specified integer amount.
If the field does not exist, it is created with the increment as its value.
The increment must be an integer; floats are not allowed.
Trying to increment a non-integer field causes an error.
HINCRBY returns the new value of the field after incrementing.