3 Ways to Return all Members of a Set in Redis

When working with Redis, we have multiple ways to return the members of a set. Here are 3 ways to return the members of a set in Redis.

The SMEMBERS Command

The most obvious way to do it is to use the SMEMBERS command. This command returns all the members of a set.

Example:

SMEMBERS animals

Result:

1) "Horse"
2) "Dog"
3) "Cat"
4) "Cow"
5) "Bird"
6) "Zebra"

Here, I returned all members of a set called animals. This set contains six members.

The SINTER Command

Another way to do it is to use the SINTER command. This command returns the members of the set resulting from the intersection of all the given sets. So it’s normally used against multiple sets. However, if we pass just one set, we’ll get all members of that set.

Example:

SINTER animals

Result:

1) "Horse"
2) "Dog"
3) "Cat"
4) "Cow"
5) "Bird"
6) "Zebra"

As expected, we get all members from the set.

The SSCAN Command

The SSCAN command can also output all members in a set.

Example:

SSCAN animals 0

Result:

1) "0"
2) 1) "Bird"
   2) "Horse"
   3) "Dog"
   4) "Cat"
   5) "Zebra"
   6) "Cow"

The output is slightly different to the previous commands. This command incrementally iterates over the members of the set. It’s a cursor based iterator. Therefore, with every call of the command, the server returns an updated cursor that the user needs to use as the cursor argument in the next call.

An iteration starts when the cursor is set to 0, and terminates when the cursor returned by the server is 0.

The SSCAN command works in the same way that the SCAN command works, except that SSCAN is to be used on sets (SCAN on the other hand, iterates the set of keys in the currently selected Redis database). See the Redis documentation for the SCAN command for a more detailed explanation and examples.