AttentionThis page documents an earlier version. Go to the latest (v2.1)version.
ZADD key [NX|XX] [CH] [INCR] score member [score member ...]
This command sets all specified
members with their respective
scores in the sorted set
key, with multiple
member pairs possible. If a specified
member is already in
the sorted set, this command updates that
member with the new
score. If the
key does not exist, a new sorted set
is created, with the specified pairs as the only elements in the set. A
score should be a double,
member can be any string.
The number of new
members added to the sorted set, unless the
CH option is specified (see below).
membersthat already exist. Do not add new
membersthat already exist. Only addd new
membersadded or updated.
score. Only one
memberpair can be specified.
Add two elements into the sorted set.
$ ZADD z_key 1.0 v1 2.0 v2
Update an element in the set. Note the return value is 0, since we do not add a new member.
$ ZADD z_key 3.0 v1
Now we add a new member with an existing score. This is fine, since multiple members can have the same score.
$ ZADD z_key 3.0 v3
Let us now see the members in the sorted set. Note the sort order by score. Since both v1 and v3 have the same score, we use comparison on the members themselves to determine order.
$ ZRANGEBYSCORE z_key -inf +inf WITHSCORES
1) "v2" 2) "2.0" 3) "v1" 4) "3.0" 5) "v3" 6) "3.0"
With the XX option specified, only update exiting members. Here, only v1 is modified.
$ ZADD z_key XX 1.0 v1 4.0 v4
With the NX option specified, only add new members. Here only v4 is added.
$ ZADD z_key NX 0.0 v1 4.0 v4
With the CH option specified, return number of new and updated members.
$ ZADD z_key CH 0.0 v1 5.0 v5
With the INCR option specified, increment by score. Score of v5 should now be 6.0.
$ ZADD z_key INCR 1.0 v5
Let us now see the updated sorted set.
$ ZRANGEBYSCORE z_key -inf +inf
1) "v1" 2) "0.0" 3) "v2" 4) "2.0" 5) "v3" 6) "3.0" 7) "v4" 8) "4.0" 9) "v5" 10) "6.0"