The HINCRBYFLOAT
command in Redis is used to increment the float value of a hash field by the given amount. This can be useful when you're keeping track of high-precision numeric values in a hash and need to increase them incrementally. Some common use cases include:
<?php // Connecting to Redis server on localhost $redis = new Redis(); $redis->connect('127.0.0.1', 6379); // Using HINCRBYFLOAT to increment a hash field $redis->hSet("hash", "field", 10.5); echo $redis->hIncrByFloat("hash", "field", 1.5); // Outputs: 12.0 ?>
In this example, we first set up a connection to the Redis server. Next, we create a Redis hash named "hash" and add a field called "field" with a float value of 10.5. We then use hIncrByFloat
to increment the value of "field" by 1.5, yielding a final result of 12.0 .
HINCRBYFLOAT
, Redis will treat it as having an initial value of 0.HINCRBYFLOAT
works only on string keys: If you try to use HINCRBYFLOAT
on a key storing a data type other than a string, Redis will return an error.What happens if I try to increment a non-existent key?
Redis will treat the non-existent key as having an initial value of 0, and then perform the increment operation.
Can I decrement a value using HINCRBYFLOAT?
Yes, by providing a negative float value to the HINCRBYFLOAT
command, you can effectively decrement the value of a hash field.
Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.