How to Use SMEMBERS Command in Redis: Syntax and Examples
Use the
SMEMBERS command in Redis to retrieve all members of a set stored at a given key. It returns all elements as an unordered collection. The syntax is SMEMBERS key, where key is the name of the set.Syntax
The SMEMBERS command retrieves all members of the set stored at the specified key. If the key does not exist, it returns an empty set.
- key: The name of the set you want to get members from.
redis
SMEMBERS key
Example
This example shows how to add members to a set and then retrieve all members using SMEMBERS.
redis
SADD fruits apple banana orange SMEMBERS fruits
Output
1) "apple"
2) "banana"
3) "orange"
Common Pitfalls
Common mistakes when using SMEMBERS include:
- Using
SMEMBERSon a key that is not a set, which causes an error. - Expecting the members to be returned in any specific order; sets are unordered.
- Not checking if the key exists, which returns an empty set but might be mistaken for an error.
redis
/* Wrong: Using SMEMBERS on a string key */ SET mykey "hello" SMEMBERS mykey /* Right: Use SMEMBERS only on set keys */ SADD myset "hello" SMEMBERS myset
Output
(error) WRONGTYPE Operation against a key holding the wrong kind of value
1) "hello"
Quick Reference
| Command | Description |
|---|---|
| SMEMBERS key | Returns all members of the set stored at key |
| SADD key member [member ...] | Adds one or more members to a set |
| SISMEMBER key member | Checks if a member exists in the set |
| SCARD key | Returns the number of members in the set |
Key Takeaways
SMEMBERS returns all members of a set stored at the given key in Redis.
The returned members are unordered; sets do not guarantee order.
Using SMEMBERS on a non-set key causes an error.
If the key does not exist, SMEMBERS returns an empty set.
Use SADD to add members before retrieving them with SMEMBERS.