Redis ZADD – How to create and add elements in the sorted set value

5 years ago Lalit Bhagtani 0

In this tutorial, we will learn about how to create and add elements in a sorted set value stored at the key, by using a redis ZADD command.

The ZADD command is used to add one or more elements with their respective scores in the sorted set value stored at a specified key. If a specified element already exists, the score of an element is updated and the element is reinserted at the right position to ensure the correct ordering. The score values should be the string representation of a double precision floating point number. +inf and -inf values are valid values.

If a key does not exist in the datastore, a new sorted set is created before performing the insertion operation. If the key exists, but value stored at the key is not of the sorted set datatype, an error is returned.

Optional Arguments

The Redis ZADD command takes following optional arguments :-

  1. XX :- It only updates the elements that already exist in the sorted set but never add new elements.
  2. NX :- It only adds new elements in the sorted set but never update the already existing elements.
  3. CH :-  It modifies the return value from the number of new elements inserted, to the total number of elements changed. Changed elements are new elements added and elements already existing for which the score was updated. So elements specified in the command line having the same score as they had in the past are not counted.
  4. INCR :- If this option is specified ZADD acts like a ZINCRBY command. Only one score-element pair can be specified in this mode. It sets the string value, only if the key already exist.

The elements in the sorted set are in ascending order by their score. For elements having equal score lexicographical order is maintained. The syntax of the Redis ZADD command is as follows :-

Syntax :-

redis host:post> ZADD <key> [XX|NX] [CH] [INCR] <score> <member> [<score> <member>]

Output :- 

- (integer value), representing the number of elements added to the sorted set,
  not including all the elements that were already present. 
- error, if key exist and value stored at the key is not a sorted set.

Example :-

Redis ZADD

References :-

  1. ZADD Command Docs

That’s all for how to create and add elements in a sorted set value stored in redis datastore. If you liked it, please share your thoughts in comments section and share it with others too.