Redis Command: SREM

Summary

Command NameSREM
UsageRemove item(s) from set
Group set
ACL Category@write
@set
@fast
Time ComplexityO(N)
FlagWRITE
FAST
Arity-3

Notes

  • Time complexity of this command is O(N), where N is the elements to be removed.

Signature

SREM <key> <member> [ <member>]

Usage

Remove one or more items/members from a set.

Notes

  • If the member is not present in the set, then then it is ignored.
  • If the <key> does not exist, then it is treated like an empty set.

Arguments

ParameterDescriptionNameTypeMultiple
<key>Name of the key of the setkeykey
<member>Member of the set to removememberstringTrue

Return Value

Return valueCase for the return valueType
Number of removed itemsOn success we get the number of removed items.integer
0If the provided <key> does not exist.
or If none of the provided members exist.
integer
errorIf applied to the wrong data type.error

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 SREM command-

# Redis SREM command examples

# Add members to set
127.0.0.1:6379> sadd bigboxset nine eight seven six five four three two one
(integer) 9

# Check set members
127.0.0.1:6379> smembers bigboxset
1) "nine"
2) "eight"
3) "seven"
4) "six"
5) "five"
6) "four"
7) "three"
8) "two"
9) "one"

# Remove set member
127.0.0.1:6379> srem bigboxset eight
(integer) 1

# Check set members
127.0.0.1:6379> smembers bigboxset
1) "nine"
2) "seven"
3) "six"
4) "five"
5) "four"
6) "three"
7) "two"
8) "one"

# Remove set members
127.0.0.1:6379> srem bigboxset two four six someunknownitem
(integer) 3

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

# Try to remove from a non existing key
# SREM handles it as an empty array, and returns zero(0)
127.0.0.1:6379> srem nonexistingkey a b c
(integer) 0

# Set a string
127.0.0.1:6379> set bigboxstr "some string value for demo"
OK

# Try to use SREM on a string
# Returns error ans SREM can only be used a set
127.0.0.1:6379> srem bigboxstr "some"
(error) WRONGTYPE Operation against a key holding the wrong kind of value

Code Implementations

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

// Redis SREM 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 nine eight seven six five four three two one
	* Result: (integer) 9
	 */
	saddResult, err := rdb.SAdd(ctx, "bigboxset", "nine", "eight", "seven", "six", "five", "four", "three", "two", "one").Result()

	if err != nil {
		fmt.Println("Command: sadd bigboxset nine eight seven six five four three two one | Error: " + err.Error())
	}

	fmt.Println("Command: sadd bigboxset nine eight seven six five four three two one | Result: ", saddResult)

	/**
	* Check set members
	*
	* Command: smembers bigboxset
	* Result:
	*      1) "nine"
	*      2) "eight"
	*      3) "seven"
	*      4) "six"
	*      5) "five"
	*      6) "four"
	*      7) "three"
	*      8) "two"
	*      9) "one"
	 */
	smembersResult, err := rdb.SMembers(ctx, "bigboxset").Result()

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

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

	/**
	* Remove set member
	*
	* Command: srem bigboxset eight
	* Result: (integer) 1
	 */
	sremResult, err := rdb.SRem(ctx, "bigboxset", "eight").Result()

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

	fmt.Println("Command: srem bigboxset eight | Result: ", sremResult)

	/**
	* Check set members
	*
	* Command: smembers bigboxset
	* Result:
	*      1) "nine"
	*      2) "seven"
	*      3) "six"
	*      4) "five"
	*      5) "four"
	*      6) "three"
	*      7) "two"
	*      8) "one"
	 */
	smembersResult, err = rdb.SMembers(ctx, "bigboxset").Result()

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

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

	/**
	* Remove set members
	*
	* Command: srem bigboxset two four six someunknownitem
	* Result: (integer) 3
	 */
	sremResult, err = rdb.SRem(ctx, "bigboxset", "two", "four", "six", "someunknownitem").Result()

	if err != nil {
		fmt.Println("Command: srem bigboxset two four six someunknownitem | Error: " + err.Error())
	}

	fmt.Println("Command: srem bigboxset two four six someunknownitem | Result: ", sremResult)

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

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

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

	/**
	* Try to remove from a non existing key
	* SREM handles it as an empty array, and returns zero(0)
	*
	* Command: srem nonexistingkey a b c
	* Result: (integer) 0
	 */
	sremResult, err = rdb.SRem(ctx, "nonexistingkey", "a", "b", "c").Result()

	if err != nil {
		fmt.Println("Command: srem nonexistingkey a b c | Error: " + err.Error())
	}

	fmt.Println("Command: srem nonexistingkey a b c | Result: ", sremResult)

	/**
	* Set a string
	*
	* Command: set bigboxstr "some string value for demo"
	* Result: OK
	 */
	setResult, err := rdb.Set(ctx, "bigboxstr", "some string value for demo", 0).Result()

	if err != nil {
		fmt.Println("Command: set bigboxstr "some string value for demo" | Error: " + err.Error())
	}

	fmt.Println("Command: set bigboxstr "some string value for demo" | Result: " + setResult)

	/**
	* Try to use SREM on a string
	* Returns error ans SREM can only be used a set
	*
	* Command: srem bigboxstr "some"
	* Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
	 */
	sremResult, err = rdb.SRem(ctx, "bigboxstr", "some").Result()

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

	fmt.Println("Command: srem bigboxstr "some" | Result: ", sremResult)

}

Output:

Command: sadd bigboxset nine eight seven six five four three two one | Result:  9
Command: smembers bigboxset | Result:  [nine eight seven six five four three two one]

Command: srem bigboxset eight | Result:  1
Command: smembers bigboxset | Result:  [nine seven six five four three two one]

Command: srem bigboxset two four six someunknownitem | Result:  3
Command: smembers bigboxset | Result:  [nine seven five three one]

Command: srem nonexistingkey a b c | Result:  0

Command: set bigboxstr "some string value for demo" | Result: OK
Command: srem bigboxstr "some" | Error: WRONGTYPE Operation against a key holding the wrong kind of value
Command: srem bigboxstr "some" | Result:  0

Notes

  • Use “SRem” method from redis-go module.
  • Signature of the method is-
    SRem(ctx context.Context, key string, members ...interface{}) *IntCmd
// Redis SREM 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 nine eight seven six five four three two one
 * Result: (integer) 9
 */
let commandResult = await redisClient.sAdd("bigboxset", [
  "nine",
  "eight",
  "seven",
  "six",
  "five",
  "four",
  "three",
  "two",
  "one",
]);

console.log(
  "Command: sadd bigboxset nine eight seven six five four three two one | Result: " +
    commandResult
);

/**
 * Check set members
 *
 * Command: smembers bigboxset
 * Result:
 *      1) "nine"
 *      2) "eight"
 *      3) "seven"
 *      4) "six"
 *      5) "five"
 *      6) "four"
 *      7) "three"
 *      8) "two"
 *      9) "one"
 */
commandResult = await redisClient.sMembers("bigboxset");

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

/**
 * Remove set member
 *
 * Command: srem bigboxset eight
 * Result: (integer) 1
 */
commandResult = await redisClient.sRem("bigboxset", "eight");

console.log("Command: srem bigboxset eight | Result: " + commandResult);

/**
 * Check set members
 *
 * Command: smembers bigboxset
 * Result:
 *      1) "nine"
 *      2) "seven"
 *      3) "six"
 *      4) "five"
 *      5) "four"
 *      6) "three"
 *      7) "two"
 *      8) "one"
 */
commandResult = await redisClient.sMembers("bigboxset");

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

/**
 * Remove set members
 *
 * Command: srem bigboxset two four six someunknownitem
 * Result: (integer) 3
 */
commandResult = await redisClient.sRem("bigboxset", [
  "two",
  "four",
  "six",
  "someunknownitem",
]);

console.log(
  "Command: srem bigboxset two four six someunknownitem | Result: " +
    commandResult
);

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

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

/**
 * Try to remove from a non existing key
 * SREM handles it as an empty array, and returns zero(0)
 *
 * Command: srem nonexistingkey a b c
 * Result: (integer) 0
 */
commandResult = await redisClient.sRem("nonexistingkey", ["a", "b", "c"]);

console.log("Command: srem nonexistingkey a b c | Result: " + commandResult);

/**
 * Set a string
 *
 * Command: set bigboxstr "some string value for demo"
 * Result: OK
 */
commandResult = await redisClient.set(
  "bigboxstr",
  "some string value for demo"
);

console.log(
  'Command: set bigboxstr "some string value for demo" | Result: ' +
    commandResult
);

/**
 * Try to use SREM on a string
 * Returns error ans SREM can only be used a set
 *
 * Command: srem bigboxstr "some"
 * Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
 */
try {
  commandResult = await redisClient.sRem("bigboxstr", "some");

  console.log('Command: srem bigboxstr "some" | Result: ' + commandResult);
} catch (err) {
  console.log('Command: srem bigboxstr "some" | Error: ', err);
}

process.exit(0);

Output:

Command: sadd bigboxset nine eight seven six five four three two one | Result: 9
Command: smembers bigboxset | Result: nine,eight,seven,six,five,four,three,two,one

Command: srem bigboxset eight | Result: 1
Command: smembers bigboxset | Result: nine,seven,six,five,four,three,two,one

Command: srem bigboxset two four six someunknownitem | Result: 3
Command: smembers bigboxset | Result: nine,seven,five,three,one

Command: srem nonexistingkey a b c | Result: 0

Command: set bigboxstr "some string value for demo" | Result: OK
Command: srem bigboxstr "some" | Error:  [ErrorReply: WRONGTYPE Operation against a key holding the wrong kind of value]

Notes

  • Use the function “sRem” of node-redis.
  • Signature of the method-
    function sRem(key: RedisCommandArgument, members: RedisCommandArgument | Array<RedisCommandArgument>)
// Redis SREM command example in Java

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

import java.util.Set;

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

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

            /**
             * Add members to set
             *
             * Command: sadd bigboxset nine eight seven six five four three two one
             * Result: (integer) 9
             */
            long saddResult = jedis.sadd("bigboxset", "nine", "eight", "seven", "six", "five", "four", "three", "two", "one");

            System.out.println("Command: sadd bigboxset nine eight seven six five four three two one | Result: " + saddResult);

            /**
             * Check set members
             *
             * Command: smembers bigboxset
             * Result:
             *      1) "nine"
             *      2) "eight"
             *      3) "seven"
             *      4) "six"
             *      5) "five"
             *      6) "four"
             *      7) "three"
             *      8) "two"
             *      9) "one"
             */
            Set<String> smembersResult = jedis.smembers("bigboxset");

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

            /**
             * Remove set member
             *
             * Command: srem bigboxset eight
             * Result: (integer) 1
             */
            long sremResult = jedis.srem("bigboxset", "eight");

            System.out.println("Command: srem bigboxset eight | Result: " + sremResult);

            /**
             * Check set members
             *
             * Command: smembers bigboxset
             * Result:
             *      1) "nine"
             *      2) "seven"
             *      3) "six"
             *      4) "five"
             *      5) "four"
             *      6) "three"
             *      7) "two"
             *      8) "one"
             */
            smembersResult = jedis.smembers("bigboxset");

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

            /**
             * Remove set members
             *
             * Command: srem bigboxset two four six someunknownitem
             * Result: (integer) 3
             */
            sremResult = jedis.srem("bigboxset", "two", "four", "six", "someunknownitem");

            System.out.println("Command: srem bigboxset two four six someunknownitem | Result: " + sremResult);

            /**
             * Check set members
             *
             * Command: smembers bigboxset
             * Result:
             *      1) "nine"
             *      2) "seven"
             *      3) "five"
             *      4) "three"
             *      5) "one"
             */
            smembersResult = jedis.smembers("bigboxset");

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

            /**
             * Try to remove from a non existing key
             * SREM handles it as an empty array, and returns zero(0)
             *
             * Command: srem nonexistingkey a b c
             * Result: (integer) 0
             */
            sremResult = jedis.srem("nonexistingkey", "a", "b", "c");

            System.out.println("Command: srem nonexistingkey a b c | Result: " + sremResult);

            /**
             * Set a string
             *
             * Command: set bigboxstr "some string value for demo"
             * Result: OK
             */
            String setResult = jedis.set("bigboxstr", "some string value for demo");

            System.out.println("Command: set bigboxstr "some string value for demo" | Result: " + setResult);

            /**
             * Try to use SREM on a string
             * Returns error ans SREM can only be used a set
             *
             * Command: srem bigboxstr "some"
             * Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
             */
            try {
                sremResult = jedis.srem("bigboxstr", "some");

                System.out.println("Command: srem bigboxstr "some" | Result: " + sremResult);
            } catch (Exception e) {
                System.out.println("Command: srem bigboxstr "some" | Error: " + e.getMessage());
            }
        }
    }
}

Output:

Command: sadd bigboxset nine eight seven six five four three two one | Result: 9
Command: smembers bigboxset | Result: [nine, six, four, one, seven, five, three, two, eight]

Command: srem bigboxset eight | Result: 1
Command: smembers bigboxset | Result: [nine, six, four, one, seven, five, three, two]

Command: srem bigboxset two four six someunknownitem | Result: 3
Command: smembers bigboxset | Result: [nine, one, seven, five, three]

Command: srem nonexistingkey a b c | Result: 0

Command: set bigboxstr "some string value for demo" | Result: OK
Command: srem bigboxstr "some" | Error: WRONGTYPE Operation against a key holding the wrong kind of value

Notes

  • Use method “srem” from Jedis package.
  • The signature of the method is-
    public long srem(final String key, final String... members)
// Redis SREM command examples in C#

using StackExchange.Redis;
using System.Collections.Generic;


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

            /**
             * Add members to set
             *
             * Command: sadd bigboxset nine eight seven six five four three two one
             * Result: (integer) 9
             */
            long saddResult = rdb.SetAdd("bigboxset", new RedisValue[] { "nine", "eight", "seven", "six", "five", "four", "three", "two", "one" });

            Console.WriteLine("Command: sadd bigboxset nine eight seven six five four three two one | Result: " + saddResult);

            /**
             * Check set members
             *
             * Command: smembers bigboxset
             * Result:
             *      1) "nine"
             *      2) "eight"
             *      3) "seven"
             *      4) "six"
             *      5) "five"
             *      6) "four"
             *      7) "three"
             *      8) "two"
             *      9) "one"
             */
            RedisValue[] smembersResult = rdb.SetMembers("bigboxset");

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

            /**
             * Remove set member
             *
             * Command: srem bigboxset eight
             * Result: (integer) 1
             */
            bool sremResult = rdb.SetRemove("bigboxset", "eight");

            Console.WriteLine("Command: srem bigboxset eight | Result: " + sremResult);

            /**
             * Check set members
             *
             * Command: smembers bigboxset
             * Result:
             *      1) "nine"
             *      2) "seven"
             *      3) "six"
             *      4) "five"
             *      5) "four"
             *      6) "three"
             *      7) "two"
             *      8) "one"
             */
            smembersResult = rdb.SetMembers("bigboxset");

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

            /**
             * Remove set members
             *
             * Command: srem bigboxset two four six someunknownitem
             * Result: (integer) 3
             */
            long sremResultMultiple = rdb.SetRemove("bigboxset", new RedisValue[] { "two", "four", "six", "someunknownitem" });

            Console.WriteLine("Command: srem bigboxset two four six someunknownitem | Result: " + sremResultMultiple);

            /**
             * Check set members
             *
             * Command: smembers bigboxset
             * Result:
             *      1) "nine"
             *      2) "seven"
             *      3) "five"
             *      4) "three"
             *      5) "one"
             */
            smembersResult = rdb.SetMembers("bigboxset");

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

            /**
             * Try to remove from a non existing key
             * SREM handles it as an empty array, and returns zero(0)
             *
             * Command: srem nonexistingkey a b c
             * Result: (integer) 0
             */
            sremResultMultiple = rdb.SetRemove("nonexistingkey", new RedisValue[] { "a", "b", "c" });

            Console.WriteLine("Command: srem nonexistingkey a b c | Result: " + sremResultMultiple);

            /**
             * Set a string
             *
             * Command: set bigboxstr "some string value for demo"
             * Result: OK
             */
            bool setResult = rdb.StringSet("bigboxstr", "some string value for demo");

            Console.WriteLine("Command: set bigboxstr "some string value for demo" | Result: " + setResult);

            /**
             * Try to use SREM on a string
             * Returns error ans SREM can only be used a set
             *
             * Command: srem bigboxstr "some"
             * Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
             */
            try
            {
                sremResult = rdb.SetRemove("bigboxstr", "some");

                Console.WriteLine("Command: srem bigboxstr "some" | Result: " + sremResult);
            }
            catch (Exception e)
            {
                Console.WriteLine("Command: srem bigboxstr "some" | Error: " + e.Message);
            }
        }
    }
}

Output:

Command: sadd bigboxset nine eight seven six five four three two one | Result: 9
Command: smembers bigboxset | Result: nine,eight,seven,six,five,four,three,two,one

Command: srem bigboxset eight | Result: True
Command: smembers bigboxset | Result: nine,seven,six,five,four,three,two,one

Command: srem bigboxset two four six someunknownitem | Result: 3
Command: smembers bigboxset | Result: nine,seven,five,three,one

Command: srem nonexistingkey a b c | Result: 0

Command: set bigboxstr "some string value for demo" | Result: True
Command: srem bigboxstr "some" | Error: WRONGTYPE Operation against a key holding the wrong kind of value

Notes

  • Use the method “SetRemove” from StackExchange.Redis.
  • Method signatures-
    • bool SetRemove(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None)
    • long SetRemove(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None)
<?php
// Redis SREM 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 nine eight seven six five four three two one
 * Result: (integer) 9
 */
$commandResult = $redisClient->sadd("bigboxset", ["nine", "eight", "seven", "six", "five", "four", "three", "two", "one"]);

echo "Command: sadd bigboxset nine eight seven six five four three two one | Result: " . $commandResult . "n";

/**
 * Check set members
 *
 * Command: smembers bigboxset
 * Result:
 *      1) "nine"
 *      2) "eight"
 *      3) "seven"
 *      4) "six"
 *      5) "five"
 *      6) "four"
 *      7) "three"
 *      8) "two"
 *      9) "one"
 */
$commandResult = $redisClient->smembers("bigboxset");

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

/**
 * Remove set member
 *
 * Command: srem bigboxset eight
 * Result: (integer) 1
 */
$commandResult = $redisClient->srem("bigboxset", "eight");

echo "Command: srem bigboxset eight | Result: " . $commandResult . "n";

/**
 * Check set members
 *
 * Command: smembers bigboxset
 * Result:
 *      1) "nine"
 *      2) "seven"
 *      3) "six"
 *      4) "five"
 *      5) "four"
 *      6) "three"
 *      7) "two"
 *      8) "one"
 */
$commandResult = $redisClient->smembers("bigboxset");

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

/**
 * Remove set members
 *
 * Command: srem bigboxset two four six someunknownitem
 * Result: (integer) 3
 */
$commandResult = $redisClient->srem("bigboxset", ["two", "four", "six", "someunknownitem"]);

echo "Command: srem bigboxset two four six someunknownitem | Result: " . $commandResult . "n";

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

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

/**
 * Try to remove from a non existing key
 * SREM handles it as an empty array, and returns zero(0)
 *
 * Command: srem nonexistingkey a b c
 * Result: (integer) 0
 */
$commandResult = $redisClient->srem("nonexistingkey", ["a", "b", "c"]);

echo "Command: srem nonexistingkey a b c | Result: " . $commandResult . "n";

/**
 * Set a string
 *
 * Command: set bigboxstr "some string value for demo"
 * Result: OK
 */
$commandResult = $redisClient->set("bigboxstr", "some string value for demo");

echo "Command: set bigboxstr "some string value for demo" | Result: " . $commandResult . "n";

/**
 * Try to use SREM on a string
 * Returns error ans SREM can only be used a set
 *
 * Command: srem bigboxstr "some"
 * Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
 */
try {
    $commandResult = $redisClient->srem("bigboxstr", "some");

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

Output:

Command: sadd bigboxset nine eight seven six five four three two one | Result: 9
Command: smembers bigboxset | Result:Array
(
    [0] => nine
    [1] => eight
    [2] => seven
    [3] => six
    [4] => five
    [5] => four
    [6] => three
    [7] => two
    [8] => one
)

Command: srem bigboxset eight | Result: 1
Command: smembers bigboxset | Result:Array
(
    [0] => nine
    [1] => seven
    [2] => six
    [3] => five
    [4] => four
    [5] => three
    [6] => two
    [7] => one
)

Command: srem bigboxset two four six someunknownitem | Result: 3
Command: smembers bigboxset | Result: Array
(
    [0] => nine
    [1] => seven
    [2] => five
    [3] => three
    [4] => one
)

Command: srem nonexistingkey a b c | Result: 0

Command: set bigboxstr "some string value for demo" | Result: OK
Command: srem bigboxstr "some" | Error: WRONGTYPE Operation against a key holding the wrong kind of value

Notes

  • Use the method “srem” of predis.
  • Signature of the method is-
    srem(string $key, array|string $member): int
# Redis SREM 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 nine eight seven six five four three two one
# Result: (integer) 9
commandResult = redisClient.sadd("bigboxset", "nine", "eight", "seven", "six", "five", "four", "three", "two", "one")

print("Command: sadd bigboxset nine eight seven six five four three two one | Result: {}".format(commandResult))

# Check set members
# Command: smembers bigboxset
# Result:
#      1) "nine"
#      2) "eight"
#      3) "seven"
#      4) "six"
#      5) "five"
#      6) "four"
#      7) "three"
#      8) "two"
#      9) "one"
commandResult = redisClient.smembers("bigboxset")

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

# Remove set member
# Command: srem bigboxset eight
# Result: (integer) 1
commandResult = redisClient.srem("bigboxset", "eight")

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

# Check set members
# Command: smembers bigboxset
# Result:
#      1) "nine"
#      2) "seven"
#      3) "six"
#      4) "five"
#      5) "four"
#      6) "three"
#      7) "two"
#      8) "one"
commandResult = redisClient.smembers("bigboxset")

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

# Remove set members
# Command: srem bigboxset two four six someunknownitem
# Result: (integer) 3
commandResult = redisClient.srem("bigboxset", "two", "four", "six", "someunknownitem")

print("Command: srem bigboxset two four six someunknownitem | Result: {}".format(commandResult))

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

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

# Try to remove from a non existing key
# SREM handles it as an empty array, and returns zero(0)
# Command: srem nonexistingkey a b c
# Result: (integer) 0
commandResult = redisClient.srem("nonexistingkey", "a", "b", "c")

print("Command: srem nonexistingkey a b c | Result: {}".format(commandResult))

# Set a string
# Command: set bigboxstr "some string value for demo"
# Result: OK
commandResult = redisClient.set("bigboxstr", "some string value for demo")

print("Command: set bigboxstr "some string value for demo" | Result: {}".format(commandResult))

# Try to use SREM on a string
# Returns error ans SREM can only be used a set
# Command: srem bigboxstr "some"
# Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
try:
    commandResult = redisClient.srem("bigboxstr", "some")

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

Output:

Command: sadd bigboxset nine eight seven six five four three two one | Result: 9
Command: smembers bigboxset | Result: {'five', 'nine', 'two', 'one', 'three', 'eight', 'four', 'seven', 'six'}

Command: srem bigboxset eight | Result: 1
Command: smembers bigboxset | Result: {'five', 'nine', 'two', 'one', 'three', 'four', 'seven', 'six'}

Command: srem bigboxset two four six someunknownitem | Result: 3
Command: smembers bigboxset | Result: {'five', 'nine', 'one', 'three', 'seven'}

Command: srem nonexistingkey a b c | Result: 0

Command: set bigboxstr "some string value for demo" | Result: True
Command: srem bigboxstr "some" | Error:  WRONGTYPE Operation against a key holding the wrong kind of value

Notes

  • Use method “srem” from redis-py.
  • Signature of the method is –
    def srem(self, name: str, *values: FieldT) -> Union[Awaitable[int], int]
# Redis SREM command example in Ruby

require 'redis'

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


# Add members to set
# Command: sadd bigboxset nine eight seven six five four three two one
# Result: (integer) 9
commandResult = redis.sadd("bigboxset", ["nine", "eight", "seven", "six", "five", "four", "three", "two", "one"])

print("Command: sadd bigboxset nine eight seven six five four three two one | Result: ", commandResult, "n")

# Check set members
# Command: smembers bigboxset
# Result:
#      1) "nine"
#      2) "eight"
#      3) "seven"
#      4) "six"
#      5) "five"
#      6) "four"
#      7) "three"
#      8) "two"
#      9) "one"
commandResult = redis.smembers("bigboxset")

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

# Remove set member
# Command: srem bigboxset eight
# Result: (integer) 1
commandResult = redis.srem("bigboxset", "eight")

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

# Check set members
# Command: smembers bigboxset
# Result:
#      1) "nine"
#      2) "seven"
#      3) "six"
#      4) "five"
#      5) "four"
#      6) "three"
#      7) "two"
#      8) "one"
commandResult = redis.smembers("bigboxset")

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

# Remove set members
# Command: srem bigboxset two four six someunknownitem
# Result: (integer) 3
commandResult = redis.srem("bigboxset", ["two", "four", "six", "someunknownitem"])

print("Command: srem bigboxset two four six someunknownitem | Result: ", commandResult, "n")

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

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

# Try to remove from a non existing key
# SREM handles it as an empty array, and returns zero(0)
# Command: srem nonexistingkey a b c
# Result: (integer) 0
commandResult = redis.srem("nonexistingkey", ["a", "b", "c"])

print("Command: srem nonexistingkey a b c | Result: ", commandResult, "n")

# Set a string
# Command: set bigboxstr "some string value for demo"
# Result: OK
commandResult = redis.set("bigboxstr", "some string value for demo")

print("Command: set bigboxstr "some string value for demo" | Result: ", commandResult, "n")

# Try to use SREM on a string
# Returns error ans SREM can only be used a set
# Command: srem bigboxstr "some"
# Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
begin
    commandResult = redis.srem("bigboxstr", "some")

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

Output:

Command: sadd bigboxset nine eight seven six five four three two one | Result: 9
Command: smembers bigboxset | Result: ["nine", "eight", "seven", "six", "five", "four", "three", "two", "one"]

Command: srem bigboxset eight | Result: 1
Command: smembers bigboxset | Result: ["nine", "seven", "six", "five", "four", "three", "two", "one"]

Command: srem bigboxset two four six someunknownitem | Result: 3
Command: smembers bigboxset | Result: ["nine", "seven", "five", "three", "one"]

Command: srem nonexistingkey a b c | Result: 0

Command: set bigboxstr "some string value for demo" | Result: OK
Command: srem bigboxstr "some" | Error: WRONGTYPE Operation against a key holding the wrong kind of value

Notes

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

    # @param [String] key
    # @param [String, Array<String>] member one member, or array of members
    # @return [Integer] The number of members that were successfully removed

    def srem(key, *members)

Source Code

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

Related Commands

CommandDetails
SADD Command Details
SMEMBERS Command Details

Leave a Comment


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