VOOZH about

URL: https://redis.io/docs/latest/commands/set/

⇱ SET | Docs


{"acl_categories":["@write","@string","@slow"],"arguments":[{"display_text":"key","key_spec_index":0,"name":"key","type":"key"},{"display_text":"value","name":"value","type":"string"},{"arguments":[{"display_text":"nx","name":"nx","token":"NX","type":"pure-token"},{"display_text":"xx","name":"xx","token":"XX","type":"pure-token"},{"display_text":"ifeq-value","name":"ifeq-value","since":"8.4.0","token":"IFEQ","type":"string"},{"display_text":"ifne-value","name":"ifne-value","since":"8.4.0","token":"IFNE","type":"string"},{"display_text":"ifdeq-digest","name":"ifdeq-digest","since":"8.4.0","token":"IFDEQ","type":"integer"},{"display_text":"ifdne-digest","name":"ifdne-digest","since":"8.4.0","token":"IFDNE","type":"integer"}],"name":"condition","optional":true,"since":"2.6.12","type":"oneof"},{"display_text":"get","name":"get","optional":true,"since":"6.2.0","token":"GET","type":"pure-token"},{"arguments":[{"display_text":"seconds","name":"seconds","since":"2.6.12","token":"EX","type":"integer"},{"display_text":"milliseconds","name":"milliseconds","since":"2.6.12","token":"PX","type":"integer"},{"display_text":"unix-time-seconds","name":"unix-time-seconds","since":"6.2.0","token":"EXAT","type":"unix-time"},{"display_text":"unix-time-milliseconds","name":"unix-time-milliseconds","since":"6.2.0","token":"PXAT","type":"unix-time"},{"display_text":"keepttl","name":"keepttl","since":"6.0.0","token":"KEEPTTL","type":"pure-token"}],"name":"expiration","optional":true,"type":"oneof"}],"arity":-3,"categories":["docs","develop","stack","oss","rs","rc","oss","kubernetes","clients"],"command_flags":["write","denyoom"],"complexity":"O(1)","description":"Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.","duplicateOf":"head:data-ai-metadata","group":"string","key_specs":[{"RW":true,"access":true,"begin_search":{"spec":{"index":1},"type":"index"},"find_keys":{"spec":{"keystep":1,"lastkey":0,"limit":0},"type":"range"},"notes":"RW and ACCESS due to the optional `GET` argument","update":true,"variable_flags":true}],"location":"body","since":"1.0.0","syntax_fmt":"SET key value [NX | XX | IFEQ ifeq-value | IFNE ifne-value |\n IFDEQ ifdeq-digest | IFDNE ifdne-digest] [GET] [EX seconds |\n PX milliseconds | EXAT unix-time-seconds |\n PXAT unix-time-milliseconds | KEEPTTL]","title":"SET","tableOfContents":{"sections":[]},"codeExamples":[{"codetabsId":"set_and_get-stepset","description":"Foundational: Set the string value of a key using SET (creates key if needed, overwrites existing value, supports expiration options)","difficulty":"beginner","id":"set","languages":[{"clientId":"redis-py","clientName":"redis-py","id":"Python","langId":"python","panelId":"panel_Python_set_and_get-stepset"},{"id":"Node-js","panelId":"panel_Nodejs_set_and_get-stepset"},{"clientId":"jedis","clientName":"Jedis","id":"Java-Sync","langId":"java","panelId":"panel_Java-Sync_set_and_get-stepset"},{"clientId":"go-redis","clientName":"go-redis","id":"Go","langId":"go","panelId":"panel_Go_set_and_get-stepset"},{"id":"dotnet-Sync (SE-Redis)","panelId":"panel_Csharp-Sync (SERedis)_set_and_get-stepset"}]}]}

SET

SET key value [NX | XX | IFEQ ifeq-value | IFNE ifne-value |
 IFDEQ ifdeq-digest | IFDNE ifdne-digest] [GET] [EX seconds |
 PX milliseconds | EXAT unix-time-seconds |
 PXAT unix-time-milliseconds | KEEPTTL]
set(
 name: KeyT,
 value: EncodableT,
 ex: Optional[ExpiryT] = None,
 px: Optional[ExpiryT] = None,
 nx: bool = False,
 xx: bool = False,
 keepttl: bool = False,
 get: bool = False,
 exat: Optional[AbsExpiryT] = None,
 pxat: Optional[AbsExpiryT] = None,
 ifeq: Optional[Union[bytes, str]] = None,
 ifne: Optional[Union[bytes, str]] = None,
 ifdeq: Optional[str] = None,
 ifdne: Optional[str] = None
) β†’ ResponseT
SET(
 key: RedisArgument,
 value: RedisArgument | number,
 options?: SetOptions
) β†’ Any
set(
 key: byte[],
 value: byte[]
) β†’ String // simple-string-reply OK if SET was executed correctly, or null if the SET operation was not performed because the user specified the NX or XX option but the condition was not met.

set(
 key: byte[],
 value: byte[],
 params: SetParams // key if it already exists. EX|PX, expire time units: EX = seconds; PX = milliseconds
) β†’ String // simple-string-reply OK if SET was executed correctly, or null if the SET operation was not performed because the user specified the NX or XX option but the condition was not met.

set(
 key: String,
 value: String
) β†’ String // simple-string-reply OK if SET was executed correctly, or null if the SET operation was not performed because the user specified the NX or XX option but the condition was not met.

set(
 key: String,
 value: String,
 params: SetParams // key if it already exists. EX|PX, expire time units: EX = seconds; PX = milliseconds
) β†’ String // simple-string-reply OK if SET was executed correctly, or null if the SET operation was not performed because the user specified the NX or XX option but the condition was not met.
set(
 key: K, // the key.
 value: V // the value.
) β†’ String // String simple-string-reply OK if SET was executed correctly.

set(
 key: K, // the key.
 value: V, // the value.
 setArgs: SetArgs // the setArgs.
) β†’ String // String simple-string-reply OK if SET was executed correctly.
set(
 key: K, // the key.
 value: V // the value.
) β†’ RedisFuture<String> // String simple-string-reply OK if SET was executed correctly.

set(
 key: K, // the key.
 value: V, // the value.
 setArgs: SetArgs // the setArgs.
) β†’ RedisFuture<String> // String simple-string-reply OK if SET was executed correctly.
set(
 key: K, // the key.
 value: V // the value.
) β†’ Mono<String> // String simple-string-reply OK if SET was executed correctly.

set(
 key: K, // the key.
 value: V, // the value.
 setArgs: SetArgs // the setArgs.
) β†’ Mono<String> // String simple-string-reply OK if SET was executed correctly.
Set(
 ctx: context.Context,
 key: string,
 value: interface{},
 expiration: time.Duration
) β†’ *StatusCmd
StringSet(
 key: RedisKey,
 value: RedisValue,
 expiry: TimeSpan?, // The expiry to set.
 when: When // Which condition to set the value under (defaults to always).
) β†’ bool // true if the keys were set, false otherwise.

StringSet(
 key: RedisKey,
 value: RedisValue,
 expiry: TimeSpan?, // The expiry to set.
 when: When, // Which condition to set the value under (defaults to always).
 flags: CommandFlags // The flags to use for this operation.
) β†’ bool // true if the keys were set, false otherwise.

StringSet(
 key: RedisKey,
 value: RedisValue,
 expiry: TimeSpan?, // The expiry to set.
 keepTtl: bool,
 when: When, // Which condition to set the value under (defaults to always).
 flags: CommandFlags // The flags to use for this operation.
) β†’ bool // true if the keys were set, false otherwise.

StringSet(
 key: RedisKey,
 value: RedisValue,
 expiry: Expiration, // The expiry to set.
 when: ValueCondition, // Which condition to set the value under (defaults to always).
 flags: CommandFlags // The flags to use for this operation.
) β†’ bool // true if the keys were set, false otherwise.

StringSet(
 values: KeyValuePair<RedisKey, RedisValue>[], // The keys and values to set.
 when: When, // Which condition to set the value under (defaults to always).
 flags: CommandFlags // The flags to use for this operation.
) β†’ bool // true if the keys were set, false otherwise.
StringSet(
 key: RedisKey,
 value: RedisValue,
 expiry: TimeSpan?, // The expiry to set.
 when: When // Which condition to set the value under (defaults to always).
) β†’ bool // true if the keys were set, false otherwise.

StringSet(
 key: RedisKey,
 value: RedisValue,
 expiry: TimeSpan?, // The expiry to set.
 when: When, // Which condition to set the value under (defaults to always).
 flags: CommandFlags // The flags to use for this operation.
) β†’ bool // true if the keys were set, false otherwise.

StringSet(
 key: RedisKey,
 value: RedisValue,
 expiry: TimeSpan?, // The expiry to set.
 keepTtl: bool,
 when: When, // Which condition to set the value under (defaults to always).
 flags: CommandFlags // The flags to use for this operation.
) β†’ bool // true if the keys were set, false otherwise.

StringSet(
 key: RedisKey,
 value: RedisValue,
 expiry: Expiration, // The expiry to set.
 when: ValueCondition, // Which condition to set the value under (defaults to always).
 flags: CommandFlags // The flags to use for this operation.
) β†’ bool // true if the keys were set, false otherwise.

StringSet(
 values: KeyValuePair<RedisKey, RedisValue>[], // The keys and values to set.
 when: When, // Which condition to set the value under (defaults to always).
 flags: CommandFlags // The flags to use for this operation.
) β†’ bool // true if the keys were set, false otherwise.
set(
 $key: string,
 $value: Any,
 $expireResolution = null: Any,
 $expireTTL = null: Any,
 $flag = null: Any,
 $flagValue = null: Any
) β†’ Status|null
set(
 key: K,
 value: V
) β†’ (())
set(
 key: K,
 value: V
) β†’ (())
Available since:
Redis Open Source 1.0.0
Time complexity:
O(1)
ACL categories:
@write, @string, @slow,
Compatibility:
Redis Software and Redis Cloud compatibility

Set key to hold the string value. If key already holds a value, it is overwritten, regardless of its type. Any previous time to live associated with the key is discarded on successful SET operation.

Required arguments

Optional arguments

The following options modify the command's behavior. The condition options (NX, XX, IFEQ, IFNE, IFDEQ, IFDNE) are mutually exclusive, as are the expiration options (EX, PX, EXAT, PXAT, KEEPTTL).

Note: Since the SET command options can replace SETNX, SETEX, PSETEX, GETSET, it is possible that in future versions of Redis these commands will be deprecated and finally removed.

Examples

 
Foundational: Set the string value of a key using SET (creates key if needed, overwrites existing value, supports expiration options)
"""
Code samples for data structure store quickstart pages:
 https://redis.io/docs/latest/develop/get-started/data-store/
"""
import redis
r = redis.Redis(host="localhost", port=6379, db=0, decode_responses=True)
res = r.set("bike:1", "Process 134")
print(res)
# >>> True
res = r.get("bike:1")
print(res)
# >>> "Process 134"
import { createClient } from 'redis';
const client = createClient();
client.on('error', err => console.log('Redis Client Error', err));
await client.connect().catch(console.error);
await client.set('bike:1', 'Process 134');
const value = await client.get('bike:1');
console.log(value);
// returns 'Process 134'
await client.close();
packageio.redis.examples;importredis.clients.jedis.RedisClient;publicclass SetGetExample{publicvoidrun(){RedisClientjedis=RedisClient.create("redis://localhost:6379");Stringstatus=jedis.set("bike:1","Process 134");if("OK".equals(status))System.out.println("Successfully added a bike.");Stringvalue=jedis.get("bike:1");if(value!=null)System.out.println("The name of the bike is: "+value+".");jedis.close();}}
package example_commands_test
import (
	"context"
	"fmt"
	"github.com/redis/go-redis/v9"
)
func ExampleClient_Set_and_get() {
	ctx := context.Background()
	rdb := redis.NewClient(&redis.Options{
		Addr: "localhost:6379",
		Password: "", // no password docs
		DB: 0, // use default DB
	})
	err := rdb.Set(ctx, "bike:1", "Process 134", 0).Err()
	if err != nil {
		panic(err)
	}
	fmt.Println("OK")
	value, err := rdb.Get(ctx, "bike:1").Result()
	if err != nil {
		panic(err)
	}
	fmt.Printf("The name of the bike is %s", value)
}
using NRedisStack.Tests;
using StackExchange.Redis;
public class SetGetExample
{
 public void Run()
 {
 var muxer = ConnectionMultiplexer.Connect("localhost:6379");
 var db = muxer.GetDatabase();
 bool status = db.StringSet("bike:1", "Process 134");
 if (status)
 Console.WriteLine("Successfully added a bike.");
 var value = db.StringGet("bike:1");
 if (value.HasValue)
 Console.WriteLine("The name of the bike is: " + value + ".");
 }
}

Details

Hash digest

A hash digest is a fixed-size numerical representation of a string value, computed using the XXH3 hash algorithm. Redis uses this hash digest for efficient comparison operations without needing to compare the full string content. You can retrieve a key's hash digest using the DIGEST command, which returns it as a hexadecimal string that you can use with the IFDEQ and IFDNE options, and also the DELEX command's IFDEQ and IFDNE options.

Patterns

Note: The following pattern is discouraged in favor of the Redlock algorithm which is only a bit more complex to implement, but offers better guarantees and is fault tolerant.

The command SET resource-name anystring NX EX max-lock-time is a simple way to implement a locking system with Redis.

A client can acquire the lock if the above command returns OK (or retry after some time if the command returns Nil), and remove the lock just using DEL.

The lock will be auto-released after the expire time is reached.

It is possible to make this system more robust modifying the unlock schema as follows:

  • Instead of setting a fixed string, set a non-guessable large random string, called token.
  • Instead of releasing the lock with DEL, send a script that only removes the key if the value matches.

This avoids that a client will try to release the lock after the expire time deleting the key created by another client that acquired the lock later.

An example of unlock script would be similar to the following:

if redis.call("get",KEYS[1]) == ARGV[1]
then
 return redis.call("del",KEYS[1])
else
 return 0
end

The script should be called with EVAL ...script... 1 resource-name token-value

Redis Software and Redis Cloud compatibility

Redis
Software
Redis
Cloud
Notes
βœ… Standard
βœ… Standard

Return information

  • If GET was not specified, one of the following:
    • Null bulk string reply in the following two cases.
      • The key doesn’t exist and XX/IFEQ/IFDEQ was specified. The key was not created.
      • The key exists, and NX was specified or a specified IFEQ/IFNE/IFDEQ/IFDNE condition is false. The key was not set.
    • Simple string reply: OK: The key was set.
  • If GET was specified, one of the following:
  • If GET was not specified, one of the following:
    • Null reply in the following two cases.
      • The key doesn’t exist and XX/IFEQ/IFDEQ was specified. The key was not created.
      • The key exists, and NX was specified or a specified IFEQ/IFNE/IFDEQ/IFDNE condition is false. The key was not set.
    • Simple string reply: OK: The key was set.
  • If GET was specified, one of the following:
    • Null reply: The key didn't exist before the SET operation, whether the key was created of not.
    • Bulk string reply: The previous value of the key, whether the key was set or not.

History

  • Starting with Redis version 2.6.12: Added the EX, PX, NX and XX options.
  • Starting with Redis version 6.0.0: Added the KEEPTTL option.
  • Starting with Redis version 6.2.0: Added the GET, EXAT and PXAT option.
  • Starting with Redis version 7.0.0: Allowed the NX and GET options to be used together.
  • Starting with Redis version 8.4.0: Added 'IFEQ', 'IFNE', 'IFDEQ', 'IFDNE' options.