0
0
Redisquery~5 mins

ZINCRBY for score updates in Redis

Choose your learning style9 modes available
Introduction

ZINCRBY helps you add or subtract points from a member's score in a sorted set easily.

You want to update a player's score in a game leaderboard.
You need to increase the count of how many times a user performed an action.
You want to adjust rankings based on new events or data.
You want to keep track of points earned by users over time.
You want to add bonus points to a member in a rewards program.
Syntax
Redis
ZINCRBY key increment member
The key is the name of the sorted set.
The increment is the number to add (can be negative to subtract).
The member is the item whose score you want to update.
Examples
Adds 10 points to player1's score in the leaderboard.
Redis
ZINCRBY leaderboard 10 player1
Subtracts 5 points from player2's score in the leaderboard.
Redis
ZINCRBY leaderboard -5 player2
Adds 1.5 points to user123's score in the scores set.
Redis
ZINCRBY scores 1.5 user123
Sample Program

This example first adds player1 with 50 points. Then it adds 20 more points to player1. It subtracts 10 points from player2 (who is not yet in the set, so player2 is added with score -10). Finally, it lists all players with their scores.

Redis
ZADD leaderboard 50 player1
ZINCRBY leaderboard 20 player1
ZINCRBY leaderboard -10 player2
ZRANGE leaderboard 0 -1 WITHSCORES
OutputSuccess
Important Notes

If the member does not exist, ZINCRBY adds it with the increment as its score.

You can use negative increments to reduce scores.

Scores can be floating point numbers.

Summary

ZINCRBY updates a member's score by adding a number.

It creates the member if it does not exist.

Use it to keep scores or rankings updated easily.