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 new members.
    • NX: Do not update members that already exist. Only addd new members.
    • CH: Modify the return value from new added to members added or updated.
    • INCR: Increment the specified member by score. Only one score member pair can be specified.

    Add two elements into the sorted set.

    1. (integer) 2
    1. $ 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.

      1. $ 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.

      1. $ ZRANGEBYSCORE z_key -inf +inf WITHSCORES
      1. 1) "v2"
      2. 2) "2.0"
      3. 3) "v1"
      4. 4) "3.0"
      5. 5) "v3"
      6. 6) "3.0"

      With the XX option specified, only update exiting members. Here, only v1 is modified.

      1. $ ZADD z_key XX 1.0 v1 4.0 v4
      1. (integer) 1

      With the CH option specified, return number of new and updated members.

        1. (integer) 2

        With the INCR option specified, increment by score. Score of v5 should now be 6.0.

        1. $ ZADD z_key INCR 1.0 v5

        Let us now see the updated sorted set.

        1. 1) "v1"
        2. 2) "0.0"
        3. 3) "v2"
        4. 4) "2.0"
        5. 5) "v3"
        6. 6) "3.0"
        7. 7) "v4"
        8. 8) "4.0"
        9. 9) "v5"