Redis Command: MSET [includes Golang, NodeJS, Java, C#, PHP, Python, Ruby examples]

Summary

Command NameMSET
UsageSet string values for multiple keys
Group string
ACL Category@write
@string
@slow
Time ComplexityO(N)
FlagWRITE
DENYOOM
Arity-3

Signature

MSET <key> <value> [<key> <value> … ]

Usage

Set string values for multiple keys. This is a very handy and useful command when we have a lot of string key/value to set.

Notes

  • If the value for a key already exists then the value will be replaced/overwritten, if the same key is used in MSET command. This is similar to the SET command.
  • If we want to stop/prevent replacing the existing key, and only set values if the key does not exist, then we have to use MSETNX command.

Arguments

Here is the description of what each part of the MSET command means in the above signature-

ParameterDescriptionNameType
<key>The key namekeykey
<value>The string value need to be saved for the keyvaluestring

Notes

  • Pairs of [<key> <value>] are passed to this MSET command.
  • This MSET command accepts multiple pairs of [<key> <value>].

Return Value

List of values is returned for the provided keys.

Return valueCase for the return value
OKAlways returns “OK”

Notes

  • MSET command does not fail. It always returns a successful (OK) response.

Examples

Here are a few examples of the MSET command usage-

# Redis MSET command examples

# Use MSET to set multiple values
127.0.0.1:6379> mset firstkey "first val" secondkey "second val" lastkey "last val"
OK

# Check value, and it is set properly
127.0.0.1:6379> get firstkey
"first val"

# Get multiple values with MGET to check the values
127.0.0.1:6379> mget firstkey secondkey lastkey
1) "first val"
2) "second val"
3) "last val"

# Set some new and existing keys
127.0.0.1:6379> mset newkey "some new value" firstkey "first value changed"
OK

# New key is set
127.0.0.1:6379> get newkey
"some new value"

# Existing key value is replaced
127.0.0.1:6379> get firstkey
"first value changed"

# Set the same key multiple times in the same MSET command
127.0.0.1:6379> mset commonkey "my val 1" commonkey "changed common val"
OK

# Check the value of commonkey
# The value which was set later is kept
127.0.0.1:6379> get commonkey
"changed common val"

Notes

  • If the same key is set multiple times in the same MSET command, then the last value is kept for the key. It works like this- the previous value(s) is set, but overwritten by the later value.
  • The MSET operation is atomic, so all the keys are set at the same time.

Code Implementations

Here are the usage examples of the Redis MSET command in different programming languages.

// Redis MSET 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() {

	// Use MSET to set multiple values
	// Command: mset firstkey "first val" secondkey "second val" lastkey "last val"
	// Result: OK
	commandResult, err := rdb.MSet(ctx, map[string]string{"firstkey": "first val", "secondkey": "second val", "lastkey": "last val"}).Result()

	if err != nil {
		fmt.Println("Command: mset firstkey "first val" secondkey "second val" lastkey "last val" | Error: " + err.Error())
	}

	fmt.Println("Command: mset firstkey "first val" secondkey "second val" lastkey "last val" | Result: " + commandResult)


	// Check value, and it is set properly
	// Command: get firstkey
	// Result: "first val"
	commandResult, err = rdb.Get(ctx, "firstkey").Result()

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

	fmt.Println("Command: get firstkey | Result: " + commandResult)


	// Get multiple values with MGET to check the values
	// Command: mget firstkey secondkey lastkey
	// Result: 
	//		1) "first val"
	//		2) "second val"
	//		3) "last val"
	commandResults, err := rdb.MGet(ctx, "firstkey", "secondkey", "lastkey").Result()

	if err != nil {
		fmt.Println("Command: mget firstkey secondkey lastkey | Error: " + err.Error())
	}

	fmt.Println("Command: mget firstkey secondkey lastkey | Result:")

	for _, val := range commandResults {
		fmt.Println(val)
	}


	// Set some new and existing keys
	// Command: mset newkey "some new value" firstkey "first value changed"
	// Result: OK
	commandResult, err = rdb.MSet(ctx, "newkey", "some new value", "firstkey", "first value changed").Result()

	if err != nil {
		fmt.Println("Command: mset newkey "some new value" firstkey "first value changed" | Error: " + err.Error())
	}

	fmt.Println("Command: mset newkey "some new value" firstkey "first value changed" | Result: " + commandResult)


	// New key is set
	// Command: get newkey
	// Result: "some new value"
	commandResult, err = rdb.Get(ctx, "newkey").Result()

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

	fmt.Println("Command: get newkey | Result: " + commandResult)


	// Existing key value is replaced
	// Command: get firstkey
	// Result: "first value changed"
	commandResult, err = rdb.Get(ctx, "firstkey").Result()

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

	fmt.Println("Command: get firstkey | Result: " + commandResult)


	// Set the same key multiple times in the same MSET command
	// Command: mset commonkey "my val 1" commonkey "changed common val"
	// Result: OK
	commandResult, err = rdb.MSet(ctx, []string{"commonkey", "my val 1", "commonkey", "changed common val"}).Result()

	if err != nil {
		fmt.Println("Command: mset commonkey "my val 1" commonkey "changed common val" | Error: " + err.Error())
	}

	fmt.Println("Command: mset commonkey "my val 1" commonkey "changed common val" | Result: " + commandResult)


	// Check the value of commonkey
	// The value which was set later is kept
	// Command: get commonkey
	// Result: "changed common val"
	commandResult, err = rdb.Get(ctx, "commonkey").Result()

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

	fmt.Println("Command: get commonkey | Result: " + commandResult)

}

Output:

Command: mset firstkey "first val" secondkey "second val" lastkey "last val" | Result: OK

Command: get firstkey | Result: first val

Command: mget firstkey secondkey lastkey | Result:
first val
second val
last val

Command: mset newkey "some new value" firstkey "first value changed" | Result: OK
Command: get newkey | Result: some new value
Command: get firstkey | Result: first value changed

Command: mset commonkey "my val 1" commonkey "changed common val" | Result: OK
Command: get commonkey | Result: changed common val

Notes

  • Use method “MSet” of the redis-go package for the Redis MGET command.
  • The signature of the “MGet” method is-
    MSet(ctx context.Context, values …interface{}) *StatusCmd
  • Use the method like below-
    • MSet(“key1”, “value1”, “key2”, “value2”)
    • MSet([]string{“key1”, “value1”, “key2”, “value2”})
    • MSet(map[string]interface{}{“key1”: “value1”, “key2”: “value2”})
// Redis MSET 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();

/**
 * Use MSET to set multiple values
 *
 * Command: mset firstkey "first val" secondkey "second val" lastkey "last val"
 * Result: OK
 */
let commandResult = await redisClient.mSet({ "firstkey": "first val", "secondkey": "second val", "lastkey": "last val" });

console.log("Command: mset firstkey "first val" secondkey "second val" lastkey "last val" | Result: " + commandResult);


/**
 * Check value, and it is set properly
 *
 * Command: get firstkey
 * Result: "first val"
 */
commandResult = await redisClient.get("firstkey");

console.log("Command: get firstkey | Result: " + commandResult);


/**
 * Get multiple values with MGET to check the values
 *
 * Command: mget firstkey secondkey lastkey
 * Result:
 *      1) "first val"
 *      2) "second val"
 *      3) "last val"
 */
commandResult = await redisClient.mGet(["firstkey", "secondkey", "lastkey"]);

console.log("Command: mget firstkey secondkey lastkey | Result: " + commandResult);


/**
 * Set some new and existing keys
 *
 * Command: mset newkey "some new value" firstkey "first value changed"
 * Result: OK
 */
commandResult = await redisClient.mSet(["newkey", "some new value", "firstkey", "first value changed"]);

console.log("Command: mset newkey "some new value" firstkey "first value changed" | Result: " + commandResult);


/**
 * New key is set
 *
 * Command: get newkey
 * Result: "some new value"
 */
commandResult = await redisClient.get("newkey");

console.log("Command: get newkey | Result: " + commandResult);


/**
 * Existing key value is replaced
 *
 * Command: get firstkey
 * Result: "first value changed"
 */
commandResult = await redisClient.get("firstkey");

console.log("Command: get firstkey | Result: " + commandResult);


/**
 * Set the same key multiple times in the same MSET command
 *
 * Command: mset commonkey "my val 1" commonkey "changed common val"
 * Result: OK
 */
commandResult = await redisClient.mSet([["commonkey", "my val 1"], ["commonkey", "changed common val"]]);

console.log("Command: commonkey "my val 1" commonkey "changed common val" | Result: " + commandResult);


/**
 * Check the value of commonkey
 * The value which was set later is kept
 *
 * Command: get commonkey
 * Result: "changed common val"
 */
commandResult = await redisClient.get("commonkey");

console.log("Command: get commonkey | Result: " + commandResult);


process.exit(0);

Output:

Command: mset firstkey "first val" secondkey "second val" lastkey "last val" | Result: OK
Command: get firstkey | Result: first val
Command: mget firstkey secondkey lastkey | Result: first val,second val,last val

Command: mset newkey "some new value" firstkey "first value changed" | Result: OK
Command: get newkey | Result: some new value
Command: get firstkey | Result: first value changed

Command: commonkey "my val 1" commonkey "changed common val" | Result: OK
Command: get commonkey | Result: changed common val

Notes

  • Use method “mSet” (or “MSET”) for the Redis MSET command usage.
  • We can pass the key/value sets in the following ways-
    • Array<[RedisCommandArgument, RedisCommandArgument]>
    • Array<RedisCommandArgument>
    • Record<string, RedisCommandArgument>
// Redis MSET example in Java

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

import java.util.List;

public class Mset {
    public static void main(String[] args) {
        // Create connection pool
        JedisPool jedisPool = new JedisPool("localhost", 6379);

        try (Jedis jedis = jedisPool.getResource()) {
            /**
             * Use MSET to set multiple values
             *
             * Command: mset firstkey "first val" secondkey "second val" lastkey "last val"
             * Result: OK
             */
            String commandResult = jedis.mset("firstkey", "first val", "secondkey", "second val", "lastkey", "last val");

            System.out.println("Command: mset firstkey "first val" secondkey "second val" lastkey "last val" | Result: " + commandResult);


            /**
             * Check value, and it is set properly
             *
             * Command: get firstkey
             * Result: "first val"
             */
            commandResult = jedis.get("firstkey");

            System.out.println("Command: get firstkey | Result: " + commandResult);


            /**
             * Get multiple values with MGET to check the values
             *
             * Command: mget firstkey secondkey lastkey
             * Result:
             *      1) "first val"
             *      2) "second val"
             *      3) "last val"
             */
            List<String> resultList = jedis.mget("firstkey", "secondkey", "lastkey");

            System.out.println("Command: mget firstkey secondkey lastkey | Result: ");

            for (String item : resultList) {
                System.out.println(item);
            }


            /**
             * Set some new and existing keys
             *
             * Command: mset newkey "some new value" firstkey "first value changed"
             * Result: OK
             */
            commandResult = jedis.mset("newkey", "some new value", "firstkey", "first value changed");

            System.out.println("Command: mset newkey "some new value" firstkey "first value changed" | Result: " + commandResult);


            /**
             * New key is set
             *
             * Command: get newkey
             * Result: "some new value"
             */
            commandResult = jedis.get("newkey");

            System.out.println("Command: get newkey | Result: " + commandResult);


            /**
             * Existing key value is replaced
             *
             * Command: get firstkey
             * Result: "first value changed"
             */
            commandResult = jedis.get("firstkey");

            System.out.println("Command: get firstkey | Result: " + commandResult);


            /**
             * Set the same key multiple times in the same MSET command
             *
             * Command: mset commonkey "my val 1" commonkey "changed common val"
             * Result: OK
             */
            commandResult = jedis.mset("commonkey", "my val 1", "commonkey", "changed common val");

            System.out.println("Command: commonkey "my val 1" commonkey "changed common val" | Result: " + commandResult);


            /**
             * Check the value of commonkey
             * The value which was set later is kept
             *
             * Command: get commonkey
             * Result: "changed common val"
             */
            commandResult = jedis.get("commonkey");

            System.out.println("Command: get commonkey | Result: " + commandResult);
        }

        jedisPool.close();
    }
}

Output:

Command: mset firstkey "first val" secondkey "second val" lastkey "last val" | Result: OK
Command: get firstkey | Result: first val

Command: mget firstkey secondkey lastkey | Result: 
first val
second val
last val

Command: mset newkey "some new value" firstkey "first value changed" | Result: OK
Command: get newkey | Result: some new value
Command: get firstkey | Result: first value changed

Command: commonkey "my val 1" commonkey "changed common val" | Result: OK
Command: get commonkey | Result: changed common val

Notes

  • Use the “mset” method of Jedis.
  • Signature of the method is-
    public String mset(final String… keysvalues)
// Redis MSET command examples in C#

using StackExchange.Redis;

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


            /**
             * Use MSET to set multiple values
             *
             * Command: mset firstkey "first val" secondkey "second val" lastkey "last val"
             * Result: OK
             */
            KeyValuePair<RedisKey, RedisValue>[] keyValues = new KeyValuePair<RedisKey, RedisValue>[]
                    {
                        new KeyValuePair<RedisKey, RedisValue>("firstkey", "first val"),
                        new KeyValuePair<RedisKey, RedisValue>("secondkey", "second val"),
                        new KeyValuePair<RedisKey, RedisValue>("lastkey", "last val")
                    };
            bool setCommandResult = rdb.StringSet(keyValues);
            Console.WriteLine("Command: mset firstkey "first val" secondkey "second val" lastkey "last val" | Result: " + setCommandResult);


            /**
             * Check value, and it is set properly
             *
             * Command: get firstkey
             * Result: "first val"
             */
            RedisValue getCommandResult = rdb.StringGet("firstkey");
            Console.WriteLine("Command: get firstkey | Result: " + getCommandResult);


            /**
             * Get multiple values with MGET to check the values
             *
             * Command: mget firstkey secondkey lastkey
             * Result:
             *      1) "first val"
             *      2) "second val"
             *      3) "last val"
             */
            RedisValue[] resultList = rdb.StringGet(new RedisKey[] { "firstkey", "secondkey", "lastkey" });
            Console.WriteLine("Command: mget firstkey secondkey lastkey | Result: ");

            foreach (var item in resultList)
            {
                Console.WriteLine(item);
            }


            /**
             * Set some new and existing keys
             *
             * Command: mset newkey "some new value" firstkey "first value changed"
             * Result: OK
             */
            keyValues = new KeyValuePair<RedisKey, RedisValue>[]
                    {
                        new KeyValuePair<RedisKey, RedisValue>("newkey", "some new value"),
                        new KeyValuePair<RedisKey, RedisValue>("firstkey", "first value changed"),
                    };
            setCommandResult = rdb.StringSet(keyValues);

            Console.WriteLine("Command: mset newkey "some new value" firstkey "first value changed" | Result: " + setCommandResult);


            /**
             * New key is set
             *
             * Command: get newkey
             * Result: "some new value"
             */
            getCommandResult = rdb.StringGet("newkey");

            Console.WriteLine("Command: get newkey | Result: " + getCommandResult);


            /**
             * Existing key value is replaced
             *
             * Command: get firstkey
             * Result: "first value changed"
             */
            getCommandResult = rdb.StringGet("firstkey");

            Console.WriteLine("Command: get firstkey | Result: " + getCommandResult);


            /**
             * Set the same key multiple times in the same MSET command
             *
             * Command: mset commonkey "my val 1" commonkey "changed common val"
             * Result: OK
             */
            keyValues = new KeyValuePair<RedisKey, RedisValue>[]
                    {
                        new KeyValuePair<RedisKey, RedisValue>("commonkey", "my val 1"),
                        new KeyValuePair<RedisKey, RedisValue>("commonkey", "changed common val"),
                    };
            setCommandResult = rdb.StringSet(keyValues);

            Console.WriteLine("Command: commonkey "my val 1" commonkey "changed common val" | Result: " + setCommandResult);


            /**
             * Check the value of commonkey
             * The value which was set later is kept
             *
             * Command: get commonkey
             * Result: "changed common val"
             */
            getCommandResult = rdb.StringGet("commonkey");

            Console.WriteLine("Command: get commonkey | Result: " + getCommandResult);
        }
    }
}

Output:

Command: mset firstkey "first val" secondkey "second val" lastkey "last val" | Result: True
Command: get firstkey | Result: first val
Command: mget firstkey secondkey lastkey | Result:
first val
second val
last val
Command: mset newkey "some new value" firstkey "first value changed" | Result: True
Command: get newkey | Result: some new value
Command: get firstkey | Result: first value changed
Command: commonkey "my val 1" commonkey "changed common val" | Result: True
Command: get commonkey | Result: changed common val

Notes

  • For using the MSET command, we can use the “StringSet” method of StackExchange.Redis.
  • “StringSet” is also used for setting single key/value.
  • For setting multiple keys/values this method has the following signature-
    bool StringSet(KeyValuePair[] values, When when = When.Always, CommandFlags flags = CommandFlags.None)
<?php
// Redis MSET command example in PHP

require 'vendor/autoload.php';

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


/**
 * Use MSET to set multiple values
 *
 * Command: mset firstkey "first val" secondkey "second val" lastkey "last val"
 * Result: OK
 */
$commandResult = $redisClient->mset(["firstkey" => "first val", "secondkey" => "second val", "lastkey" => "last val"]);

echo "Command: mset firstkey "first val" secondkey "second val" lastkey "last val" | Result: " . $commandResult . "n";


/**
 * Check value, and it is set properly
 *
 * Command: get firstkey
 * Result: "first val"
 */
$commandResult = $redisClient->get("firstkey");

echo "Command: get firstkey | Result: " . $commandResult . "n";


/**
 * Get multiple values with MGET to check the values
 *
 * Command: mget firstkey secondkey lastkey
 * Result:
 *      1) "first val"
 *      2) "second val"
 *      3) "last val"
 */
$resultList = $redisClient->mget("firstkey", "secondkey", "lastkey");

echo "Command: mget firstkey secondkey lastkey | Result: ";

foreach ($resultList as $item) {
    echo $item . "n";
}


/**
 * Set some new and existing keys
 *
 * Command: mset newkey "some new value" firstkey "first value changed"
 * Result: OK
 */
$commandResult = $redisClient->mset(["newkey" => "some new value", "firstkey" => "first value changed"]);

echo "Command: mset newkey "some new value" firstkey "first value changed" | Result: " . $commandResult . "n";


/**
 * New key is set
 *
 * Command: get newkey
 * Result: "some new value"
 */
$commandResult = $redisClient->get("newkey");

echo "Command: get newkey | Result: " . $commandResult . "n";


/**
 * Existing key value is replaced
 *
 * Command: get firstkey
 * Result: "first value changed"
 */
$commandResult = $redisClient->get("firstkey");

echo "Command: get firstkey | Result: " . $commandResult . "n";


/**
 * Set the same key multiple times in the same MSET command
 *
 * Command: mset commonkey "my val 1" commonkey "changed common val"
 * Result: OK
 */
$commandResult = $redisClient->mset(["commonkey" => "my val 1", "commonkey" => "changed common val"]);

echo "Command: commonkey "my val 1" commonkey "changed common val" | Result: " . $commandResult . "n";


/**
 * Check the value of commonkey
 * The value which was set later is kept
 *
 * Command: get commonkey
 * Result: "changed common val"
 */
$commandResult = $redisClient->get("commonkey");

echo "Command: get commonkey | Result: " . $commandResult . "n";

Output:

Command: mset firstkey "first val" secondkey "second val" lastkey "last val" | Result: OK
Command: get firstkey | Result: first val
Command: mget firstkey secondkey lastkey | Result: first val
second val
last val

Command: mset newkey "some new value" firstkey "first value changed" | Result: OK
Command: get newkey | Result: some new value
Command: get firstkey | Result: first value changed

Command: commonkey "my val 1" commonkey "changed common val" | Result: OK
Command: get commonkey | Result: changed common val

Notes

  • Use the “mset” method of predis for the Redis MSET command.
  • We need to pass an associative array of key/values to the method.
  • This method has the following signature-
    mset(array $dictionary): mixed
# Redis MSET command example in Python

import redis
import time

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


# Use MSET to set multiple values
# Command: mset firstkey "first val" secondkey "second val" lastkey "last val"
# Result: OK
commandResult = redisClient.mset(
    {"firstkey": "first val", "secondkey": "second val", "lastkey": "last val"})

print("Command: mset firstkey "first val" secondkey "second val" lastkey "last val" | Result: {}".format(commandResult))


# Check value, and it is set properly
# Command: get firstkey
# Result: "first val"
commandResult = redisClient.get("firstkey")

print("Command: get firstkey | Result: {}".format(commandResult))


# Get multiple values with MGET to check the values
# Command: mget firstkey secondkey lastkey
# Result:
#      1) "first val"
#      2) "second val"
#      3) "last val"
resultList = redisClient.mget("firstkey", "secondkey", "lastkey")

print("Command: mget firstkey secondkey lastkey | Result: {}".format(resultList))


# Set some new and existing keys
# Command: mset newkey "some new value" firstkey "first value changed"
# Result: OK
commandResult = redisClient.mset(
    {"newkey": "some new value", "firstkey": "first value changed"})

print("Command: mset newkey "some new value" firstkey "first value changed" | Result: {}".format(commandResult))


# New key is set
# Command: get newkey
# Result: "some new value"
commandResult = redisClient.get("newkey")

print("Command: get newkey | Result: {}".format(commandResult))


# Existing key value is replaced
# Command: get firstkey
# Result: "first value changed"
commandResult = redisClient.get("firstkey")

print("Command: get firstkey | Result: {}".format(commandResult))


# Set the same key multiple times in the same MSET command
# Command: mset commonkey "my val 1" commonkey "changed common val"
# Result: OK
commandResult = redisClient.mset(
    {"commonkey": "my val 1", "commonkey": "changed common val"})

print("Command: commonkey "my val 1" commonkey "changed common val" | Result: {}".format(commandResult))


# Check the value of commonkey
# The value which was set later is kept
# Command: get commonkey
# Result: "changed common val"
commandResult = redisClient.get("commonkey")

print("Command: get commonkey | Result: {}".format(commandResult))

Output:

Command: mset firstkey "first val" secondkey "second val" lastkey "last val" | Result: True
Command: get firstkey | Result: first val
Command: mget firstkey secondkey lastkey | Result: ['first val', 'second val', 'last val']

Command: mset newkey "some new value" firstkey "first value changed" | Result: True
Command: get newkey | Result: some new value
Command: get firstkey | Result: first value changed

Command: commonkey "my val 1" commonkey "changed common val" | Result: True
Command: get commonkey | Result: changed common val

Notes

  • Use the “mset” method from redis-py package, for using the Redis MSET command.
  • We need to pass a dictionary of key/value pairs to the “mset” method.
  • Signature of the “mset” method is-
    def mset(self, mapping: Mapping[AnyKeyT, EncodableT]) -> ResponseT
# Redis MSET command example in Ruby

require 'redis'

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


# Use MSET to set multiple values
# Command: mset firstkey "first val" secondkey "second val" lastkey "last val"
# Result: OK
commandResult = redis.mset("firstkey", "first val", "secondkey", "second val", "lastkey", "last val")

print("Command: mset firstkey "first val" secondkey "second val" lastkey "last val" | Result: ", commandResult, "n")


# Check value, and it is set properly
# Command: get firstkey
# Result: "first val"
commandResult = redis.get("firstkey")

print("Command: get firstkey | Result: ", commandResult, "n")


# Get multiple values with MGET to check the values
# Command: mget firstkey secondkey lastkey
# Result:
#      1) "first val"
#      2) "second val"
#      3) "last val"
commandResult = redis.mapped_mget("firstkey", "secondkey", "lastkey")

print("Command: mget firstkey secondkey lastkey | Result: ", commandResult, "n")


# Set some new and existing keys
# Command: mset newkey "some new value" firstkey "first value changed"
# Result: OK
commandResult = redis.mapped_mset({"newkey"=> "some new value", "firstkey"=> "first value changed"})

print("Command: mset newkey "some new value" firstkey "first value changed" | Result: ", commandResult, "n")


# New key is set
# Command: get newkey
# Result: "some new value"
commandResult = redis.get("newkey")

print("Command: get newkey | Result: ", commandResult, "n")


# Existing key value is replaced
# Command: get firstkey
# Result: "first value changed"
commandResult = redis.get("firstkey")

print("Command: get firstkey | Result: ", commandResult, "n")


# Set the same key multiple times in the same MSET command
# Command: mset commonkey "my val 1" commonkey "changed common val"
# Result: OK
commandResult = redis.mset("commonkey", "my val 1", "commonkey", "changed common val")

print("Command: commonkey "my val 1" commonkey "changed common val" | Result: ", commandResult, "n")


# Check the value of commonkey
# The value which was set later is kept
# Command: get commonkey
# Result: "changed common val"
commandResult = redis.get("commonkey")

print("Command: get commonkey | Result: ", commandResult, "n")

Output:

Command: mset firstkey "first val" secondkey "second val" lastkey "last val" | Result: OK
Command: get firstkey | Result: first val
Command: mget firstkey secondkey lastkey | Result: {"firstkey"=>"first val", "secondkey"=>"second val", "lastkey"=>"last val"}

Command: mset newkey "some new value" firstkey "first value changed" | Result: OK
Command: get newkey | Result: some new value
Command: get firstkey | Result: first value changed

Command: commonkey "my val 1" commonkey "changed common val" | Result: OK
Command: get commonkey | Result: changed common val

Notes

  • Use method “mset” for using the Redis MSET command in redis-rb, like – mset(“key1”, “value1”, “key2”, “value2”)
  • We can also use the “mapped_mset” method and pass a hash to the method, like – mapped_mset({ “key1” => “value1”, “key2” => “value2” })

Source Code

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

Related Commands

CommandDetails
GET Command Details
GETDEL Command Details
MGET Command Details
SET Command Details
MSETNX Command Details

Leave a Comment


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