0
0
Redisquery~5 mins

ZADD for adding scored members in Redis

Choose your learning style9 modes available
Introduction

ZADD lets you add items with scores to a sorted list in Redis. This helps keep things in order by score.

When you want to keep a leaderboard with player scores.
When you need to store tasks with priorities and get them sorted.
When you want to track items by time or rating and retrieve them in order.
When you want to add new members to a sorted set with their scores.
Syntax
Redis
ZADD key [NX|XX] [CH] [INCR] score member [score member ...]

key is the name of the sorted set.

You add one or more score member pairs to the set.

Examples
Adds 'player1' with score 100 to the 'leaderboard' sorted set.
Redis
ZADD leaderboard 100 player1
Adds two members 'taskA' with score 5 and 'taskB' with score 10 in one command.
Redis
ZADD tasks 5 taskA 10 taskB
Adds 'player2' with score 150 only if 'player2' does not already exist in 'leaderboard'.
Redis
ZADD leaderboard NX 150 player2
Sample Program

This adds three players with scores to the 'leaderboard' and then lists all players with their scores in order.

Redis
ZADD leaderboard 50 Alice
ZADD leaderboard 70 Bob
ZADD leaderboard 60 Charlie
ZRANGE leaderboard 0 -1 WITHSCORES
OutputSuccess
Important Notes

ZADD returns the number of new members added, not counting updated scores.

Scores are numbers and can be decimals.

Use ZRANGE with WITHSCORES to see members and their scores.

Summary

ZADD adds members with scores to a sorted set.

It keeps members sorted by score automatically.

You can add multiple members at once.