Redis HINCRBYFLOAT in Node.js (Detailed Guide w/ Code Examples)

Use Case(s)

Redis HINCRBYFLOAT command is used to increment the float value of a hash field by the given amount. In a Node.js context, it's commonly utilized in applications where you need to adjust numeric values within a hash, such as:

  • Adjusting a user's account balance in a banking application.
  • Changing player scores in an online game.

Code Examples

The node_redis library provides the hincrbyfloat function to perform this operation.

Here's a simple example of incrementing a user's score:

const redis = require("redis"); const client = redis.createClient(); client.hset("user_scores", "bob", 10, redis.print); client.hincrbyfloat("user_scores", "bob", 2.1, (err, res) => { if(err) console.error(err); else console.log(`Bob's new score: ${res}`); }); client.quit();

In this code:

  1. We create a Redis client.
  2. We set initial score for user 'bob' to 10 using hset.
  3. We increment 'bob's' score by 2.1 using hincrbyfloat. The new score is logged to console.

Best Practices

  • Only use hincrbyfloat with fields that contain numeric data. If the field does not exist or holds non-numeric data, an error will occur.
  • Always handle errors in your callback functions for safer code.
  • Close the connection when done to free up resources using client.quit().

Common Mistakes

  • Not checking if the key and field exists before running hincrbyfloat. If the key or field doesn't exist, Redis will assume it's 0 and perform the operation.
  • Trying to increment non-numeric values which results in an error.

FAQs

Q: What happens if the hash or field doesn't exist?

A: If either the hash or field do not exist, Redis creates them for you. The initial value is assumed to be 0, so hincrbyfloat increments from 0.

Q: What precision does HINCRBYFLOAT use?

A: Redis HINCRBYFLOAT uses a double precision floating point number, which provides very high precision and large range of magnitudes.

Was this content helpful?

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.