The following commands can be used to update a field in a Redis hash. The command we use will depend on the type of data that’s stored in the field.
The HSET
Command
The HSET
command can be used to update the value at the given field.
Suppose we set a hash like this:
HSET pet name "Wag" age 10 height 7.85
Result:
(integer) 3
Let’s use HGET
to check the value of the name
field:
HGET pet name
Result:
"Wag"
We can use the HSET
command to update that field’s value:
HSET pet name "Bark"
Result:
(integer) 0
An integer reply of zero means that no new fields were added. However, our existing field was updated.
Let’s check:
HGET pet name
Result:
"Bark"
It has been updated as specified.
The HINCRBY
Command
The HINCRBY
command increments the number stored at a field by the specified amount. This command is limited to 64 bit signed integers, therefore, we would only use it on fields that contain integers:
HINCRBY pet age 1
Result:
(integer) 11
The integer reply tells us the value of the field after it has been incremented. The original value of this field was 10, and we incremented it by 1. Therefore, the new value is 11 as indicated in the result.
Let’s check the value of that field now:
HGET pet age
Result:
"11"
As expected.
The HINCRBYFLOAT
Command
The HINCRBYFLOAT
command is similar to HINCRBY
but it is intended to be used on floating point numbers. Let’s update the height
field:
HINCRBYFLOAT pet height 1.27
Result:
"9.12"
The bulk string reply tells us the value of the field after it has been incremented.
Let’s use the HGETALL
command to check the contents of the hash now:
HGETALL pet
Result:
1) "name" 2) "Bark" 3) "age" 4) "11" 5) "height" 6) "9.12"