In Redis, the SADD
command allows us to add members to a key. We can add multiple members if required.
A Redis set is an unordered collection of unique strings (members).
Syntax
The syntax goes like this:
SADD key member [member ...]
This allows us to add one or more members to the specified key.
Example
Here’s an example to demonstrate:
SADD animals "Cat" "Dog" "Ant"
Result:
(integer) 3
In this case, the set didn’t already exist and so I created the set and added three members to it.
We can take a look at the set like this:
SMEMBERS animals
Result:
1) "Ant" 2) "Dog" 3) "Cat"
We can see that the members have been added to the list as specified.
Let’s add another member:
SADD animals "Horse"
Result:
(integer) 1
Let’s check the set again:
SMEMBERS animals
Result:
1) "Horse" 2) "Ant" 3) "Dog" 4) "Cat"
We can see that the latest member has been added as specified.
Duplicate Values
If we try to add a value that already exists, the value isn’t added. This is because a Redis set consists of unique strings.
Let’s try to add the same value again:
SADD animals "Horse"
Result:
(integer) 0
Let’s check the set again:
SMEMBERS animals
Result:
1) "Horse" 2) "Ant" 3) "Dog" 4) "Cat"
We can see that the new value wasn’t added, because it already existed in the set.