Add Elements with Scores using ZADD
In this step, you will learn how to add elements with scores to a Redis Sorted Set using the ZADD command. Sorted Sets are a data structure that stores elements associated with a score. The elements are ordered by their scores, allowing you to retrieve them in a sorted manner.
First, let's connect to the Redis server. Open a terminal in the LabEx VM. You should already be in the ~/project directory. Now, connect to the Redis server using the redis-cli command:
redis-cli
You should see the Redis prompt: 127.0.0.1:6379>.
Now, let's add some elements with scores to a Sorted Set named my_zset. The ZADD command takes the following syntax:
ZADD key score member [score member ...]
Where:
key is the name of the Sorted Set.
score is the score associated with the element.
member is the element to be added.
Let's add three elements to my_zset: "apple" with a score of 1, "banana" with a score of 2, and "cherry" with a score of 3.
ZADD my_zset 1 apple 2 banana 3 cherry
You should see the following output:
(integer) 3
This indicates that three elements were added to the Sorted Set.
It's important to exit the Redis CLI after this step to ensure the commands are logged correctly. To exit, type:
exit