ZADD
This command sets all specified members
with their respective scores
in the sorted setspecified by key
, with multiple score
member
pairs possible. If a specified member
is already inthe sorted set, this command updates that member
with the new score
. If the key
does not exist, a new sorted setis created, with the specified pairs as the only elements in the set. A score
should be a double,while a member
can be any string.
The number of new members
added to the sorted set, unless the CH
option is specified (see below).
- XX: Only update
members
that already exist. Do not add newmembers
. - NX: Do not update
members
that already exist. Only addd newmembers
. - CH: Modify the return value from new added to
members
added or updated. - INCR: Increment the specified
member
byscore
. Only onescore
member
pair can be specified.
Add two elements into the sorted set.
(integer) 2
$ 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
(integer) 1
With the CH option specified, return number of new and updated members.
(integer) 2
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.
1) "v1"
2) "0.0"
3) "v2"
4) "2.0"
5) "v3"
6) "3.0"
7) "v4"
8) "4.0"
9) "v5"