In Redis, we have several options for incrementing a key. For example, if we set a key to 1, we can increment it by 1 to make 2. Or we can increment it by whatever amount we desire.
Below are four ways to increment a key in Redis.
The INCR
Command
Our first option is to use the INCR
command. This command increments the key by one. If the key doesn’t exist, it’s created with a value of 0
, then incremented by 1
.
Here’s an example of using INCR
to create a key and increment it by one:
INCR age
Result:
(integer) 1
This command returns the value of the key after the increment has taken place. So if we run the same command again, we get the following:
INCR age
Result:
(integer) 2
The INCRBY
Command
Another option is to use the INCRBY
command. This command increments the key by a specified amount. If the key doesn’t exist, it’s created with a value of 0
, then incremented by the specified amount.
Here’s an example of using INCRBY
on the same key and value from the previous example:
INCRBY age 10
Result:
(integer) 12
This command returns the value of the key after the increment has taken place. In this case the initial value was 2, and we incremented it by 10.
The DECRBY
Command
If we pass a negative value to the DECRBY
command, it has the effect of incrementing the value.
Here’s an example of using DECRBY
with a negative argument:
DECRBY age -2
Result:
(integer) 14
In this case we used -2
which incremented the value by 2.
The INCRBYFLOAT
Command
If you’re working with floating point numbers, you can use the INCRBYFLOAT
command. This command is similar to INCRBY
except that it works on floating point numbers, and also allows you to increment by a floating point number.
Here’s an example of using INCRBYFLOAT
on the same key and value from the previous example:
INCRBYFLOAT age 1.45
Result:
"15.45"