redis Sorted Sets Adding Items to a Sorted Set


Redis provides the ZADD command to add items to a sorted set. The basic form of the ZADD command is to specify the set, the item to add and it's score. For example, if I wanted to construct an ordered set of my favorite food (from least to most), I could use either of:

zadd favs 1 apple
zadd favs 2 pizza
zadd favs 3 chocolate
zadd favs 4 beer

or alternatively:

zadd favs 1 apple 2 pizza 3 chocolate 4 beer

The ZADD function operates very similarly to the unsorted set function SADD. The result of the ZADD command is the number of items that were added. So after creating my set as above, if I attempted to ZADD beer again:

ZADD favs 4 beer

I would get a 0 result, if I decided I like chocolate better than beer, I could execute:

ZADD favs 3 beer 4 chocolate

to update my preferences, but I would still get a 0 return result since both beer and chocolate are already in the set.