0
0
Redisquery~5 mins

HINCRBY for numeric fields in Redis

Choose your learning style9 modes available
Introduction

HINCRBY helps you add or subtract numbers stored inside a small group of values called a hash. It makes changing numbers easy and fast.

You want to count how many times something happens, like page views for a website.
You need to update scores in a game for different players quickly.
You want to keep track of inventory amounts for products in a store.
You want to add or subtract points from a user's profile without rewriting all data.
Syntax
Redis
HINCRBY key field increment

key is the name of the hash where numbers are stored.

field is the specific number inside the hash you want to change.

increment is how much you add (positive) or subtract (negative).

Examples
Adds 1 to the 'visits' number inside the 'user:1000' hash.
Redis
HINCRBY user:1000 visits 1
Subtracts 3 from the 'stock' number inside the 'product:200' hash.
Redis
HINCRBY product:200 stock -3
Adds 10 points to 'player1' score inside the 'game:score' hash.
Redis
HINCRBY game:score player1 10
Sample Program

This example first sets the points to 10 for user:1, then adds 5 points, subtracts 3 points, and finally gets the current points.

Redis
HSET user:1 points 10
HINCRBY user:1 points 5
HINCRBY user:1 points -3
HGET user:1 points
OutputSuccess
Important Notes

If the field does not exist, HINCRBY creates it and sets it to the increment value.

Only works with integer numbers stored as strings inside the hash.

Using a non-numeric field will cause an error.

Summary

HINCRBY changes numbers inside a hash by adding or subtracting.

It is fast and useful for counters, scores, and inventory.

Remember to use it only on numeric fields.