In Redis, the SMEMBERS
command returns all members of a given set. We specify the key name of the set when we call the command.
Syntax
The syntax goes like this:
SMEMBERS key
So all we do is pass the name of the key that contains the set.
Example
Suppose we create the following set:
SADD animals Cat Dog Mouse Zebra
We can use the SMEMBERS
command to return all values:
SMEMBERS animals
Result:
1) "Cat" 2) "Dog" 3) "Mouse" 4) "Zebra"
As expected, all elements in the set are returned in an array.
Non-Existent Key
Here’s what happens when I pass a key that doesn’t exist:
SMEMBERS oops
Result:
(empty array)
We get an empty array.
Passing the Wrong Number of Arguments
Passing the wrong number of arguments results in an error:
SMEMBERS animals Dog
Result:
(error) ERR wrong number of arguments for 'smembers' command
The error tells us what we did wrong.
We get the same error if we call the command without any arguments:
SMEMBERS
Result:
(error) ERR wrong number of arguments for 'smembers' command