Redis Command: SMEMBERS

Summary

Command NameSMEMBERS
UsageGet all members of a set
Group set
ACL Category@read
@set
@slow
Time ComplexityO(N)
FlagREADONLY
Arity2

Notes

  • Time complexity of this command is O(N), where N is the cardinality of the set.
  • Cardinality refers to the total number of members of a set.

Signature

SMEMBERS <key>

Usage

Get all the members of a set. We get the full list of all the members. This is the only proper command available to get items/members from a set.

Notes

  • SSCAN command can be used to serve a similar purpose.
  • Using SINTER or SUNION can give us the same result, if used with one argument. But that would not be a natural use of those commands.

Arguments

ParameterDescriptionNameType
<key>Name of the key of the setkeykey

Return Value

Return valueCase for the return valueType
Array of stringsOn success we get the list of all members of the listarray[string]
(empty array)If the key does not exist(empty array)
errorIf applied to the wrong data typeerror

Notes

  • If the command is applied to a key that is not a hash, then the following error is returned-
    (error) WRONGTYPE Operation against a key holding the wrong kind of value

Examples

Here are a few examples of the usage examples of the Redis SMEMBERS command-

# Redis SMEMBERS command examples

# Add members to set
127.0.0.1:6379> sadd bigboxset one two three "ninety nine" "twelve"
(integer) 5

# Check set members
127.0.0.1:6379> smembers bigboxset
1) "one"
2) "two"
3) "three"
4) "ninety nine"
5) "twelve"

# Add some more members
# existing members are ignored
127.0.0.1:6379> sadd bigboxset "new element" two "ninety nine"
(integer) 1

# Check set members
127.0.0.1:6379> smembers bigboxset
1) "one"
2) "two"
3) "three"
4) "ninety nine"
5) "twelve"
6) "new element"

# Use SMEMBERS on a key that does not exist
# Returns an empty array
127.0.0.1:6379> smembers nonexistingset
(empty array)

# Set a string key
127.0.0.1:6379> set bigboxstr 'url of the site is bigboxcode.com'
OK

# Try to use SMEMBERS on a string
# we get an error
127.0.0.1:6379> smembers bigboxstr
(error) WRONGTYPE Operation against a key holding the wrong kind of value

Code Implementations

Redis SMEMBERS command example implementation in Golang, NodeJS, Java, C#, PHP, Python, Ruby-

// Redis SMEMBERS command example in Golang

package main

import (
	"context"
	"fmt"

	"github.com/redis/go-redis/v9"
)

var rdb *redis.Client
var ctx context.Context

func init() {
	rdb = redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Username: "default",
		Password: "",
		DB:       0,
	})

	ctx = context.Background()
}

func main() {

	/**
	* Add members to set
	* Command: sadd bigboxset one two three "ninety nine" "twelve"
	* Result: (integer) 5
	 */
	saddResult, err := rdb.SAdd(ctx, "bigboxset", "one", "two", "three", "ninety nine", "twelve").Result()

	if err != nil {
		fmt.Println("Command: sadd bigboxset one two three "ninety nine" "twelve" | Error: " + err.Error())
	}

	fmt.Println("Command: sadd bigboxset one two three "ninety nine" "twelve" | Result: ", saddResult)

	/**
	* Check set members
	* Command: smembers bigboxset
	* Result:
	*      1) "one"
	*      2) "two"
	*      3) "three"
	*      4) "ninety nine"
	*      5) "twelve"
	 */
	smembersResult, err := rdb.SMembers(ctx, "bigboxset").Result()

	if err != nil {
		fmt.Println("Command: smembers bigboxset | Result: Error: " + err.Error())
	}

	fmt.Println("Command: smembers bigboxset | Result: ", smembersResult)

	/**
	* Add some more members
	* existing members are ignored
	* Command: sadd bigboxset "new element" two "ninety nine"
	* Result: (integer) 1
	 */
	saddResult, err = rdb.SAdd(ctx, "bigboxset", "new element", "two", "ninety nine").Result()

	if err != nil {
		fmt.Println("Command: sadd bigboxset "new element" two "ninety nine" | Error: " + err.Error())
	}

	fmt.Println("Command: sadd bigboxset "new element" two "ninety nine" | Result: ", saddResult)

	/**
	* Check set members
	* Command: smembers bigboxset
	* Result:
	*      1) "one"
	*      2) "two"
	*      3) "three"
	*      4) "ninety nine"
	*      5) "twelve"
	*      6) "new element"
	 */
	smembersResult, err = rdb.SMembers(ctx, "bigboxset").Result()

	if err != nil {
		fmt.Println("Command: smembers bigboxset | Result: Error: " + err.Error())
	}

	fmt.Println("Command: smembers bigboxset | Result: ", smembersResult)

	/**
	* Use SMEMBERS on a key that does not exist
	* Returns an empty array
	* Command: smembers nonexistingset
	* Result: (empty array)
	 */
	smembersResult, err = rdb.SMembers(ctx, "nonexistingset").Result()

	if err != nil {
		fmt.Println("Command: smembers nonexistingset | Result: Error: " + err.Error())
	}

	fmt.Println("Command: smembers nonexistingset | Result: ", smembersResult)

	/**
	* Set a string key
	* Command: set bigboxstr 'url of the site is bigboxcode.com'
	* Result: OK
	 */
	setResult, err := rdb.Set(ctx, "bigboxstr", "url of the site is bigboxcode.com", 0).Result()

	if err != nil {
		fmt.Println("Command: set bigboxstr 'url of the site is bigboxcode.com' | Error: " + err.Error())
	}

	fmt.Println("Command: set bigboxstr 'url of the site is bigboxcode.com' | Result: " + setResult)

	/**
	* Try to use SMEMBERS on a string
	* we get an error
	* Command: smembers bigboxstr
	* Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
	 */
	smembersResult, err = rdb.SMembers(ctx, "bigboxstr").Result()

	if err != nil {
		fmt.Println("Command: smembers bigboxstr | Result: Error: " + err.Error())
	}

	fmt.Println("Command: smembers bigboxstr | Result: ", smembersResult)

}

Output:

Command: sadd bigboxset one two three "ninety nine" "twelve" | Result:  5
Command: smembers bigboxset | Result:  [one two three ninety nine twelve]

Command: sadd bigboxset "new element" two "ninety nine" | Result:  1
Command: smembers bigboxset | Result:  [one two three ninety nine twelve new element]

Command: smembers nonexistingset | Result:  []

Command: set bigboxstr 'url of the site is bigboxcode.com' | Result: OK
Command: smembers bigboxstr | Result: Error: WRONGTYPE Operation against a key holding the wrong kind of value
Command: smembers bigboxstr | Result:  []

Notes

  • Use “SMembers” method from redis-go module.
  • Signature of the method is-
    SMembers(ctx context.Context, key string) *StringSliceCmd
// Redis SMEMBERS command example in JavaScript(NodeJS)

import { createClient } from "redis";

// Create redis client
const redisClient = createClient({
  url: "redis://default:@localhost:6379",
});

redisClient.on("error", (err) =>
  console.log("Error while connecting to Redis", err)
);

// Connect Redis client
await redisClient.connect();

/**
 * Add members to set
 * 
 * Command: sadd bigboxset one two three "ninety nine" "twelve"
 * Result: (integer) 5
 */
let commandResult = await redisClient.sAdd("bigboxset", [
  "one",
  "two",
  "three",
  "ninety nine",
  "twelve",
]);

console.log(
  'Command: sadd bigboxset one two three "ninety nine" "twelve" | Result: ' +
    commandResult
);

/**
 * Check set members
 * 
 * Command: smembers bigboxset
 * Result:
 *      1) "one"
 *      2) "two"
 *      3) "three"
 *      4) "ninety nine"
 *      5) "twelve"
 */
commandResult = await redisClient.sMembers("bigboxset");

console.log("Command: smembers bigboxset | Result: ", commandResult);

/**
 * Add some more members
 * existing members are ignored
 * 
 * Command: sadd bigboxset "new element" two "ninety nine"
 * Result: (integer) 1
 */
commandResult = await redisClient.sAdd("bigboxset", [
  "new element",
  "two",
  "ninety nine",
]);

console.log(
  'Command: sadd bigboxset "new element" two "ninety nine" | Result: ' +
    commandResult
);

/**
 * Check set members
 * 
 * Command: smembers bigboxset
 * Result:
 *      1) "one"
 *      2) "two"
 *      3) "three"
 *      4) "ninety nine"
 *      5) "twelve"
 *      6) "new element"
 */
commandResult = await redisClient.sMembers("bigboxset");

console.log("Command: smembers bigboxset | Result: ", commandResult);

/**
 * Use SMEMBERS on a key that does not exist
 * Returns an empty array
 * 
 * Command: smembers nonexistingset
 * Result: (empty array)
 */
commandResult = await redisClient.sMembers("nonexistingset");

console.log("Command: smembers nonexistingset | Result: ", commandResult);

/**
 * Set a string key
 * 
 * Command: set bigboxstr 'url of the site is bigboxcode.com'
 * Result: OK
 */
commandResult = await redisClient.set(
  "bigboxstr",
  "url of the site is bigboxcode.com"
);

console.log(
  "Command: set bigboxstr 'url of the site is bigboxcode.com' | Result: " +
    commandResult
);

/**
 * Try to use SMEMBERS on a string
 * we get an error
 * 
 * Command: smembers bigboxstr
 * Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
 */
try {
  commandResult = await redisClient.sMembers("bigboxstr");

  console.log("Command: smembers bigboxstr | Result: ", commandResult);
} catch (err) {
  console.log("Command: smembers bigboxstr | Error: ", err);
}

process.exit(0);

Output:

Command: sadd bigboxset one two three "ninety nine" "twelve" | Result: 5
Command: smembers bigboxset | Result:  [ 'one', 'two', 'three', 'ninety nine', 'twelve' ]

Command: sadd bigboxset "new element" two "ninety nine" | Result: 1
Command: smembers bigboxset | Result:  [ 'one', 'two', 'three', 'ninety nine', 'twelve', 'new element' ]

Command: smembers nonexistingset | Result:  []

Command: set bigboxstr 'url of the site is bigboxcode.com' | Result: OK
Command: smembers bigboxstr | Error:  [ErrorReply: WRONGTYPE Operation against a key holding the wrong kind of value]

Notes

  • Use the function “sMembers” of node-redis.
  • Signature of the method-
    function sMembers((key: RedisCommandArgument)
// Redis SMEMBERS command example in Java

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Set;

public class SMembers {
    public static void main(String[] args) {
        JedisPool jedisPool = new JedisPool("localhost", 6379);

        try (Jedis jedis = jedisPool.getResource()) {

            /**
             * Add members to set
             * Command: sadd bigboxset one two three "ninety nine" "twelve"
             * Result: (integer) 5
             */
            long saddResult = jedis.sadd("bigboxset", "one", "two", "three", "ninety nine", "twelve");

            System.out.println("Command: sadd bigboxset one two three "ninety nine" "twelve" | Result: " + saddResult);

            /**
             * Check set members
             * Command: smembers bigboxset
             * Result:
             *      1) "one"
             *      2) "two"
             *      3) "three"
             *      4) "ninety nine"
             *      5) "twelve"
             */
            Set<String> smembersResult = jedis.smembers("bigboxset");

            System.out.println("Command: smembers bigboxset | Result: " + smembersResult.toString());

            /**
             * Add some more members
             * existing members are ignored
             * Command: sadd bigboxset "new element" two "ninety nine"
             * Result: (integer) 1
             */
            saddResult = jedis.sadd("bigboxset", "new element", "two", "ninety nine");

            System.out.println("Command: sadd bigboxset "new element" two "ninety nine" | Result: " + saddResult);

            /**
             * Check set members
             * Command: smembers bigboxset
             * Result:
             *      1) "one"
             *      2) "two"
             *      3) "three"
             *      4) "ninety nine"
             *      5) "twelve"
             *      6) "new element"
             */
            smembersResult = jedis.smembers("bigboxset");

            System.out.println("Command: smembers bigboxset | Result: " + smembersResult.toString());

            /**
             * Use SMEMBERS on a key that does not exist
             * Returns an empty array
             * Command: smembers nonexistingset
             * Result: (empty array)
             */
            smembersResult = jedis.smembers("nonexistingset");

            System.out.println("Command: smembers nonexistingset | Result: " + smembersResult.toString());

            /**
             * Set a string key
             * Command: set bigboxstr 'url of the site is bigboxcode.com'
             * Result: OK
             */
            String setResult = jedis.set("bigboxstr", "url of the site is bigboxcode.com");

            System.out.println("Command: set bigboxstr 'url of the site is bigboxcode.com' | Result: " + setResult);

            /**
             * Try to use SMEMBERS on a string
             * we get an error
             * Command: smembers bigboxstr
             * Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
             */
            try {
                smembersResult = jedis.smembers("bigboxstr");

                System.out.println("Command: smembers bigboxstr | Result: " + smembersResult.toString());
            } catch (Exception e) {
                System.out.println("Command: smembers bigboxstr | Error: " + e.getMessage());
            }

        }
    }
}

Output:

Command: sadd bigboxset one two three "ninety nine" "twelve" | Result: 5
Command: smembers bigboxset | Result: [one, twelve, two, three, ninety nine]

Command: sadd bigboxset "new element" two "ninety nine" | Result: 1
Command: smembers bigboxset | Result: [one, twelve, new element, two, three, ninety nine]

Command: smembers nonexistingset | Result: []

Command: set bigboxstr 'url of the site is bigboxcode.com' | Result: OK
Command: smembers bigboxstr | Error: WRONGTYPE Operation against a key holding the wrong kind of value

Notes

  • Use method “smembers” from Jedis package.
  • The signature of the method is-
    public Set<String> smembers(final String key)
// Redis SADD command examples in C#

using StackExchange.Redis;


namespace SMembers
{
    internal class Program
    {
        static void Main(string[] args)
        {
            ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
            IDatabase rdb = redis.GetDatabase();

            /**
             * Add members to set
             * Command: sadd bigboxset one two three "ninety nine" "twelve"
             * Result: (integer) 5
             */
            long saddResult = rdb.SetAdd("bigboxset", new RedisValue[] { "one", "two", "three", "ninety nine", "twelve" });

            Console.WriteLine("Command: sadd bigboxset one two three "ninety nine" "twelve" | Result: " + saddResult);

            /**
             * Check set members
             * Command: smembers bigboxset
             * Result:
             *      1) "one"
             *      2) "two"
             *      3) "three"
             *      4) "ninety nine"
             *      5) "twelve"
             */
            RedisValue[] smembersResult = rdb.SetMembers("bigboxset");

            Console.WriteLine("Command: smembers bigboxset | Result: " + String.Join(",", smembersResult));

            /**
             * Add some more members
             * existing members are ignored
             * Command: sadd bigboxset "new element" two "ninety nine"
             * Result: (integer) 1
             */
            saddResult = rdb.SetAdd("bigboxset", new RedisValue[] { "new element", "two", "ninety nine" });

            Console.WriteLine("Command: sadd bigboxset "new element" two "ninety nine" | Result: " + saddResult);

            /**
             * Check set members
             * Command: smembers bigboxset
             * Result:
             *      1) "one"
             *      2) "two"
             *      3) "three"
             *      4) "ninety nine"
             *      5) "twelve"
             *      6) "new element"
             */
            smembersResult = rdb.SetMembers("bigboxset");

            Console.WriteLine("Command: smembers bigboxset | Result: " + String.Join(",", smembersResult));

            /**
             * Use SMEMBERS on a key that does not exist
             * Returns an empty array
             * Command: smembers nonexistingset
             * Result: (empty array)
             */
            smembersResult = rdb.SetMembers("nonexistingset");

            Console.WriteLine("Command: smembers nonexistingset | Result: " + String.Join(",", smembersResult));

            /**
             * Set a string key
             * Command: set bigboxstr 'url of the site is bigboxcode.com'
             * Result: OK
             */
            bool setResult = rdb.StringSet("bigboxstr", "url of the site is bigboxcode.com");

            Console.WriteLine("Command: set bigboxstr 'url of the site is bigboxcode.com' | Result: " + setResult);

            /**
             * Try to use SMEMBERS on a string
             * we get an error
             * Command: smembers bigboxstr
             * Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
             */
            try
            {
                smembersResult = rdb.SetMembers("bigboxstr");

                Console.WriteLine("Command: smembers bigboxstr | Result: " + String.Join(",", smembersResult));
            }
            catch (Exception e)
            {
                Console.WriteLine("Command: smembers bigboxstr | Error: " + e.Message);
            }

        }
    }
}

Output:

Command: sadd bigboxset one two three "ninety nine" "twelve" | Result: 5
Command: smembers bigboxset | Result: one,two,three,ninety nine,twelve

Command: sadd bigboxset "new element" two "ninety nine" | Result: 1
Command: smembers bigboxset | Result: one,two,three,ninety nine,twelve,new element

Command: smembers nonexistingset | Result:

Command: set bigboxstr 'url of the site is bigboxcode.com' | Result: True
Command: smembers bigboxstr | Error: WRONGTYPE Operation against a key holding the wrong kind of value

Notes

  • Use the method “SetMembers” from StackExchange.Redis.
  • Method signature-
    RedisValue[] SetMembers(RedisKey key, CommandFlags flags = CommandFlags.None)
<?php
// Redis SMEMBERS command example in PHP

require 'vendor/autoload.php';

// Connect to Redis
$redisClient = new PredisClient([
    'scheme' => 'tcp',
    'host' => 'localhost',
    'port' => 6379,
]);

/**
 * Add members to set
 * Command: sadd bigboxset one two three "ninety nine" "twelve"
 * Result: (integer) 5
 */
$commandResult = $redisClient->sadd("bigboxset", ["one", "two", "three", "ninety nine", "twelve"]);

echo "Command: sadd bigboxset one two three "ninety nine" "twelve" | Result: " . $commandResult . "n";

/**
 * Check set members
 * Command: smembers bigboxset
 * Result:
 *      1) "one"
 *      2) "two"
 *      3) "three"
 *      4) "ninety nine"
 *      5) "twelve"
 */
$commandResult = $redisClient->smembers("bigboxset");

echo "Command: smembers bigboxset | Result: ";
print_r($commandResult);

/**
 * Add some more members
 * existing members are ignored
 * Command: sadd bigboxset "new element" two "ninety nine"
 * Result: (integer) 1
 */
$commandResult = $redisClient->sadd("bigboxset", ["new element", "two", "ninety nine"]);

echo "Command: sadd bigboxset "new element" two "ninety nine" | Result: " . $commandResult . "n";

/**
 * Check set members
 * Command: smembers bigboxset
 * Result:
 *      1) "one"
 *      2) "two"
 *      3) "three"
 *      4) "ninety nine"
 *      5) "twelve"
 *      6) "new element"
 */
$commandResult = $redisClient->smembers("bigboxset");

echo "Command: smembers bigboxset | Result: ";
print_r($commandResult);

/**
 * Use SMEMBERS on a key that does not exist
 * Returns an empty array
 * Command: smembers nonexistingset
 * Result: (empty array)
 */
$commandResult = $redisClient->smembers("nonexistingset");

echo "Command: smembers nonexistingset | Result: ";
print_r($commandResult);

/**
 * Set a string key
 * Command: set bigboxstr 'url of the site is bigboxcode.com'
 * Result: OK
 */
$commandResult = $redisClient->set("bigboxstr", "url of the site is bigboxcode.com");

echo "Command: set bigboxstr 'url of the site is bigboxcode.com' | Result: " . $commandResult . "n";

/**
 * Try to use SMEMBERS on a string
 * we get an error
 * Command: smembers bigboxstr
 * Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
 */
try {
    $commandResult = $redisClient->smembers("bigboxstr");

    echo "Command: smembers bigboxstr | Result: ";
    print_r($commandResult);
} catch (Exception $e) {
    echo "Command: smembers bigboxstr | Error: " . $e->getMessage() . "n";
}

Output:

Command: sadd bigboxset one two three "ninety nine" "twelve" | Result: 5
Command: smembers bigboxset | Result: Array
(
    [0] => one
    [1] => two
    [2] => three
    [3] => ninety nine
    [4] => twelve
)

Command: sadd bigboxset "new element" two "ninety nine" | Result: 1
Command: smembers bigboxset | Result: Array
(
    [0] => one
    [1] => two
    [2] => three
    [3] => ninety nine
    [4] => twelve
    [5] => new element
)

Command: smembers nonexistingset | Result: Array
(
)

Command: set bigboxstr 'url of the site is bigboxcode.com' | Result: OK
Command: smembers bigboxstr | Error: WRONGTYPE Operation against a key holding the wrong kind of value

Notes

  • Use the method “smembers” of predis.
  • Signature of the method is-
    smembers(string $key): string[]
# Redis SMEMBERS command example in Python

import redis
import time

# Create Redis client
redisClient = redis.Redis(
    host="localhost", port=6379, username="default", password="", decode_responses=True
)


# Add members to set
# Command: sadd bigboxset one two three "ninety nine" "twelve"
# Result: (integer) 5
commandResult = redisClient.sadd(
    "bigboxset", "one", "two", "three", "ninety nine", "twelve"
)

print(
    'Command: sadd bigboxset one two three "ninety nine" "twelve" | Result: {}'.format(
        commandResult
    )
)

# Check set members
# Command: smembers bigboxset
# Result:
#      1) "one"
#      2) "two"
#      3) "three"
#      4) "ninety nine"
#      5) "twelve"
commandResult = redisClient.smembers("bigboxset")

print("Command: smembers bigboxset | Result: {}".format(commandResult))

# Add some more members
# existing members are ignored
# Command: sadd bigboxset "new element" two "ninety nine"
# Result: (integer) 1
commandResult = redisClient.sadd("bigboxset", "new element", "two", "ninety nine")

print(
    'Command: sadd bigboxset "new element" two "ninety nine" | Result: {}'.format(
        commandResult
    )
)

# Check set members
# Command: smembers bigboxset
# Result:
#      1) "one"
#      2) "two"
#      3) "three"
#      4) "ninety nine"
#      5) "twelve"
#      6) "new element"
commandResult = redisClient.smembers("bigboxset")

print("Command: smembers bigboxset | Result: {}".format(commandResult))

# Use SMEMBERS on a key that does not exist
# Returns an empty array
# Command: smembers nonexistingset
# Result: (empty array)
commandResult = redisClient.smembers("nonexistingset")

print("Command: smembers nonexistingset | Result: {}".format(commandResult))

# Set a string key
# Command: set bigboxstr 'url of the site is bigboxcode.com'
# Result: OK
commandResult = redisClient.set("bigboxstr", "url of the site is bigboxcode.com")

print(
    "Command: set bigboxstr 'url of the site is bigboxcode.com' | Result: {}".format(
        commandResult
    )
)

# Try to use SMEMBERS on a string
# we get an error
# Command: smembers bigboxstr
# Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
try:
    commandResult = redisClient.smembers("bigboxstr")

    print("Command: smembers bigboxstr | Result: {}".format(commandResult))
except Exception as error:
    print("Command: smembers bigboxstr | Error: ", error)

Output:

Command: sadd bigboxset one two three "ninety nine" "twelve" | Result: 5
Command: smembers bigboxset | Result: {'one', 'twelve', 'ninety nine', 'three', 'two'}

Command: sadd bigboxset "new element" two "ninety nine" | Result: 1
Command: smembers bigboxset | Result: {'one', 'twelve', 'new element', 'ninety nine', 'three', 'two'}

Command: smembers nonexistingset | Result: set()

Command: set bigboxstr 'url of the site is bigboxcode.com' | Result: True
Command: smembers bigboxstr | Error:  WRONGTYPE Operation against a key holding the wrong kind of value

Notes

  • Use method “smembers” from redis-py.
  • Signature of the method is –
    def smembers(self, name: str) -> Union[Awaitable[Set], Set]
# Redis SMEMBERS command example in Ruby

require 'redis'

redis = Redis.new(host: "localhost", port: 6379)


# Add members to set
# Command: sadd bigboxset one two three "ninety nine" "twelve"
# Result: (integer) 5
commandResult = redis.sadd(
    "bigboxset", ["one", "two", "three", "ninety nine", "twelve"]
)

print("Command: sadd bigboxset one two three "ninety nine" "twelve" | Result: ", commandResult, "n")

# Check set members
# Command: smembers bigboxset
# Result:
#      1) "one"
#      2) "two"
#      3) "three"
#      4) "ninety nine"
#      5) "twelve"
commandResult = redis.smembers("bigboxset")

print("Command: smembers bigboxset | Result: ", commandResult, "n")

# Add some more members
# existing members are ignored
# Command: sadd bigboxset "new element" two "ninety nine"
# Result: (integer) 1
commandResult = redis.sadd("bigboxset", ["new element", "two", "ninety nine"])

print("Command: sadd bigboxset "new element" two "ninety nine" | Result: ", commandResult, "n")

# Check set members
# Command: smembers bigboxset
# Result:
#      1) "one"
#      2) "two"
#      3) "three"
#      4) "ninety nine"
#      5) "twelve"
#      6) "new element"
commandResult = redis.smembers("bigboxset")

print("Command: smembers bigboxset | Result: ", commandResult, "n")

# Use SMEMBERS on a key that does not exist
# Returns an empty array
# Command: smembers nonexistingset
# Result: (empty array)
commandResult = redis.smembers("nonexistingset")

print("Command: smembers nonexistingset | Result: ", commandResult, "n")

# Set a string key
# Command: set bigboxstr 'url of the site is bigboxcode.com'
# Result: OK
commandResult = redis.set("bigboxstr", "url of the site is bigboxcode.com")

print(    "Command: set bigboxstr 'url of the site is bigboxcode.com' | Result: ", commandResult, "n")

# Try to use SMEMBERS on a string
# we get an error
# Command: smembers bigboxstr
# Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
begin
    commandResult = redis.smembers("bigboxstr")

    print("Command: smembers bigboxstr | Result: ", commandResult, "n")
rescue => e
    print("Command: smembers bigboxstr | Error: ", e, "n")
end

Output:

Command: sadd bigboxset one two three "ninety nine" "twelve" | Result: 5
Command: smembers bigboxset | Result: ["one", "two", "three", "ninety nine", "twelve"]

Command: sadd bigboxset "new element" two "ninety nine" | Result: 1
Command: smembers bigboxset | Result: ["one", "two", "three", "ninety nine", "twelve", "new element"]

Command: smembers nonexistingset | Result: []
Command: set bigboxstr 'url of the site is bigboxcode.com' | Result: OK
Command: smembers bigboxstr | Error: WRONGTYPE Operation against a key holding the wrong kind of value

Notes

  • Use method “smembers” from the redis-rb.
  • Signature of the method is-

    # @param [String] key
    # @return [Array<String>]

    def smembers(key)

Source Code

Use the following links to get the source code used in this article-

Related Commands

CommandDetails
SADD Command Details
SREM Command Details

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.