Summary
Command Name | MSETNX |
Usage | Set string values for multiple keys if not exist |
Group | string |
ACL Category | @write @string @slow |
Time Complexity | O(N) |
Flag | WRITE DENYOOM |
Arity | -3 |
Signature
MSETNX <key> <value> [<key> <value> … ]
Usage
Set multiple key values if the keys do not already exist. NX represents “Not exists”. This is a very useful command if we want to set multiple key/values only if they do not already exist.
Notes
- If any of the keys already exist then the full operation fails and none of the keys are set. Using this command either all keys are set, or none is set.
- This command is similar to the MSET command. The only difference is MSET command always sets the provided key/values, but this command checks key existence.
Arguments
Here is the description of what each part of the MSETMX command means in the above signature-
Parameter | Description | Name | Type |
---|---|---|---|
<key> | The key name | key | key |
<value> | The string value need to be saved for the key | value | string |
Notes
- Pairs of [<key> <value>] are passed to this MSETNX command.
- This MSETNX command accepts multiple pairs of [<key> <value>].
Return Value
List of values is returned for the provided keys.
Return value | Case for the return value |
---|---|
1 | When the operation is successful and all the keys are set (none of the keys already exists). |
0 | When the operation failed and none of the keys are set (if any of the keys already exists) |
Notes
- 0(zero) means none of the keys are set.
Examples
Here are a few examples of the MSETNX command usage-
# Redis MSETNX command examples
# Set 2 values if they do not already exists. Both are set successfully
127.0.0.1:6379> msetnx firstkey "first value" secondkey "second value"
(integer) 1
# Set 2 values. Returns 0 as "firstkey" already exists
127.0.0.1:6379> msetnx newkey "new value" firstkey "changed first value"
(integer) 0
# Check value, and it is not set
127.0.0.1:6379> get newkey
(nil)
# Check firstkey, and it has old value
127.0.0.1:6379> get firstkey
"first value"
# Pass same key multiple times
127.0.0.1:6379> msetnx newkey "new value" newkey "another new value"
(integer) 1
# newkey has the value that was set/provided later
127.0.0.1:6379> get newkey
"another new value"
Notes
- If the same key is set multiple times in the same MSETNX command, then the last value is kept for the key.
- The MSETNX 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 MSETNX 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() {
// Set 2 values if they do not already exists. Both are set successfully
// Command: msetnx firstkey "first value" secondkey "second value"
// Result: (integer) 1
commandResult, err := rdb.MSetNX(ctx, map[string]string{"firstkey": "first value", "secondkey": "second value"}).Result()
if err != nil {
fmt.Println("Command: msetnx firstkey "first value" secondkey "second value" | Error: " + err.Error())
}
fmt.Printf("Command: msetnx firstkey "first value" secondkey "second value" | Result: %vn", commandResult)
// Try to get values for 3 keys
// Command: mget firstkey secondkey
// Result:
// 1) "my first value"
// 2) "second value"
commandResults, err := rdb.MGet(ctx, "firstkey", "secondkey").Result()
if err != nil {
fmt.Println("Command: mget firstkey secondkey | Error: " + err.Error())
}
fmt.Println("Command: mget firstkey secondkey | Result:")
for _, val := range commandResults {
fmt.Println(val)
}
// # Set 2 values. Returns 0 as "firstkey" already exists
// Command: msetnx newkey "new value" firstkey "changed first value"
// Result: (integer) 0
commandResult, err = rdb.MSetNX(ctx, "newkey", "new value", "firstkey", "changed first value").Result()
if err != nil {
fmt.Println("Command: msetnx newkey "new value" firstkey "changed first value" | Error: " + err.Error())
}
fmt.Printf("Command: msetnx newkey "new value" firstkey "changed first value" | Result: %vn", commandResult)
// Check value, and it is not set
// Command: get newkey
// Result: (nil)
getCommandResult, err := rdb.Get(ctx, "newkey").Result()
if err != nil {
fmt.Println("Command: get newkey | Error: " + err.Error())
}
fmt.Println("Command: get newkey | Result: " + getCommandResult)
// Check firstkey, and it has old value
// Command: get firstkey
// Result: "first value"
getCommandResult, err = rdb.Get(ctx, "firstkey").Result()
if err != nil {
fmt.Println("Command: get firstkey | Error: " + err.Error())
}
fmt.Println("Command: get firstkey | Result: " + getCommandResult)
// Pass same key multiple times
// Command: msetnx newkey "new value" newkey "another new value"
// Result: (integer) 1
commandResult, err = rdb.MSetNX(ctx, "newkey", "new value", "newkey", "another new value").Result()
if err != nil {
fmt.Println("Command: msetnx newkey "new value" newkey "another new value" | Error: " + err.Error())
}
fmt.Printf("Command: msetnx newkey "new value" newkey "another new value" | Result: %vn", commandResult)
// newkey has the value that was set/provided later
// Command: get newkey
// Result: "another new value"
getCommandResult, err = rdb.Get(ctx, "newkey").Result()
if err != nil {
fmt.Println("Command: get newkey | Error: " + err.Error())
}
fmt.Println("Command: get newkey | Result: " + getCommandResult)
}
Output:
Command: msetnx firstkey "first value" secondkey "second value" | Result: true
Command: mget firstkey secondkey | Result:
first value
second value
Command: msetnx newkey "new value" firstkey "changed first value" | Result: false
Command: get newkey | Error: redis: nil
Command: get newkey | Result:
Command: get firstkey | Result: first value
Command: msetnx newkey "new value" newkey "another new value" | Result: true
Command: get newkey | Result: another new value
Notes
- We need to use the method “MsetNX” from the redis-go module, to use the Redis MSETNX command.
- The signature of the method is-
func (c cmdable) MSetNX(ctx context.Context, values …interface{}) *BoolCmd - We can pass the keys and values in one of the following ways-
- MSetNX(ctx, “key1”, “value1”, “key2”, “value2”)
- MSetNX(ctx, []string{“key1”, “value1”, “key2”, “value2”})
- MSetNX(ctx, map[string]interface{}{“key1”: “value1”, “key2”: “value2”})
// Redis MSETNX 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();
/**
* Set 2 values if they do not already exist. Both are set successfully
*
* Command: msetnx firstkey "first value" secondkey "second value"
* Result: (integer) 1
*/
let commandResult = await redisClient.mSetNX({ "firstkey": "first value", "secondkey": "second value" });
console.log("Command: msetnx firstkey "first value" secondkey "second value" | Result: " + commandResult);
/**
* Try to get values for 3 keys
*
* Command: mget firstkey secondkey
* Result:
* 1) "my first value"
* 2) "second value"
*/
commandResult = await redisClient.mGet(["firstkey", "secondkey"]);
console.log("Command: mget firstkey secondkey | Result: ", commandResult);
/**
* Set 2 values. Returns 0 as "firstkey" already exists
*
* Command: msetnx newkey "new value" firstkey "changed first value"
* Result: (integer) 0
*/
commandResult = await redisClient.mSetNX(["newkey", "new value", "firstkey", "changed first value"]);
console.log("Command: msetnx newkey "new value" firstkey "changed first value" | Result: " + commandResult);
/**
* Check value, and it is not set
*
* Command: get newkey
* Result: (nil)
*/
commandResult = await redisClient.get("newkey");
console.log("Command: get newkey | Result: " + commandResult);
/**
* Check firstkey, and it has old value
*
* Command: get firstkey
* Result: "first value"
*/
commandResult = await redisClient.get("firstkey");
console.log("Command: get firstkey | Result: " + commandResult);
/**
* Pass same key multiple times
*
* Command: msetnx newkey "new value" newkey "another new value"
* Result: (integer) 1
*/
commandResult = await redisClient.mSetNX(["newkey", "new value", "newkey", "another new value"]);
console.log("Command: msetnx newkey "new value" newkey "another new value" | Result: " + commandResult);
/**
* newkey has the value that was set/provided later
*
* Command: get newkey
* Result: "another new value"
*/
commandResult = await redisClient.get("newkey");
console.log("Command: get newkey | Result: " + commandResult);
process.exit(0);
Output:
Command: msetnx firstkey "first value" secondkey "second value" | Result: true
Command: mget firstkey secondkey | Result: [ 'first value', 'second value' ]
Command: msetnx newkey "new value" firstkey "changed first value" | Result: false
Command: get newkey | Result: null
Command: get firstkey | Result: first value
Command: msetnx newkey "new value" newkey "another new value" | Result: true
Command: get newkey | Result: another new value
Notes
- Use method “mSetNX” (or “MSETNX”) for the Redis MSETNX command usage.
- We can pass the key/value sets in the following ways-
- Array<[RedisCommandArgument, RedisCommandArgument]>
- Array<RedisCommandArgument>
- Record<string, RedisCommandArgument>
// Redis MSETNX example in Java
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.util.List;
public class Msetnx {
public static void main(String[] args) {
// Create connection pool
JedisPool jedisPool = new JedisPool("localhost", 6379);
try (Jedis jedis = jedisPool.getResource()) {
/**
* Set 2 values if they do not already exist. Both are set successfully
*
* Command: msetnx firstkey "first value" secondkey "second value"
* Result: (integer) 1
*/
long setCommandResult = jedis.msetnx("firstkey", "first value", "secondkey", "second value");
System.out.println("Command: msetnx firstkey "first value" secondkey "second value" | Result: " + setCommandResult);
/**
* Try to get values for 3 keys
*
* Command: mget firstkey secondkey
* Result:
* 1) "my first value"
* 2) "second value"
*/
List<String> resultList = jedis.mget("firstkey", "secondkey");
System.out.println("Command: mget firstkey secondkey | Result: ");
for (String item : resultList) {
System.out.println(item);
}
/**
* Set 2 values. Returns 0 as "firstkey" already exists
*
* Command: msetnx newkey "new value" firstkey "changed first value"
* Result: (integer) 0
*/
setCommandResult = jedis.msetnx("newkey", "new value", "firstkey", "changed first value");
System.out.println("Command: msetnx newkey "new value" firstkey "changed first value" | Result: " + setCommandResult);
/**
* Check value, and it is not set
*
* Command: get newkey
* Result: (nil)
*/
String getCommandResult = jedis.get("newkey");
System.out.println("Command: get newkey | Result: " + getCommandResult);
/**
* Check firstkey, and it has old value
*
* Command: get firstkey
* Result: "first value"
*/
getCommandResult = jedis.get("firstkey");
System.out.println("Command: get firstkey | Result: " + getCommandResult);
/**
* Pass same key multiple times
*
* Command: msetnx newkey "new value" newkey "another new value"
* Result: (integer) 1
*/
setCommandResult = jedis.msetnx("newkey", "new value", "newkey", "another new value");
System.out.println("Command: msetnx newkey "new value" newkey "another new value" | Result: " + setCommandResult);
/**
* newkey has the value that was set/provided later
*
* Command: get newkey
* Result: "another new value"
*/
getCommandResult = jedis.get("newkey");
System.out.println("Command: get newkey | Result: " + getCommandResult);
}
jedisPool.close();
}
}
Output:
Command: msetnx firstkey "first value" secondkey "second value" | Result: 1
Command: mget firstkey secondkey | Result:
first value
second value
Command: msetnx newkey "new value" firstkey "changed first value" | Result: 0
Command: get newkey | Result: null
Command: get firstkey | Result: first value
Command: msetnx newkey "new value" newkey "another new value" | Result: 1
Command: get newkey | Result: another new value
Notes
- The function to use here is – “msetnx”.
- Signature of the method is-
public long msetnx(final String… keysvalues)
using StackExchange.Redis;
namespace Msetnx
{
internal class Program
{
static void Main(string[] args)
{
ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
IDatabase rdb = redis.GetDatabase();
/**
* Set 2 values if they do not already exist. Both are set successfully
*
* Command: msetnx firstkey "first value" secondkey "second value"
* Result: (integer) 1
*/
KeyValuePair<RedisKey, RedisValue>[] keyValues = new KeyValuePair<RedisKey, RedisValue>[]
{
new KeyValuePair<RedisKey, RedisValue>("firstkey", "first val"),
new KeyValuePair<RedisKey, RedisValue>("secondkey", "second val"),
};
bool setCommandResult = rdb.StringSet(keyValues, When.NotExists);
Console.WriteLine("Command: msetnx firstkey "first value" secondkey "second value" | Result: " + setCommandResult);
/**
* Try to get values for 3 keys
*
* Command: mget firstkey secondkey
* Result:
* 1) "my first value"
* 2) "second value"
*/
RedisValue[] resultList = rdb.StringGet(new RedisKey[] { "firstkey", "secondkey" });
Console.WriteLine("Command: mget firstkey secondkey | Result: ");
foreach (var item in resultList)
{
Console.WriteLine(item);
}
/**
* Set 2 values. Returns 0 as "firstkey" already exists
*
* Command: msetnx newkey "new value" firstkey "changed first value"
* Result: (integer) 0
*/
keyValues = new KeyValuePair<RedisKey, RedisValue>[]
{
new KeyValuePair<RedisKey, RedisValue>("newkey", "new val"),
new KeyValuePair<RedisKey, RedisValue>("firstkey", "changed first value"),
};
setCommandResult = rdb.StringSet(keyValues, When.NotExists);
Console.WriteLine("Command: msetnx newkey "new value" firstkey "changed first value" | Result: " + setCommandResult);
/**
* Check value, and it is not set
*
* Command: get newkey
* Result: (nil)
*/
RedisValue getCommandResult = rdb.StringGet("newkey");
Console.WriteLine("Command: get newkey | Result: " + getCommandResult);
/**
* Check firstkey, and it has old value
*
* Command: get firstkey
* Result: "first value"
*/
getCommandResult = rdb.StringGet("firstkey");
Console.WriteLine("Command: get firstkey | Result: " + getCommandResult);
/**
* Pass same key multiple times
*
* Command: msetnx newkey "new value" newkey "another new value"
* Result: (integer) 1
*/
keyValues = new KeyValuePair<RedisKey, RedisValue>[]
{
new KeyValuePair<RedisKey, RedisValue>("newkey", "new value"),
new KeyValuePair<RedisKey, RedisValue>("newkey", "another new value"),
};
setCommandResult = rdb.StringSet(keyValues, When.NotExists);
Console.WriteLine("Command: msetnx newkey "new value" newkey "another new value" | Result: " + setCommandResult);
/**
* newkey has the value that was set/provided later
*
* Command: get newkey
* Result: "another new value"
*/
getCommandResult = rdb.StringGet("newkey");
Console.WriteLine("Command: get newkey | Result: " + getCommandResult);
}
}
}
Output:
Command: msetnx firstkey "first value" secondkey "second value" | Result: True
Command: mget firstkey secondkey | Result:
first val
second val
Command: msetnx newkey "new value" firstkey "changed first value" | Result: False
Command: get newkey | Result:
Command: get firstkey | Result: first val
Command: msetnx newkey "new value" newkey "another new value" | Result: True
Command: get newkey | Result: another new value
Notes
- Use the “StringSet” method for this, and pass the When.NotExists to the method.
- 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 MSETNX command example in PHP
require 'vendor/autoload.php';
// Connect to Redis
$redisClient = new PredisClient([
'scheme' => 'tcp',
'host' => 'localhost',
'port' => 6379,
]);
/**
* Set 2 values if they do not already exist. Both are set successfully
*
* Command: msetnx firstkey "first value" secondkey "second value"
* Result: (integer) 1
*/
$commandResult = $redisClient->msetnx(["firstkey" => "first value", "secondkey" => "second value"]);
echo "Command: msetnx firstkey "first value" secondkey "second value" | Result: " . $commandResult . "n";
/**
* Try to get values for 3 keys
*
* Command: mget firstkey secondkey
* Result:
* 1) "my first value"
* 2) "second value"
*/
$commandResult = $redisClient->mget("firstkey", "secondkey");
echo "Command: mget firstkey secondkey | Result: n";
print_r($commandResult);
/**
* Set 2 values. Returns 0 as "firstkey" already exists
*
* Command: msetnx newkey "new value" firstkey "changed first value"
* Result: (integer) 0
*/
$commandResult = $redisClient->msetnx(["newkey" => "new value", "firstkey" => "changed first value"]);
echo "Command: msetnx newkey "new value" firstkey "changed first value" | Result: " . $commandResult . "n";
/**
* Check value, and it is not set
*
* Command: get newkey
* Result: (nil)
*/
$commandResult = $redisClient->get("newkey");
echo "Command: get newkey | Result: " . $commandResult . "n";
/**
* Check firstkey, and it has old value
*
* Command: get firstkey
* Result: "first value"
*/
$commandResult = $redisClient->get("firstkey");
echo "Command: get firstkey | Result: " . $commandResult . "n";
/**
* Pass same key multiple times
*
* Command: msetnx newkey "new value" newkey "another new value"
* Result: (integer) 1
*/
$commandResult = $redisClient->msetnx(["newkey" => "new value", "newkey" => "another new value"]);
echo "Command: msetnx newkey "new value" newkey "another new value" | Result: " . $commandResult . "n";
/**
* newkey has the value that was set/provided later
*
* Command: get newkey
* Result: "another new value"
*/
$commandResult = $redisClient->get("newkey");
echo "Command: get newkey | Result: " . $commandResult . "n";
Output:
Command: msetnx firstkey "first value" secondkey "second value" | Result: 0
Command: mget firstkey secondkey | Result:
Array
(
[0] => first val
[1] => second val
)
Command: msetnx newkey "new value" firstkey "changed first value" | Result: 0
Command: get newkey | Result: another new value
Command: get firstkey | Result: first val
Command: msetnx newkey "new value" newkey "another new value" | Result: 0
Command: get newkey | Result: another new value
Notes
- Use the “msetnx” method of predis for the Redis MSETNX command. Pass an associative array of key/values to the method.
- This method has the following signature-
msetnx(array $dictionary): mixed
# Redis MSETNX command example in Python
import redis
import time
# Create Redis client
redisClient = redis.Redis(host='localhost', port=6379,
username='default', password='',
decode_responses=True)
# Set 2 values if they do not already exists. Both are set successfully
# Command: msetnx firstkey "first value" secondkey "second value"
# Result: (integer) 1
commandResult = redisClient.msetnx(
{"firstkey": "first value", "secondkey": "second value"})
print("Command: msetnx firstkey "first value" secondkey "second value" | Result: {}".format(commandResult))
# Try to get values for 3 keys
# Command: mget firstkey secondkey
# Result:
# 1) "my first value"
# 2) "second value"
commandResult = redisClient.mget("firstkey", "secondkey")
print("Command: mget firstkey secondkey | Result: {}".format(commandResult))
# Set 2 values. Returns 0 as "firstkey" already exists
# Command: msetnx newkey "new value" firstkey "changed first value"
# Result: (integer) 0
commandResult = redisClient.msetnx(
{"newkey": "new value", "firstkey": "changed first value"})
print("Command: msetnx newkey "new value" firstkey "changed first value" | Result: {}".format(commandResult))
# Check value, and it is not set
# Command: get newkey
# Result: (nil)
commandResult = redisClient.get("newkey")
print("Command: get newkey | Result: {}".format(commandResult))
# Check firstkey, and it has old value
# Command: get firstkey
# Result: "first value"
commandResult = redisClient.get("firstkey")
print("Command: get firstkey | Result: {}".format(commandResult))
# Pass same key multiple times
# Command: msetnx newkey "new value" newkey "another new value"
# Result: (integer) 1
commandResult = redisClient.msetnx(
{"newkey": "new value", "newkey": "another new value"})
print("Command: msetnx newkey "new value" newkey "another new value" | Result: {}".format(commandResult))
# newkey has the value that was set/provided later
# Command: get newkey
# Result: "another new value"
commandResult = redisClient.get("newkey")
print("Command: get newkey | Result: {}".format(commandResult))
Output:
Command: msetnx firstkey "first value" secondkey "second value" | Result: True
Command: mget firstkey secondkey | Result: ['first value', 'second value']
Command: msetnx newkey "new value" firstkey "changed first value" | Result: False
Command: get newkey | Result: None
Command: get firstkey | Result: first value
Command: msetnx newkey "new value" newkey "another new value" | Result: True
Command: get newkey | Result: another new value
Notes
- Use the “msetnx” method from redis-py package, for using the Redis MSETNX command. Pass a dictionary of key/value pairs to the “msetnx” method.
- Signature of the “mset” method is-
def msetnx(self, mapping: Mapping[AnyKeyT, EncodableT]) -> ResponseT:
# Redis MSETNX command example in Ruby
require 'redis'
redis = Redis.new(host: "localhost", port: 6379)
# Set 2 values if they do not already exists. Both are set successfully
# Command: msetnx firstkey "first value" secondkey "second value"
# Result: (integer) 1
commandResult = redis.mapped_msetnx(
{"firstkey" => "first value", "secondkey" => "second value"})
print("Command: msetnx firstkey "first value" secondkey "second value" | Result: ", commandResult, "n")
# Try to get values for 3 keys
# Command: mget firstkey secondkey
# Result:
# 1) "my first value"
# 2) "second value"
commandResult = redis.mapped_mget("firstkey", "secondkey")
print("Command: mget firstkey secondkey | Result: ", commandResult, "n")
# Set 2 values. Returns 0 as "firstkey" already exists
# Command: msetnx newkey "new value" firstkey "changed first value"
# Result: (integer) 0
commandResult = redis.mapped_msetnx(
{"newkey" => "new value", "firstkey" => "changed first value"})
print("Command: msetnx newkey "new value" firstkey "changed first value" | Result: ", commandResult, "n")
# Check value, and it is not set
# Command: get newkey
# Result: (nil)
commandResult = redis.get("newkey")
print("Command: get newkey | Result: ", commandResult, "n")
# Check firstkey, and it has old value
# Command: get firstkey
# Result: "first value"
commandResult = redis.get("firstkey")
print("Command: get firstkey | Result: ", commandResult, "n")
# Pass same key multiple times
# Command: msetnx newkey "new value" newkey "another new value"
# Result: (integer) 1
commandResult = redis.msetnx("newkey", "new value", "newkey", "another new value")
print("Command: msetnx newkey "new value" newkey "another new value" | Result: ", commandResult, "n")
# newkey has the value that was set/provided later
# Command: get newkey
# Result: "another new value"
commandResult = redis.get("newkey")
print("Command: get newkey | Result: ", commandResult, "n")
Output:
Command: msetnx firstkey "first value" secondkey "second value" | Result: true
Command: mget firstkey secondkey | Result: {"firstkey"=>"first value", "secondkey"=>"second value"}
Command: msetnx newkey "new value" firstkey "changed first value" | Result: false
Command: get newkey | Result:
Command: get firstkey | Result: first value
Command: msetnx newkey "new value" newkey "another new value" | Result: true
Command: get newkey | Result: another new value
Notes
- Use method “msetnx” for using the Redis MSETNX command in redis-rb, like – msetnx(“key1”, “value1”, “key2”, “value2”)
- We can also use the “mapped_msetnx” method and pass a hash to the method, like – mapped_msetnx({ “key1” => “value1”, “key2” => “value2” })
Source Code
Use the following links to get the source code used in this article-
Source Code of | Source Code Link |
---|---|
Command Examples | GitHub |
Golang Implementation | GitHub |
NodeJS Implementation | GitHub |
Java Implementation | GitHub |
C# Implementation | GitHub |
PHP Implementation | GitHub |
Python Implementation | GitHub |
Ruby Implementation | GitHub |
Related Commands
Command | Details |
---|---|
GET | Command Details |
GETDEL | Command Details |
MGET | Command Details |
SET | Command Details |
MSET | Command Details |