Redis Strings
Introduction to Redis strings
-
APPEND v2.0.0 @write @string @fastAppends a string to the value of a key. Creates the key if it doesn't exist. O(1). The amortized time complexity is O(1) assuming the appended value is small and the already present value is of any size, since the dynamic string library used by Redis will double the free space available on every reallocation.
-
DECR v1.0.0 @write @string @fastDecrements the integer value of a key by one. Uses 0 as initial value if the key doesn't exist. O(1)
-
DECRBY v1.0.0 @write @string @fastDecrements a number from the integer value of a key. Uses 0 as initial value if the key doesn't exist. O(1)
-
DELEX v8.4.0 @write @string @fastConditionally removes the specified key based on value or digest comparison. O(1) for IFEQ/IFNE, O(N) for IFDEQ/IFDNE where N is the length of the string value.
-
DIGEST v8.4.0 @read @string @fastReturns the XXH3 hash of a string value. O(N) where N is the length of the string value.
-
GET v1.0.0 @read @string @fastReturns the string value of a key. O(1)
-
GETDEL v6.2.0 @write @string @fastReturns the string value of a key after deleting the key. O(1)
-
GETEX v6.2.0 @write @string @fastReturns the string value of a key after setting its expiration time. O(1)
-
GETRANGE v2.4.0 @read @string @slowReturns a substring of the string stored at a key. O(N) where N is the length of the returned string. The complexity is ultimately determined by the returned length, but because creating a substring from an existing string is very cheap, it can be considered O(1) for small strings.
-
GETSET v1.0.0 @write @string @fastReturns the previous string value of a key after setting it to a new value. O(1)
-
INCR v1.0.0 @write @string @fastIncrements the integer value of a key by one. Uses 0 as initial value if the key doesn't exist. O(1)
-
INCRBY v1.0.0 @write @string @fastIncrements the integer value of a key by a number. Uses 0 as initial value if the key doesn't exist. O(1)
-
INCRBYFLOAT v2.6.0 @write @string @fastIncrement the floating point value of a key by a number. Uses 0 as initial value if the key doesn't exist. O(1)
-
INCREX v8.8.0 @write @string @fastIncrements the numeric value of a key by a number and sets its expiration time. Uses 0 as initial value if the key doesn't exist. O(1)
-
LCS v7.0.0 @read @string @slowFinds the longest common substring. O(N*M) where N and M are the lengths of s1 and s2, respectively
-
MGET v1.0.0 @read @string @fastAtomically returns the string values of one or more keys. O(N) where N is the number of keys to retrieve.
-
MSET v1.0.1 @write @string @slowAtomically creates or modifies the string values of one or more keys. O(N) where N is the number of keys to set.
-
MSETEX v8.4.0 @write @string @slowAtomically sets multiple string keys with a shared expiration in a single operation. Supports flexible argument parsing where condition and expiration flags can appear in any order. O(N) where N is the number of keys to set.
-
MSETNX v1.0.1 @write @string @slowAtomically modifies the string values of one or more keys only when all keys don't exist. O(N) where N is the number of keys to set.
-
PSETEX v2.6.0 @write @string @slowSets both string value and expiration time in milliseconds of a key. The key is created if it doesn't exist. O(1)
-
SET v1.0.0 @write @string @slowSets the string value of a key, ignoring its type. The key is created if it doesn't exist. O(1)
-
SETEX v2.0.0 @write @string @slowSets the string value and expiration time of a key. Creates the key if it doesn't exist. O(1)
-
SETNX v1.0.0 @write @string @fastSet the string value of a key only when the key doesn't exist. O(1)
-
SETRANGE v2.2.0 @write @string @slowOverwrites a part of a string value with another by an offset. Creates the key if it doesn't exist. O(1), not counting the time taken to copy the new string in place. Usually, this string is very small so the amortized complexity is O(1). Otherwise, complexity is O(M) with M being the length of the value argument.
-
STRLEN v2.2.0 @read @string @fastReturns the length of a string value. O(1)
-
SUBSTR v1.0.0 @read @string @slowReturns a substring from a string value. O(N) where N is the length of the returned string. The complexity is ultimately determined by the returned length, but because creating a substring from an existing string is very cheap, it can be considered O(1) for small strings.
Redis strings store sequences of bytes, including text, serialized objects, and binary arrays. As such, strings are the simplest type of value you can associate with a Redis key. They're often used for caching, but they support additional functionality that lets you implement counters and perform bitwise operations, too.
Since Redis keys are strings, when we use the string type as a value too, we are mapping a string to another string. The string data type is useful for a number of use cases, like caching HTML fragments or pages.
> SET bike:1 Deimos OK > GET bike:1 "Deimos"
res1 = r.set("bike:1", "Deimos")
print(res1) # True
res2 = r.get("bike:1")
print(res2) # Deimos
"""
Code samples for String doc pages:
https://redis.io/docs/latest/develop/data-types/strings/
"""
import redis
r = redis.Redis(decode_responses=True)
res1 = r.set("bike:1", "Deimos")
print(res1) # True
res2 = r.get("bike:1")
print(res2) # Deimos
# Recreate the bike:1 key so this example runs on its own.
r.set("bike:1", "Deimos")
res3 = r.set("bike:1", "bike", nx=True)
print(res3) # None
print(r.get("bike:1")) # Deimos
res4 = r.set("bike:1", "bike", xx=True)
print(res4) # True
r.set("bike:1", "Deimos")
res9 = r.set("bike:1", "Ares", ifeq="Deimos")
print(res9) # True
res10 = r.set("bike:1", "Zeus", ifeq="Deimos")
print(res10) # None
print(r.get("bike:1")) # Ares
res11 = r.delex("bike:1", ifeq="Deimos")
print(res11) # 0
res12 = r.delex("bike:1", ifeq="Ares")
print(res12) # 1
res5 = r.mset({"bike:1": "Deimos", "bike:2": "Ares", "bike:3": "Vanth"})
print(res5) # True
res6 = r.mget(["bike:1", "bike:2", "bike:3"])
print(res6) # ['Deimos', 'Ares', 'Vanth']
r.set("total_crashes", 0)
res7 = r.incr("total_crashes")
print(res7) # 1
res8 = r.incrby("total_crashes", 10)
print(res8) # 11
-
Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.
-
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
-
set(
const res1 = await client.set("bike:1", "Deimos");
console.log(res1); // OK
const res2 = await client.get("bike:1");
console.log(res2); // Deimos
import assert from 'assert';
import { createClient } from 'redis';
const client = createClient();
await client.connect();
const res1 = await client.set("bike:1", "Deimos");
console.log(res1); // OK
const res2 = await client.get("bike:1");
console.log(res2); // Deimos
// Recreate the bike:1 key so this example runs on its own.
await client.set("bike:1", "Deimos");
const res3 = await client.set("bike:1", "bike", {'NX': true});
console.log(res3); // null
console.log(await client.get("bike:1")); // Deimos
const res4 = await client.set("bike:1", "bike", {'XX': true});
console.log(res4); // OK
await client.set("bike:1", "Deimos");
const res9 = await client.set("bike:1", "Ares", {
condition: 'IFEQ', matchValue: "Deimos"
});
console.log(res9); // OK
const res10 = await client.set("bike:1", "Zeus", {
condition: 'IFEQ', matchValue: "Deimos"
});
console.log(res10); // null
console.log(await client.get("bike:1")); // Ares
const res11 = await client.delEx("bike:1", {
condition: 'IFEQ', matchValue: "Deimos"
});
console.log(res11); // 0
const res12 = await client.delEx("bike:1", {
condition: 'IFEQ', matchValue: "Ares"
});
console.log(res12); // 1
const res5 = await client.mSet([
["bike:1", "Deimos"],
["bike:2", "Ares"],
["bike:3", "Vanth"]
]);
console.log(res5); // OK
const res6 = await client.mGet(["bike:1", "bike:2", "bike:3"]);
console.log(res6); // ['Deimos', 'Ares', 'Vanth']
await client.set("total_crashes", 0);
const res7 = await client.incr("total_crashes");
console.log(res7); // 1
const res8 = await client.incrBy("total_crashes", 10);
console.log(res8); // 11
String res1 = jedis.set("bike:1", "Deimos");
System.out.println(res1); // OK
String res2 = jedis.get("bike:1");
System.out.println(res2); // Deimos
package io.redis.examples;
import redis.clients.jedis.UnifiedJedis;
import redis.clients.jedis.params.SetParams;
import redis.clients.jedis.util.CompareCondition;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class StringExample {
public void run() {
try (UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379")) {
String res1 = jedis.set("bike:1", "Deimos");
System.out.println(res1); // OK
String res2 = jedis.get("bike:1");
System.out.println(res2); // Deimos
// Recreate the bike:1 key so this example runs on its own.
jedis.set("bike:1", "Deimos");
Long res3 = jedis.setnx("bike:1", "bike");
System.out.println(res3); // 0 (because key already exists)
System.out.println(jedis.get("bike:1")); // Deimos (value is unchanged)
String res4 = jedis.set("bike:1", "bike", SetParams.setParams().xx()); // set the value to "bike" if it
// already
// exists
System.out.println(res4); // OK
jedis.set("bike:1", "Deimos");
String res9 = jedis.set("bike:1", "Ares",
SetParams.setParams().condition(CompareCondition.valueEq("Deimos")));
System.out.println(res9); // OK
String res10 = jedis.set("bike:1", "Zeus",
SetParams.setParams().condition(CompareCondition.valueEq("Deimos")));
System.out.println(res10); // null
System.out.println(jedis.get("bike:1")); // Ares
long res11 = jedis.delex("bike:1", CompareCondition.valueEq("Deimos"));
System.out.println(res11); // 0
long res12 = jedis.delex("bike:1", CompareCondition.valueEq("Ares"));
System.out.println(res12); // 1
String res5 = jedis.mset("bike:1", "Deimos", "bike:2", "Ares", "bike:3", "Vanth");
System.out.println(res5); // OK
List<String> res6 = jedis.mget("bike:1", "bike:2", "bike:3");
System.out.println(res6); // [Deimos, Ares, Vanth]
jedis.set("total_crashes", "0");
Long res7 = jedis.incr("total_crashes");
System.out.println(res7); // 1
Long res8 = jedis.incrBy("total_crashes", 10);
System.out.println(res8); // 11
}
}
}
-
Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.
-
set(
- key: byte[],
- value: byte[]
-
set(
- key: byte[],
- value: byte[],
- params: SetParams // key if it already exists. EX|PX, expire time units: EX = seconds; PX = milliseconds
-
set(
- key: String,
- value: String
-
set(
- key: String,
- value: String,
- params: SetParams // key if it already exists. EX|PX, expire time units: EX = seconds; PX = milliseconds
-
set(
CompletableFuture<Void> setAndGet = asyncCommands.set("bike:1", "Deimos").thenCompose(v -> {
System.out.println(v); // >>> OK
return asyncCommands.get("bike:1");
})
.thenAccept(System.out::println) // >>> Deimos
.toCompletableFuture();
package io.redis.examples.async;
import io.lettuce.core.*;
import io.lettuce.core.api.async.RedisAsyncCommands;
import io.lettuce.core.api.StatefulRedisConnection;
import java.util.*;
import java.util.concurrent.CompletableFuture;
public class StringExample {
public void run() {
RedisClient redisClient = RedisClient.create("redis://localhost:6379");
try (StatefulRedisConnection<String, String> connection = redisClient.connect()) {
RedisAsyncCommands<String, String> asyncCommands = connection.async();
CompletableFuture<Void> setAndGet = asyncCommands.set("bike:1", "Deimos").thenCompose(v -> {
System.out.println(v); // >>> OK
return asyncCommands.get("bike:1");
})
.thenAccept(System.out::println) // >>> Deimos
.toCompletableFuture();
setAndGet.join();
// Recreate the bike:1 key so this example runs on its own.
CompletableFuture<Void> setnx = asyncCommands.set("bike:1", "Deimos")
.thenCompose(setup -> asyncCommands.setnx("bike:1", "bike")).thenCompose(v -> {
System.out.println(v); // >>> false (because key already exists)
return asyncCommands.get("bike:1");
})
.thenAccept(System.out::println) // >>> Deimos (value is unchanged)
.toCompletableFuture();
setnx.join();
// set the value to "bike" if it already exists
CompletableFuture<Void> setxx = asyncCommands.set("bike:1", "bike", SetArgs.Builder.xx())
.thenAccept(System.out::println) // >>> OK
.toCompletableFuture();
setxx.join();
CompletableFuture<Void> casCad = asyncCommands.set("bike:1", "Deimos")
.thenCompose(setup -> asyncCommands.set("bike:1", "Ares",
SetArgs.Builder.compareCondition(CompareCondition.valueEq("Deimos"))))
.thenCompose(v -> {
System.out.println(v); // >>> OK
return asyncCommands.set("bike:1", "Zeus",
SetArgs.Builder.compareCondition(CompareCondition.valueEq("Deimos")));
}).thenCompose(v -> {
System.out.println(v); // >>> null
return asyncCommands.get("bike:1");
}).thenCompose(v -> {
System.out.println(v); // >>> Ares
return asyncCommands.delex("bike:1", CompareCondition.valueEq("Deimos"));
}).thenCompose(v -> {
System.out.println(v); // >>> 0
return asyncCommands.delex("bike:1", CompareCondition.valueEq("Ares"));
})
.thenAccept(System.out::println) // >>> 1
.toCompletableFuture();
casCad.join();
Map<String, String> bikeMap = new HashMap<>();
bikeMap.put("bike:1", "Deimos");
bikeMap.put("bike:2", "Ares");
bikeMap.put("bike:3", "Vanth");
CompletableFuture<Void> mset = asyncCommands.mset(bikeMap).thenCompose(v -> {
System.out.println(v); // >>> OK
return asyncCommands.mget("bike:1", "bike:2", "bike:3");
})
.thenAccept(System.out::println)
// >>> [KeyValue[bike:1, Deimos], KeyValue[bike:2, Ares], KeyValue[bike:3,
// Vanth]]
.toCompletableFuture();
mset.join();
CompletableFuture<Void> incrby = asyncCommands.set("total_crashes", "0")
.thenCompose(v -> asyncCommands.incr("total_crashes")).thenCompose(v -> {
System.out.println(v); // >>> 1
return asyncCommands.incrby("total_crashes", 10);
})
.thenAccept(System.out::println) // >>> 11
.toCompletableFuture();
incrby.join();
} finally {
redisClient.shutdown();
}
}
}
-
Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.
-
set(
- key: K, // the key.
- value: V // the value.
-
set(
- key: K, // the key.
- value: V, // the value.
- setArgs: SetArgs // the setArgs.
-
set(
Mono<Void> setAndGet = reactiveCommands.set("bike:1", "Deimos").doOnNext(v -> {
System.out.println(v); // OK
}).flatMap(v -> reactiveCommands.get("bike:1")).doOnNext(res -> {
System.out.println(res); // Deimos
}).then();
package io.redis.examples.reactive;
import io.lettuce.core.*;
import io.lettuce.core.api.reactive.RedisReactiveCommands;
import io.lettuce.core.api.StatefulRedisConnection;
import reactor.core.publisher.Mono;
import java.util.*;
public class StringExample {
public void run() {
RedisClient redisClient = RedisClient.create("redis://localhost:6379");
try (StatefulRedisConnection<String, String> connection = redisClient.connect()) {
RedisReactiveCommands<String, String> reactiveCommands = connection.reactive();
Mono<Void> setAndGet = reactiveCommands.set("bike:1", "Deimos").doOnNext(v -> {
System.out.println(v); // OK
}).flatMap(v -> reactiveCommands.get("bike:1")).doOnNext(res -> {
System.out.println(res); // Deimos
}).then();
// Recreate the bike:1 key so this example runs on its own.
Mono<Void> setnx = reactiveCommands.set("bike:1", "Deimos")
.flatMap(setup -> reactiveCommands.setnx("bike:1", "bike")).doOnNext(v -> {
System.out.println(v); // false (because key already exists)
}).flatMap(v -> reactiveCommands.get("bike:1")).doOnNext(res -> {
System.out.println(res); // Deimos (value is unchanged)
}).then();
Mono<Void> setxx = reactiveCommands.set("bike:1", "bike", SetArgs.Builder.xx()).doOnNext(res -> {
System.out.println(res); // OK
}).then();
Mono<Void> casCad = reactiveCommands.set("bike:1", "Deimos")
.flatMap(setup -> reactiveCommands.set("bike:1", "Ares",
SetArgs.Builder.compareCondition(CompareCondition.valueEq("Deimos"))))
.doOnNext(res -> {
System.out.println(res); // OK
})
// A failed condition returns an empty Mono, so check for an element.
.flatMap(v -> reactiveCommands.set("bike:1", "Zeus",
SetArgs.Builder.compareCondition(CompareCondition.valueEq("Deimos"))).hasElement())
.doOnNext(res -> {
System.out.println(res); // false
}).flatMap(v -> reactiveCommands.get("bike:1")).doOnNext(res -> {
System.out.println(res); // Ares
}).flatMap(v -> reactiveCommands.delex("bike:1", CompareCondition.valueEq("Deimos")))
.doOnNext(res -> {
System.out.println(res); // 0
}).flatMap(v -> reactiveCommands.delex("bike:1", CompareCondition.valueEq("Ares")))
.doOnNext(res -> {
System.out.println(res); // 1
}).then();
Map<String, String> bikeMap = new HashMap<>();
bikeMap.put("bike:1", "Deimos");
bikeMap.put("bike:2", "Ares");
bikeMap.put("bike:3", "Vanth");
Mono<Void> mset = reactiveCommands.mset(bikeMap).doOnNext(System.out::println) // OK
.flatMap(v -> reactiveCommands.mget("bike:1", "bike:2", "bike:3").collectList()).doOnNext(res -> {
System.out.println(res); // [KeyValue[bike:1, Deimos], KeyValue[bike:2, Ares], KeyValue[bike:3, Vanth]]
}).then();
Mono<Void> incrby = reactiveCommands.set("total_crashes", "0").flatMap(v -> reactiveCommands.incr("total_crashes"))
.doOnNext(v -> {
System.out.println(v); // 1
}).flatMap(v -> reactiveCommands.incrby("total_crashes", 10)).doOnNext(res -> {
System.out.println(res); // 11
}).then();
// Run the steps sequentially: several of them mutate bike:1, so a
// shared Mono.when() would race them against each other's reads.
setAndGet.then(setnx).then(setxx).then(casCad).then(mset).then(incrby).block();
} finally {
redisClient.shutdown();
}
}
}
-
Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.
-
set(
- key: K, // the key.
- value: V // the value.
-
set(
- key: K, // the key.
- value: V, // the value.
- setArgs: SetArgs // the setArgs.
-
set(
res1, err := rdb.Set(ctx, "bike:1", "Deimos", 0).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> OK
res2, err := rdb.Get(ctx, "bike:1").Result()
if err != nil {
panic(err)
}
fmt.Println(res2) // >>> Deimos
package example_commands_test
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
func ExampleClient_set_get() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res1, err := rdb.Set(ctx, "bike:1", "Deimos", 0).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> OK
res2, err := rdb.Get(ctx, "bike:1").Result()
if err != nil {
panic(err)
}
fmt.Println(res2) // >>> Deimos
}
func ExampleClient_setnx_xx() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
// Recreate the bike:1 key so this example runs on its own.
rdb.Set(ctx, "bike:1", "Deimos", 0)
res3, err := rdb.SetNX(ctx, "bike:1", "bike", 0).Result()
if err != nil {
panic(err)
}
fmt.Println(res3) // >>> false
res4, err := rdb.Get(ctx, "bike:1").Result()
if err != nil {
panic(err)
}
fmt.Println(res4) // >>> Deimos
res5, err := rdb.SetXX(ctx, "bike:1", "bike", 0).Result()
if err != nil {
panic(err)
}
fmt.Println(res5) // >>> OK
}
func ExampleClient_cas_cad() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
rdb.Set(ctx, "bike:1", "Deimos", 0)
res11, err := rdb.SetIFEQ(ctx, "bike:1", "Ares", "Deimos", 0).Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> OK
// The value no longer matches, so SetIFEQ returns redis.Nil.
_, err = rdb.SetIFEQ(ctx, "bike:1", "Zeus", "Deimos", 0).Result()
if err != nil && err != redis.Nil {
panic(err)
}
fmt.Println(err == redis.Nil) // >>> true
res12, err := rdb.Get(ctx, "bike:1").Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> Ares
res13, err := rdb.DelExArgs(ctx, "bike:1", redis.DelExArgs{
Mode: "IFEQ", MatchValue: "Deimos",
}).Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> 0
res14, err := rdb.DelExArgs(ctx, "bike:1", redis.DelExArgs{
Mode: "IFEQ", MatchValue: "Ares",
}).Result()
if err != nil {
panic(err)
}
fmt.Println(res14) // >>> 1
}
func ExampleClient_mset() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res6, err := rdb.MSet(ctx, "bike:1", "Deimos", "bike:2", "Ares", "bike:3", "Vanth").Result()
if err != nil {
panic(err)
}
fmt.Println(res6) // >>> OK
res7, err := rdb.MGet(ctx, "bike:1", "bike:2", "bike:3").Result()
if err != nil {
panic(err)
}
fmt.Println(res7) // >>> [Deimos Ares Vanth]
}
func ExampleClient_incr() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res8, err := rdb.Set(ctx, "total_crashes", "0", 0).Result()
if err != nil {
panic(err)
}
fmt.Println(res8) // >>> OK
res9, err := rdb.Incr(ctx, "total_crashes").Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> 1
res10, err := rdb.IncrBy(ctx, "total_crashes", 10).Result()
if err != nil {
panic(err)
}
fmt.Println(res10) // >>> 11
}
-
Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.
-
Set(
- ctx: context.Context,
- key: string,
- value: interface{},
- expiration: time.Duration
-
SetArgs(
- ctx: context.Context,
- key: string,
- value: interface{},
- a: SetArgs // Mode can be `NX`, `XX`, `IFEQ`, `IFNE`, `IFDEQ`, `IFDNE` or empty. MatchValue is used with IFEQ/IFNE; MatchDigest (a uint64 xxh3 hash) is used with IFDEQ/IFDNE.
-
SetIFEQ(
- ctx: context.Context,
- key: string,
- value: interface{},
- matchValue: interface{},
- expiration: time.Duration // Zero expiration means the key has no expiration time.
-
SetIFNE(
- ctx: context.Context,
- key: string,
- value: interface{},
- matchValue: interface{},
- expiration: time.Duration // Zero expiration means the key has no expiration time.
-
SetIFDEQ(
- ctx: context.Context,
- key: string,
- value: interface{},
- matchDigest: uint64, // A uint64 xxh3 hash value.
- expiration: time.Duration // Zero expiration means the key has no expiration time.
-
SetIFDNE(
- ctx: context.Context,
- key: string,
- value: interface{},
- matchDigest: uint64, // A uint64 xxh3 hash value.
- expiration: time.Duration // Zero expiration means the key has no expiration time.
-
Set(
var res1 = db.StringSet("bike:1", "Deimos");
Console.WriteLine(res1); // true
var res2 = db.StringGet("bike:1");
Console.WriteLine(res2); // Deimos
public class StringSnippets
{
public void Run()
{
var muxer = ConnectionMultiplexer.Connect("localhost:6379");
var db = muxer.GetDatabase();
var res1 = db.StringSet("bike:1", "Deimos");
Console.WriteLine(res1); // true
var res2 = db.StringGet("bike:1");
Console.WriteLine(res2); // Deimos
// Recreate the bike:1 key so this example runs on its own.
db.StringSet("bike:1", "Deimos");
var res3 = db.StringSet("bike:1", "bike", when: When.NotExists);
Console.WriteLine(res3); // false
Console.WriteLine(db.StringGet("bike:1"));
var res4 = db.StringSet("bike:1", "bike", when: When.Exists);
Console.WriteLine(res4); // true
db.StringSet("bike:1", "Deimos");
var res9 = db.StringSet("bike:1", "Ares", when: ValueCondition.Equal("Deimos"));
Console.WriteLine(res9); // True
var res10 = db.StringSet("bike:1", "Zeus", when: ValueCondition.Equal("Deimos"));
Console.WriteLine(res10); // False
Console.WriteLine(db.StringGet("bike:1")); // Ares
var res11 = db.StringDelete("bike:1", ValueCondition.Equal("Deimos"));
Console.WriteLine(res11); // False
var res12 = db.StringDelete("bike:1", ValueCondition.Equal("Ares"));
Console.WriteLine(res12); // True
var res5 = db.StringSet([
new ("bike:1", "Deimos"), new("bike:2", "Ares"), new("bike:3", "Vanth")
]);
Console.WriteLine(res5);
var res6 = db.StringGet(["bike:1", "bike:2", "bike:3"]);
Console.WriteLine(string.Join(", ", res6));
db.StringSet("total_crashes", 0);
var res7 = db.StringIncrement("total_crashes");
Console.WriteLine(res7); // 1
var res8 = db.StringIncrement("total_crashes", 10);
Console.WriteLine(res8);
}
}-
Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.
-
StringSet(
- key: RedisKey,
- value: RedisValue,
- expiry: TimeSpan?, // The expiry to set.
- when: When // Which condition to set the value under (defaults to always).
-
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.
-
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.
-
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.
-
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.
-
StringSet(
-
Returns the string value of a key.
-
StringGet(
- key: RedisKey,
- flags: CommandFlags // The flags to use for this operation.
-
StringGet(
- keys: RedisKey[], // The keys of the strings.
- flags: CommandFlags // The flags to use for this operation.
-
StringGet(
- key: Any,
- flags: Any // The flags to use for this operation.
-
StringGet(
- key: RedisKey,
- flags: CommandFlags // The flags to use for this operation.
-
StringGet(
- keys: RedisKey[], // The keys of the strings.
- flags: CommandFlags // The flags to use for this operation.
-
StringGet(
$res1 = $r->set('bike:1', 'Deimos');
echo "$res1" . PHP_EOL;
// >>> OK
$res2 = $r->get('bike:1');
echo "$res2" . PHP_EOL;
// >>> Deimos
<?php
require 'vendor/autoload.php';
use Predis\Client as PredisClient;
class DtStringTest
{
public function testDtString() {
$r = new PredisClient([
'scheme' => 'tcp',
'host' => '127.0.0.1',
'port' => 6379,
'password' => '',
'database' => 0,
]);
$res1 = $r->set('bike:1', 'Deimos');
echo "$res1" . PHP_EOL;
// >>> OK
$res2 = $r->get('bike:1');
echo "$res2" . PHP_EOL;
// >>> Deimos
// Recreate the bike:1 key so this example runs on its own.
$r->set('bike:1', 'Deimos');
$res3 = $r->set('bike:1', 'bike', 'nx');
echo var_export($res3, true) . PHP_EOL;
// >>> NULL
echo $r->get('bike:1') . PHP_EOL;
// >>> Deimos
$res4 = $r->set('bike:1', 'bike', 'xx');
echo "$res4" . PHP_EOL;
// >>> OK
$r->set('bike:1', 'Deimos');
$res9 = $r->set('bike:1', 'Ares', null, null, 'IFEQ', 'Deimos');
echo "$res9" . PHP_EOL;
// >>> OK
$res10 = $r->set('bike:1', 'Zeus', null, null, 'IFEQ', 'Deimos');
echo var_export($res10, true) . PHP_EOL;
// >>> NULL
echo $r->get('bike:1') . PHP_EOL;
// >>> Ares
$res11 = $r->delex('bike:1', 'IFEQ', 'Deimos');
echo "$res11" . PHP_EOL;
// >>> 0
$res12 = $r->delex('bike:1', 'IFEQ', 'Ares');
echo "$res12" . PHP_EOL;
// >>> 1
$res5 = $r->mset([
'bike:1' => 'Deimos', 'bike:2' => 'Ares', 'bike:3' => 'Vanth'
]);
echo "$res5" . PHP_EOL;
// >>> OK
$res6 = $r->mget(['bike:1', 'bike:2', 'bike:3']);
echo json_encode($res6) . PHP_EOL;
// >>> ["Deimos","Ares","Vanth"]
$r->set('total_crashes', 0);
$res7 = $r->incr('total_crashes');
echo "$res7" . PHP_EOL;
// >>> 1
$res8 = $r->incrby('total_crashes', 10);
echo "$res8" . PHP_EOL;
// >>> 11
}
}res1 = r.set('bike:1', 'Deimos')
puts res1 # >>> OK
res2 = r.get('bike:1')
puts res2 # >>> Deimos
require 'redis'
r = Redis.new
res1 = r.set('bike:1', 'Deimos')
puts res1 # >>> OK
res2 = r.get('bike:1')
puts res2 # >>> Deimos
# Recreate the bike:1 key so this example runs on its own.
r.set('bike:1', 'Deimos')
res3 = r.set('bike:1', 'bike', nx: true)
puts res3 # >>> false
puts r.get('bike:1') # >>> Deimos
res4 = r.set('bike:1', 'bike', xx: true)
puts res4 # >>> true
res5 = r.mset('bike:1', 'Deimos', 'bike:2', 'Ares', 'bike:3', 'Vanth')
puts res5 # >>> OK
res6 = r.mget('bike:1', 'bike:2', 'bike:3')
puts res6.inspect # >>> ["Deimos", "Ares", "Vanth"]
r.set('total_crashes', 0)
res7 = r.incr('total_crashes')
puts res7 # >>> 1
res8 = r.incrby('total_crashes', 10)
puts res8 # >>> 11
-
Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.
-
set(
- key: String,
- value: String,
- ex: Integer, // Set the specified expire time, in seconds.
- px: Integer, // Set the specified expire time, in milliseconds.
- exat: Integer, // Set the specified Unix time at which the key will expire, in seconds.
- pxat: Integer, // Set the specified Unix time at which the key will expire, in milliseconds.
- nx: Boolean, // Only set the key if it does not already exist.
- xx: Boolean, // Only set the key if it already exists.
- keepttl: Boolean, // Retain the time to live associated with the key.
- get: Boolean // Return the old string stored at key, or nil if key did not exist.
-
set(
if let Ok(res) = r.set("bike:1", "Deimos") {
let res: String = res;
println!("{res}"); // >>> OK
}
match r.get("bike:1") {
Ok(res) => {
let res: String = res;
println!("{res}"); // >>> Deimos
},
Err(e) => {
println!("Error getting bike:1: {e}");
return;
}
};
mod strings_tests {
use redis::{Commands, ExistenceCheck, ValueComparison};
fn run() {
let mut r = match redis::Client::open("redis://127.0.0.1") {
Ok(client) => {
match client.get_connection() {
Ok(conn) => conn,
Err(e) => {
println!("Failed to connect to Redis: {e}");
return;
}
}
},
Err(e) => {
println!("Failed to create Redis client: {e}");
return;
}
};
if let Ok(res) = r.set("bike:1", "Deimos") {
let res: String = res;
println!("{res}"); // >>> OK
}
match r.get("bike:1") {
Ok(res) => {
let res: String = res;
println!("{res}"); // >>> Deimos
},
Err(e) => {
println!("Error getting bike:1: {e}");
return;
}
};
// Recreate the bike:1 key so this example runs on its own.
let _: () = r.set("bike:1", "Deimos").expect("Failed to set");
if let Ok(res) = r.set_options("bike:1", "bike", redis::SetOptions::default().conditional_set(ExistenceCheck::NX)) {
let res: bool = res;
println!("{res}"); // >>> false
}
match r.get("bike:1") {
Ok(res) => {
let res: String = res;
println!("{res}"); // >>> Deimos
},
Err(e) => {
println!("Error getting bike:1: {e}");
return;
}
};
if let Ok(res) = r.set_options("bike:1", "bike", redis::SetOptions::default().conditional_set(ExistenceCheck::XX)) {
let res: String = res;
println!("{res}"); // >>> OK
}
match r.get("bike:1") {
Ok(res) => {
let res: String = res;
println!("{res}"); // >>> bike
},
Err(e) => {
println!("Error getting bike:1: {e}");
return;
}
};
let _: () = r.set("bike:1", "Deimos").expect("Failed to set");
let res: Option<String> = r
.set_options("bike:1", "Ares", redis::SetOptions::default().value_comparison(ValueComparison::ifeq("Deimos")))
.expect("Failed to set");
println!("{res:?}"); // >>> Some("OK")
let res: Option<String> = r
.set_options("bike:1", "Zeus", redis::SetOptions::default().value_comparison(ValueComparison::ifeq("Deimos")))
.expect("Failed to set");
println!("{res:?}"); // >>> None
let res: String = r.get("bike:1").expect("Failed to get");
println!("{res}"); // >>> Ares
let res: usize = r.del_ex("bike:1", ValueComparison::ifeq("Deimos")).expect("Failed to delete");
println!("{res}"); // >>> 0
let res: usize = r.del_ex("bike:1", ValueComparison::ifeq("Ares")).expect("Failed to delete");
println!("{res}"); // >>> 1
if let Ok(res) = r.mset(&[("bike:1", "Deimos"), ("bike:2", "Ares"), ("bike:3", "Vanth")]) {
let res: String = res;
println!("{res}"); // >>> OK
}
match r.mget(&["bike:1", "bike:2", "bike:3"]) {
Ok(res) => {
let res: Vec<String> = res;
println!("{res:?}"); // >>> ["Deimos", "Ares", "Vanth"]
},
Err(e) => {
println!("Error getting values: {e}");
return;
}
};
if let Ok(res) = r.set("total_crashes", 0) {
let res: String = res;
println!("{res}"); // >>> OK
}
if let Ok(res) = r.incr("total_crashes", 1) {
let res: i32 = res;
println!("{res}"); // >>> 1
}
if let Ok(res) = r.incr("total_crashes", 10) {
let res: i32 = res;
println!("{res}"); // >>> 11
}
}
} if let Ok(res) = r.set("bike:1", "Deimos").await {
let res: String = res;
println!("{res}"); // >>> OK
}
match r.get("bike:1").await {
Ok(res) => {
let res: String = res;
println!("{res}"); // >>> Deimos
},
Err(e) => {
println!("Error getting foo: {e}");
return;
}
};
mod tests {
use redis::{AsyncCommands, ExistenceCheck, ValueComparison};
async fn run() {
let mut r = match redis::Client::open("redis://127.0.0.1") {
Ok(client) => {
match client.get_multiplexed_async_connection().await {
Ok(conn) => conn,
Err(e) => {
println!("Failed to connect to Redis: {e}");
return;
}
}
},
Err(e) => {
println!("Failed to create Redis client: {e}");
return;
}
};
if let Ok(res) = r.set("bike:1", "Deimos").await {
let res: String = res;
println!("{res}"); // >>> OK
}
match r.get("bike:1").await {
Ok(res) => {
let res: String = res;
println!("{res}"); // >>> Deimos
},
Err(e) => {
println!("Error getting foo: {e}");
return;
}
};
// Recreate the bike:1 key so this example runs on its own.
let _: () = r.set("bike:1", "Deimos").await.expect("Failed to set");
if let Ok(res) = r.set_options("bike:1", "bike", redis::SetOptions::default().conditional_set(ExistenceCheck::NX)).await {
let res: bool = res;
println!("{res}"); // >>> false
}
match r.get("bike:1").await {
Ok(res) => {
let res: String = res;
println!("{res}"); // >>> Deimos
},
Err(e) => {
println!("Error getting foo: {e}");
return;
}
};
if let Ok(res) = r.set_options("bike:1", "bike", redis::SetOptions::default().conditional_set(ExistenceCheck::XX)).await {
let res: String = res;
println!("{res}"); // >>> OK
}
match r.get("bike:1").await {
Ok(res) => {
let res: String = res;
println!("{res}"); // >>> bike
},
Err(e) => {
println!("Error getting foo: {e}");
return;
}
};
let _: () = r.set("bike:1", "Deimos").await.expect("Failed to set");
let res: Option<String> = r
.set_options("bike:1", "Ares", redis::SetOptions::default().value_comparison(ValueComparison::ifeq("Deimos")))
.await.expect("Failed to set");
println!("{res:?}"); // >>> Some("OK")
let res: Option<String> = r
.set_options("bike:1", "Zeus", redis::SetOptions::default().value_comparison(ValueComparison::ifeq("Deimos")))
.await.expect("Failed to set");
println!("{res:?}"); // >>> None
let res: String = r.get("bike:1").await.expect("Failed to get");
println!("{res}"); // >>> Ares
let res: usize = r.del_ex("bike:1", ValueComparison::ifeq("Deimos")).await.expect("Failed to delete");
println!("{res}"); // >>> 0
let res: usize = r.del_ex("bike:1", ValueComparison::ifeq("Ares")).await.expect("Failed to delete");
println!("{res}"); // >>> 1
if let Ok(res) = r.mset(&[("bike:1", "Deimos"), ("bike:2", "Ares"), ("bike:3", "Vanth")]).await {
let res: String = res;
println!("{res}"); // >>> OK
}
match r.mget(&["bike:1", "bike:2", "bike:3"]).await {
Ok(res) => {
let res: Vec<String> = res;
println!("{res:?}"); // >>> ["Deimos", "Ares", "Vanth"]
},
Err(e) => {
println!("Error getting foo: {e}");
return;
}
};
if let Ok(res) = r.set("total_crashes", 0).await {
let res: String = res;
println!("{res}"); // >>> OK
}
if let Ok(res) = r.incr("total_crashes", 1).await {
let res: i32 = res;
println!("{res}"); // >>> 1
}
if let Ok(res) = r.incr("total_crashes", 10).await {
let res: i32 = res;
println!("{res}"); // >>> 11
}
}
}As you can see using the SET and the GET commands are the way we set
and retrieve a string value. Note that SET will replace any existing value
already stored into the key, in the case that the key already exists, even if
the key is associated with a non-string value. So SET performs an assignment.
Values can be strings (including binary data) of every kind, for instance you can store a jpeg image inside a value. A value can't be bigger than 512 MB.
The SET command has interesting options that are provided as additional
arguments. For example, I may ask SET to fail if the key already exists,
or the opposite, that it only succeed if the key already exists:
# Recreate the bike:1 key so this example runs on its own. > SET bike:1 Deimos OK > SET bike:1 bike NX (nil) > SET bike:1 bike XX OK
# Recreate the bike:1 key so this example runs on its own.
r.set("bike:1", "Deimos")
res3 = r.set("bike:1", "bike", nx=True)
print(res3) # None
print(r.get("bike:1")) # Deimos
res4 = r.set("bike:1", "bike", xx=True)
print(res4) # True
-
Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.
-
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
-
set(
// Recreate the bike:1 key so this example runs on its own.
await client.set("bike:1", "Deimos");
const res3 = await client.set("bike:1", "bike", {'NX': true});
console.log(res3); // null
console.log(await client.get("bike:1")); // Deimos
const res4 = await client.set("bike:1", "bike", {'XX': true});
console.log(res4); // OK
// Recreate the bike:1 key so this example runs on its own.
jedis.set("bike:1", "Deimos");
Long res3 = jedis.setnx("bike:1", "bike");
System.out.println(res3); // 0 (because key already exists)
System.out.println(jedis.get("bike:1")); // Deimos (value is unchanged)
String res4 = jedis.set("bike:1", "bike", SetParams.setParams().xx()); // set the value to "bike" if it
// already
// exists
System.out.println(res4); // OK
-
Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.
-
set(
- key: byte[],
- value: byte[]
-
set(
- key: byte[],
- value: byte[],
- params: SetParams // key if it already exists. EX|PX, expire time units: EX = seconds; PX = milliseconds
-
set(
- key: String,
- value: String
-
set(
- key: String,
- value: String,
- params: SetParams // key if it already exists. EX|PX, expire time units: EX = seconds; PX = milliseconds
-
set(
// Recreate the bike:1 key so this example runs on its own.
CompletableFuture<Void> setnx = asyncCommands.set("bike:1", "Deimos")
.thenCompose(setup -> asyncCommands.setnx("bike:1", "bike")).thenCompose(v -> {
System.out.println(v); // >>> false (because key already exists)
return asyncCommands.get("bike:1");
})
.thenAccept(System.out::println) // >>> Deimos (value is unchanged)
.toCompletableFuture();
setnx.join();
// set the value to "bike" if it already exists
CompletableFuture<Void> setxx = asyncCommands.set("bike:1", "bike", SetArgs.Builder.xx())
.thenAccept(System.out::println) // >>> OK
.toCompletableFuture();
setxx.join();
-
Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.
-
set(
- key: K, // the key.
- value: V // the value.
-
set(
- key: K, // the key.
- value: V, // the value.
- setArgs: SetArgs // the setArgs.
-
set(
// Recreate the bike:1 key so this example runs on its own.
Mono<Void> setnx = reactiveCommands.set("bike:1", "Deimos")
.flatMap(setup -> reactiveCommands.setnx("bike:1", "bike")).doOnNext(v -> {
System.out.println(v); // false (because key already exists)
}).flatMap(v -> reactiveCommands.get("bike:1")).doOnNext(res -> {
System.out.println(res); // Deimos (value is unchanged)
}).then();
Mono<Void> setxx = reactiveCommands.set("bike:1", "bike", SetArgs.Builder.xx()).doOnNext(res -> {
System.out.println(res); // OK
}).then();
-
Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.
-
set(
- key: K, // the key.
- value: V // the value.
-
set(
- key: K, // the key.
- value: V, // the value.
- setArgs: SetArgs // the setArgs.
-
set(
// Recreate the bike:1 key so this example runs on its own.
rdb.Set(ctx, "bike:1", "Deimos", 0)
res3, err := rdb.SetNX(ctx, "bike:1", "bike", 0).Result()
if err != nil {
panic(err)
}
fmt.Println(res3) // >>> false
res4, err := rdb.Get(ctx, "bike:1").Result()
if err != nil {
panic(err)
}
fmt.Println(res4) // >>> Deimos
res5, err := rdb.SetXX(ctx, "bike:1", "bike", 0).Result()
if err != nil {
panic(err)
}
fmt.Println(res5) // >>> OK
-
Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.
-
Set(
- ctx: context.Context,
- key: string,
- value: interface{},
- expiration: time.Duration
-
SetArgs(
- ctx: context.Context,
- key: string,
- value: interface{},
- a: SetArgs // Mode can be `NX`, `XX`, `IFEQ`, `IFNE`, `IFDEQ`, `IFDNE` or empty. MatchValue is used with IFEQ/IFNE; MatchDigest (a uint64 xxh3 hash) is used with IFDEQ/IFDNE.
-
SetIFEQ(
- ctx: context.Context,
- key: string,
- value: interface{},
- matchValue: interface{},
- expiration: time.Duration // Zero expiration means the key has no expiration time.
-
SetIFNE(
- ctx: context.Context,
- key: string,
- value: interface{},
- matchValue: interface{},
- expiration: time.Duration // Zero expiration means the key has no expiration time.
-
SetIFDEQ(
- ctx: context.Context,
- key: string,
- value: interface{},
- matchDigest: uint64, // A uint64 xxh3 hash value.
- expiration: time.Duration // Zero expiration means the key has no expiration time.
-
SetIFDNE(
- ctx: context.Context,
- key: string,
- value: interface{},
- matchDigest: uint64, // A uint64 xxh3 hash value.
- expiration: time.Duration // Zero expiration means the key has no expiration time.
-
Set(
// Recreate the bike:1 key so this example runs on its own.
db.StringSet("bike:1", "Deimos");
var res3 = db.StringSet("bike:1", "bike", when: When.NotExists);
Console.WriteLine(res3); // false
Console.WriteLine(db.StringGet("bike:1"));
var res4 = db.StringSet("bike:1", "bike", when: When.Exists);
Console.WriteLine(res4); // true
-
Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.
-
StringSet(
- key: RedisKey,
- value: RedisValue,
- expiry: TimeSpan?, // The expiry to set.
- when: When // Which condition to set the value under (defaults to always).
-
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.
-
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.
-
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.
-
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.
-
StringSet(
// Recreate the bike:1 key so this example runs on its own.
$r->set('bike:1', 'Deimos');
$res3 = $r->set('bike:1', 'bike', 'nx');
echo var_export($res3, true) . PHP_EOL;
// >>> NULL
echo $r->get('bike:1') . PHP_EOL;
// >>> Deimos
$res4 = $r->set('bike:1', 'bike', 'xx');
echo "$res4" . PHP_EOL;
// >>> OK
# Recreate the bike:1 key so this example runs on its own.
r.set('bike:1', 'Deimos')
res3 = r.set('bike:1', 'bike', nx: true)
puts res3 # >>> false
puts r.get('bike:1') # >>> Deimos
res4 = r.set('bike:1', 'bike', xx: true)
puts res4 # >>> true
-
Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.
-
set(
- key: String,
- value: String,
- ex: Integer, // Set the specified expire time, in seconds.
- px: Integer, // Set the specified expire time, in milliseconds.
- exat: Integer, // Set the specified Unix time at which the key will expire, in seconds.
- pxat: Integer, // Set the specified Unix time at which the key will expire, in milliseconds.
- nx: Boolean, // Only set the key if it does not already exist.
- xx: Boolean, // Only set the key if it already exists.
- keepttl: Boolean, // Retain the time to live associated with the key.
- get: Boolean // Return the old string stored at key, or nil if key did not exist.
-
set(
// Recreate the bike:1 key so this example runs on its own.
let _: () = r.set("bike:1", "Deimos").expect("Failed to set");
if let Ok(res) = r.set_options("bike:1", "bike", redis::SetOptions::default().conditional_set(ExistenceCheck::NX)) {
let res: bool = res;
println!("{res}"); // >>> false
}
match r.get("bike:1") {
Ok(res) => {
let res: String = res;
println!("{res}"); // >>> Deimos
},
Err(e) => {
println!("Error getting bike:1: {e}");
return;
}
};
if let Ok(res) = r.set_options("bike:1", "bike", redis::SetOptions::default().conditional_set(ExistenceCheck::XX)) {
let res: String = res;
println!("{res}"); // >>> OK
}
match r.get("bike:1") {
Ok(res) => {
let res: String = res;
println!("{res}"); // >>> bike
},
Err(e) => {
println!("Error getting bike:1: {e}");
return;
}
};
// Recreate the bike:1 key so this example runs on its own.
let _: () = r.set("bike:1", "Deimos").await.expect("Failed to set");
if let Ok(res) = r.set_options("bike:1", "bike", redis::SetOptions::default().conditional_set(ExistenceCheck::NX)).await {
let res: bool = res;
println!("{res}"); // >>> false
}
match r.get("bike:1").await {
Ok(res) => {
let res: String = res;
println!("{res}"); // >>> Deimos
},
Err(e) => {
println!("Error getting foo: {e}");
return;
}
};
if let Ok(res) = r.set_options("bike:1", "bike", redis::SetOptions::default().conditional_set(ExistenceCheck::XX)).await {
let res: String = res;
println!("{res}"); // >>> OK
}
match r.get("bike:1").await {
Ok(res) => {
let res: String = res;
println!("{res}"); // >>> bike
},
Err(e) => {
println!("Error getting foo: {e}");
return;
}
};
Starting with Redis 8.4, SET can also check the key's current value before it writes.
With the IFEQ option, SET succeeds only if the current value equals the one you pass.
This lets a client update a value it read earlier without overwriting a change that another client made in the meantime, a pattern known as compare-and-swap (CAS).
The DELEX command applies the same check to deletion (compare-and-delete):
> SET bike:1 Deimos OK > SET bike:1 Ares IFEQ Deimos OK > SET bike:1 Zeus IFEQ Deimos (nil) > GET bike:1 "Ares" > DELEX bike:1 IFEQ Deimos (integer) 0 > DELEX bike:1 IFEQ Ares (integer) 1
r.set("bike:1", "Deimos")
res9 = r.set("bike:1", "Ares", ifeq="Deimos")
print(res9) # True
res10 = r.set("bike:1", "Zeus", ifeq="Deimos")
print(res10) # None
print(r.get("bike:1")) # Ares
res11 = r.delex("bike:1", ifeq="Deimos")
print(res11) # 0
res12 = r.delex("bike:1", ifeq="Ares")
print(res12) # 1
-
Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.
-
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
-
set(
await client.set("bike:1", "Deimos");
const res9 = await client.set("bike:1", "Ares", {
condition: 'IFEQ', matchValue: "Deimos"
});
console.log(res9); // OK
const res10 = await client.set("bike:1", "Zeus", {
condition: 'IFEQ', matchValue: "Deimos"
});
console.log(res10); // null
console.log(await client.get("bike:1")); // Ares
const res11 = await client.delEx("bike:1", {
condition: 'IFEQ', matchValue: "Deimos"
});
console.log(res11); // 0
const res12 = await client.delEx("bike:1", {
condition: 'IFEQ', matchValue: "Ares"
});
console.log(res12); // 1
jedis.set("bike:1", "Deimos");
String res9 = jedis.set("bike:1", "Ares",
SetParams.setParams().condition(CompareCondition.valueEq("Deimos")));
System.out.println(res9); // OK
String res10 = jedis.set("bike:1", "Zeus",
SetParams.setParams().condition(CompareCondition.valueEq("Deimos")));
System.out.println(res10); // null
System.out.println(jedis.get("bike:1")); // Ares
long res11 = jedis.delex("bike:1", CompareCondition.valueEq("Deimos"));
System.out.println(res11); // 0
long res12 = jedis.delex("bike:1", CompareCondition.valueEq("Ares"));
System.out.println(res12); // 1
-
Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.
-
set(
- key: byte[],
- value: byte[]
-
set(
- key: byte[],
- value: byte[],
- params: SetParams // key if it already exists. EX|PX, expire time units: EX = seconds; PX = milliseconds
-
set(
- key: String,
- value: String
-
set(
- key: String,
- value: String,
- params: SetParams // key if it already exists. EX|PX, expire time units: EX = seconds; PX = milliseconds
-
set(
CompletableFuture<Void> casCad = asyncCommands.set("bike:1", "Deimos")
.thenCompose(setup -> asyncCommands.set("bike:1", "Ares",
SetArgs.Builder.compareCondition(CompareCondition.valueEq("Deimos"))))
.thenCompose(v -> {
System.out.println(v); // >>> OK
return asyncCommands.set("bike:1", "Zeus",
SetArgs.Builder.compareCondition(CompareCondition.valueEq("Deimos")));
}).thenCompose(v -> {
System.out.println(v); // >>> null
return asyncCommands.get("bike:1");
}).thenCompose(v -> {
System.out.println(v); // >>> Ares
return asyncCommands.delex("bike:1", CompareCondition.valueEq("Deimos"));
}).thenCompose(v -> {
System.out.println(v); // >>> 0
return asyncCommands.delex("bike:1", CompareCondition.valueEq("Ares"));
})
.thenAccept(System.out::println) // >>> 1
.toCompletableFuture();
-
Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.
-
set(
- key: K, // the key.
- value: V // the value.
-
set(
- key: K, // the key.
- value: V, // the value.
- setArgs: SetArgs // the setArgs.
-
set(
-
Conditionally removes the specified key based on value or digest comparison.
-
delex(
- key: K, // the key.
- compareCondition: CompareCondition<V> // the compare condition, must not be null.
-
delex(
Mono<Void> casCad = reactiveCommands.set("bike:1", "Deimos")
.flatMap(setup -> reactiveCommands.set("bike:1", "Ares",
SetArgs.Builder.compareCondition(CompareCondition.valueEq("Deimos"))))
.doOnNext(res -> {
System.out.println(res); // OK
})
// A failed condition returns an empty Mono, so check for an element.
.flatMap(v -> reactiveCommands.set("bike:1", "Zeus",
SetArgs.Builder.compareCondition(CompareCondition.valueEq("Deimos"))).hasElement())
.doOnNext(res -> {
System.out.println(res); // false
}).flatMap(v -> reactiveCommands.get("bike:1")).doOnNext(res -> {
System.out.println(res); // Ares
}).flatMap(v -> reactiveCommands.delex("bike:1", CompareCondition.valueEq("Deimos")))
.doOnNext(res -> {
System.out.println(res); // 0
}).flatMap(v -> reactiveCommands.delex("bike:1", CompareCondition.valueEq("Ares")))
.doOnNext(res -> {
System.out.println(res); // 1
}).then();
-
Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.
-
set(
- key: K, // the key.
- value: V // the value.
-
set(
- key: K, // the key.
- value: V, // the value.
- setArgs: SetArgs // the setArgs.
-
set(
-
Conditionally removes the specified key based on value or digest comparison.
-
delex(
- key: K, // the key.
- compareCondition: CompareCondition<V> // the compare condition, must not be null.
-
delex(
rdb.Set(ctx, "bike:1", "Deimos", 0)
res11, err := rdb.SetIFEQ(ctx, "bike:1", "Ares", "Deimos", 0).Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> OK
// The value no longer matches, so SetIFEQ returns redis.Nil.
_, err = rdb.SetIFEQ(ctx, "bike:1", "Zeus", "Deimos", 0).Result()
if err != nil && err != redis.Nil {
panic(err)
}
fmt.Println(err == redis.Nil) // >>> true
res12, err := rdb.Get(ctx, "bike:1").Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> Ares
res13, err := rdb.DelExArgs(ctx, "bike:1", redis.DelExArgs{
Mode: "IFEQ", MatchValue: "Deimos",
}).Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> 0
res14, err := rdb.DelExArgs(ctx, "bike:1", redis.DelExArgs{
Mode: "IFEQ", MatchValue: "Ares",
}).Result()
if err != nil {
panic(err)
}
fmt.Println(res14) // >>> 1
-
Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.
-
Set(
- ctx: context.Context,
- key: string,
- value: interface{},
- expiration: time.Duration
-
SetArgs(
- ctx: context.Context,
- key: string,
- value: interface{},
- a: SetArgs // Mode can be `NX`, `XX`, `IFEQ`, `IFNE`, `IFDEQ`, `IFDNE` or empty. MatchValue is used with IFEQ/IFNE; MatchDigest (a uint64 xxh3 hash) is used with IFDEQ/IFDNE.
-
SetIFEQ(
- ctx: context.Context,
- key: string,
- value: interface{},
- matchValue: interface{},
- expiration: time.Duration // Zero expiration means the key has no expiration time.
-
SetIFNE(
- ctx: context.Context,
- key: string,
- value: interface{},
- matchValue: interface{},
- expiration: time.Duration // Zero expiration means the key has no expiration time.
-
SetIFDEQ(
- ctx: context.Context,
- key: string,
- value: interface{},
- matchDigest: uint64, // A uint64 xxh3 hash value.
- expiration: time.Duration // Zero expiration means the key has no expiration time.
-
SetIFDNE(
- ctx: context.Context,
- key: string,
- value: interface{},
- matchDigest: uint64, // A uint64 xxh3 hash value.
- expiration: time.Duration // Zero expiration means the key has no expiration time.
-
Set(
db.StringSet("bike:1", "Deimos");
var res9 = db.StringSet("bike:1", "Ares", when: ValueCondition.Equal("Deimos"));
Console.WriteLine(res9); // True
var res10 = db.StringSet("bike:1", "Zeus", when: ValueCondition.Equal("Deimos"));
Console.WriteLine(res10); // False
Console.WriteLine(db.StringGet("bike:1")); // Ares
var res11 = db.StringDelete("bike:1", ValueCondition.Equal("Deimos"));
Console.WriteLine(res11); // False
var res12 = db.StringDelete("bike:1", ValueCondition.Equal("Ares"));
Console.WriteLine(res12); // True
-
Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.
-
StringSet(
- key: RedisKey,
- value: RedisValue,
- expiry: TimeSpan?, // The expiry to set.
- when: When // Which condition to set the value under (defaults to always).
-
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.
-
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.
-
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.
-
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.
-
StringSet(
-
Returns the string value of a key.
-
StringGet(
- key: RedisKey,
- flags: CommandFlags // The flags to use for this operation.
-
StringGet(
- keys: RedisKey[], // The keys of the strings.
- flags: CommandFlags // The flags to use for this operation.
-
StringGet(
- key: Any,
- flags: Any // The flags to use for this operation.
-
StringGet(
- key: RedisKey,
- flags: CommandFlags // The flags to use for this operation.
-
StringGet(
- keys: RedisKey[], // The keys of the strings.
- flags: CommandFlags // The flags to use for this operation.
-
StringGet(
$r->set('bike:1', 'Deimos');
$res9 = $r->set('bike:1', 'Ares', null, null, 'IFEQ', 'Deimos');
echo "$res9" . PHP_EOL;
// >>> OK
$res10 = $r->set('bike:1', 'Zeus', null, null, 'IFEQ', 'Deimos');
echo var_export($res10, true) . PHP_EOL;
// >>> NULL
echo $r->get('bike:1') . PHP_EOL;
// >>> Ares
$res11 = $r->delex('bike:1', 'IFEQ', 'Deimos');
echo "$res11" . PHP_EOL;
// >>> 0
$res12 = $r->delex('bike:1', 'IFEQ', 'Ares');
echo "$res12" . PHP_EOL;
// >>> 1
let _: () = r.set("bike:1", "Deimos").expect("Failed to set");
let res: Option<String> = r
.set_options("bike:1", "Ares", redis::SetOptions::default().value_comparison(ValueComparison::ifeq("Deimos")))
.expect("Failed to set");
println!("{res:?}"); // >>> Some("OK")
let res: Option<String> = r
.set_options("bike:1", "Zeus", redis::SetOptions::default().value_comparison(ValueComparison::ifeq("Deimos")))
.expect("Failed to set");
println!("{res:?}"); // >>> None
let res: String = r.get("bike:1").expect("Failed to get");
println!("{res}"); // >>> Ares
let res: usize = r.del_ex("bike:1", ValueComparison::ifeq("Deimos")).expect("Failed to delete");
println!("{res}"); // >>> 0
let res: usize = r.del_ex("bike:1", ValueComparison::ifeq("Ares")).expect("Failed to delete");
println!("{res}"); // >>> 1
let _: () = r.set("bike:1", "Deimos").await.expect("Failed to set");
let res: Option<String> = r
.set_options("bike:1", "Ares", redis::SetOptions::default().value_comparison(ValueComparison::ifeq("Deimos")))
.await.expect("Failed to set");
println!("{res:?}"); // >>> Some("OK")
let res: Option<String> = r
.set_options("bike:1", "Zeus", redis::SetOptions::default().value_comparison(ValueComparison::ifeq("Deimos")))
.await.expect("Failed to set");
println!("{res:?}"); // >>> None
let res: String = r.get("bike:1").await.expect("Failed to get");
println!("{res}"); // >>> Ares
let res: usize = r.del_ex("bike:1", ValueComparison::ifeq("Deimos")).await.expect("Failed to delete");
println!("{res}"); // >>> 0
let res: usize = r.del_ex("bike:1", ValueComparison::ifeq("Ares")).await.expect("Failed to delete");
println!("{res}"); // >>> 1
The IFNE option reverses the check, and the IFDEQ and IFDNE options compare a hash digest of the value instead of the value itself.
Use DIGEST to get the digest of a key's value.
There are a number of other commands for operating on strings. For example
the GETSET command sets a key to a new value, returning the old value as the
result. You can use this command, for example, if you have a
system that increments a Redis key using INCR
every time your web site receives a new visitor. You may want to collect this
information once every hour, without losing a single increment.
You can GETSET the key, assigning it the new value of "0" and reading the
old value back.
The ability to set or retrieve the value of multiple keys in a single
command is also useful for reduced latency. For this reason there are
the MSET and MGET commands:
> MSET bike:1 "Deimos" bike:2 "Ares" bike:3 "Vanth" OK > MGET bike:1 bike:2 bike:3 1) "Deimos" 2) "Ares" 3) "Vanth"
res5 = r.mset({"bike:1": "Deimos", "bike:2": "Ares", "bike:3": "Vanth"})
print(res5) # True
res6 = r.mget(["bike:1", "bike:2", "bike:3"])
print(res6) # ['Deimos', 'Ares', 'Vanth']
const res5 = await client.mSet([
["bike:1", "Deimos"],
["bike:2", "Ares"],
["bike:3", "Vanth"]
]);
console.log(res5); // OK
const res6 = await client.mGet(["bike:1", "bike:2", "bike:3"]);
console.log(res6); // ['Deimos', 'Ares', 'Vanth']
String res5 = jedis.mset("bike:1", "Deimos", "bike:2", "Ares", "bike:3", "Vanth");
System.out.println(res5); // OK
List<String> res6 = jedis.mget("bike:1", "bike:2", "bike:3");
System.out.println(res6); // [Deimos, Ares, Vanth]
Map<String, String> bikeMap = new HashMap<>();
bikeMap.put("bike:1", "Deimos");
bikeMap.put("bike:2", "Ares");
bikeMap.put("bike:3", "Vanth");
CompletableFuture<Void> mset = asyncCommands.mset(bikeMap).thenCompose(v -> {
System.out.println(v); // >>> OK
return asyncCommands.mget("bike:1", "bike:2", "bike:3");
})
.thenAccept(System.out::println)
// >>> [KeyValue[bike:1, Deimos], KeyValue[bike:2, Ares], KeyValue[bike:3,
// Vanth]]
.toCompletableFuture();
-
Atomically returns the string values of one or more keys.
-
mget(
- keys: K... // the keys.
-
mget(
- channel: KeyValueStreamingChannel<K, V>, // the channel.
- keys: K... // the keys.
-
mget(
Map<String, String> bikeMap = new HashMap<>();
bikeMap.put("bike:1", "Deimos");
bikeMap.put("bike:2", "Ares");
bikeMap.put("bike:3", "Vanth");
Mono<Void> mset = reactiveCommands.mset(bikeMap).doOnNext(System.out::println) // OK
.flatMap(v -> reactiveCommands.mget("bike:1", "bike:2", "bike:3").collectList()).doOnNext(res -> {
System.out.println(res); // [KeyValue[bike:1, Deimos], KeyValue[bike:2, Ares], KeyValue[bike:3, Vanth]]
}).then();
-
Atomically returns the string values of one or more keys.
-
mget(
- keys: K... // the keys.
-
mget(
- channel: KeyValueStreamingChannel<K, V>, // the channel.
- keys: K... // the keys.
-
mget(
res6, err := rdb.MSet(ctx, "bike:1", "Deimos", "bike:2", "Ares", "bike:3", "Vanth").Result()
if err != nil {
panic(err)
}
fmt.Println(res6) // >>> OK
res7, err := rdb.MGet(ctx, "bike:1", "bike:2", "bike:3").Result()
if err != nil {
panic(err)
}
fmt.Println(res7) // >>> [Deimos Ares Vanth]
var res5 = db.StringSet([
new ("bike:1", "Deimos"), new("bike:2", "Ares"), new("bike:3", "Vanth")
]);
Console.WriteLine(res5);
var res6 = db.StringGet(["bike:1", "bike:2", "bike:3"]);
Console.WriteLine(string.Join(", ", res6));
$res5 = $r->mset([
'bike:1' => 'Deimos', 'bike:2' => 'Ares', 'bike:3' => 'Vanth'
]);
echo "$res5" . PHP_EOL;
// >>> OK
$res6 = $r->mget(['bike:1', 'bike:2', 'bike:3']);
echo json_encode($res6) . PHP_EOL;
// >>> ["Deimos","Ares","Vanth"]
res5 = r.mset('bike:1', 'Deimos', 'bike:2', 'Ares', 'bike:3', 'Vanth')
puts res5 # >>> OK
res6 = r.mget('bike:1', 'bike:2', 'bike:3')
puts res6.inspect # >>> ["Deimos", "Ares", "Vanth"]
if let Ok(res) = r.mset(&[("bike:1", "Deimos"), ("bike:2", "Ares"), ("bike:3", "Vanth")]) {
let res: String = res;
println!("{res}"); // >>> OK
}
match r.mget(&["bike:1", "bike:2", "bike:3"]) {
Ok(res) => {
let res: Vec<String> = res;
println!("{res:?}"); // >>> ["Deimos", "Ares", "Vanth"]
},
Err(e) => {
println!("Error getting values: {e}");
return;
}
};
if let Ok(res) = r.mset(&[("bike:1", "Deimos"), ("bike:2", "Ares"), ("bike:3", "Vanth")]).await {
let res: String = res;
println!("{res}"); // >>> OK
}
match r.mget(&["bike:1", "bike:2", "bike:3"]).await {
Ok(res) => {
let res: Vec<String> = res;
println!("{res:?}"); // >>> ["Deimos", "Ares", "Vanth"]
},
Err(e) => {
println!("Error getting foo: {e}");
return;
}
};
When MGET is used, Redis returns an array of values.
Strings as counters
Even if strings are the basic values of Redis, there are interesting operations you can perform with them. For instance, one is atomic increment:
> SET total_crashes 0 OK > INCR total_crashes (integer) 1 > INCRBY total_crashes 10 (integer) 11
r.set("total_crashes", 0)
res7 = r.incr("total_crashes")
print(res7) # 1
res8 = r.incrby("total_crashes", 10)
print(res8) # 11
-
Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.
-
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
-
set(
await client.set("total_crashes", 0);
const res7 = await client.incr("total_crashes");
console.log(res7); // 1
const res8 = await client.incrBy("total_crashes", 10);
console.log(res8); // 11
jedis.set("total_crashes", "0");
Long res7 = jedis.incr("total_crashes");
System.out.println(res7); // 1
Long res8 = jedis.incrBy("total_crashes", 10);
System.out.println(res8); // 11
-
Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.
-
set(
- key: byte[],
- value: byte[]
-
set(
- key: byte[],
- value: byte[],
- params: SetParams // key if it already exists. EX|PX, expire time units: EX = seconds; PX = milliseconds
-
set(
- key: String,
- value: String
-
set(
- key: String,
- value: String,
- params: SetParams // key if it already exists. EX|PX, expire time units: EX = seconds; PX = milliseconds
-
set(
-
Increments the integer value of a key by one. Uses 0 as initial value if the key doesn't exist.
-
incrBy(
- key: byte[],
- increment: long
-
incr(
- key: byte[]
-
incrBy(
- key: String,
- increment: long
-
incr(
- key: String
-
incrBy(
-
Increments the integer value of a key by a number. Uses 0 as initial value if the key doesn't exist.
-
incrBy(
- key: byte[],
- increment: long
-
incr(
- key: byte[]
-
incrBy(
- key: String,
- increment: long
-
incr(
- key: String
-
incrBy(
CompletableFuture<Void> incrby = asyncCommands.set("total_crashes", "0")
.thenCompose(v -> asyncCommands.incr("total_crashes")).thenCompose(v -> {
System.out.println(v); // >>> 1
return asyncCommands.incrby("total_crashes", 10);
})
.thenAccept(System.out::println) // >>> 11
.toCompletableFuture();
-
Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.
-
set(
- key: K, // the key.
- value: V // the value.
-
set(
- key: K, // the key.
- value: V, // the value.
- setArgs: SetArgs // the setArgs.
-
set(
-
Increments the integer value of a key by one. Uses 0 as initial value if the key doesn't exist.
-
incr(
- key: K // the key.
-
incrby(
- key: K, // the key.
- amount: long // the increment type: long.
-
incr(
-
Increments the integer value of a key by a number. Uses 0 as initial value if the key doesn't exist.
-
incr(
- key: K // the key.
-
incrby(
- key: K, // the key.
- amount: long // the increment type: long.
-
incr(
Mono<Void> incrby = reactiveCommands.set("total_crashes", "0").flatMap(v -> reactiveCommands.incr("total_crashes"))
.doOnNext(v -> {
System.out.println(v); // 1
}).flatMap(v -> reactiveCommands.incrby("total_crashes", 10)).doOnNext(res -> {
System.out.println(res); // 11
}).then();
-
Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.
-
set(
- key: K, // the key.
- value: V // the value.
-
set(
- key: K, // the key.
- value: V, // the value.
- setArgs: SetArgs // the setArgs.
-
set(
-
Increments the integer value of a key by one. Uses 0 as initial value if the key doesn't exist.
-
incr(
- key: K // the key.
-
incrby(
- key: K, // the key.
- amount: long // the increment type: long.
-
incr(
-
Increments the integer value of a key by a number. Uses 0 as initial value if the key doesn't exist.
-
incr(
- key: K // the key.
-
incrby(
- key: K, // the key.
- amount: long // the increment type: long.
-
incr(
res8, err := rdb.Set(ctx, "total_crashes", "0", 0).Result()
if err != nil {
panic(err)
}
fmt.Println(res8) // >>> OK
res9, err := rdb.Incr(ctx, "total_crashes").Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> 1
res10, err := rdb.IncrBy(ctx, "total_crashes", 10).Result()
if err != nil {
panic(err)
}
fmt.Println(res10) // >>> 11
-
Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.
-
Set(
- ctx: context.Context,
- key: string,
- value: interface{},
- expiration: time.Duration
-
SetArgs(
- ctx: context.Context,
- key: string,
- value: interface{},
- a: SetArgs // Mode can be `NX`, `XX`, `IFEQ`, `IFNE`, `IFDEQ`, `IFDNE` or empty. MatchValue is used with IFEQ/IFNE; MatchDigest (a uint64 xxh3 hash) is used with IFDEQ/IFDNE.
-
SetIFEQ(
- ctx: context.Context,
- key: string,
- value: interface{},
- matchValue: interface{},
- expiration: time.Duration // Zero expiration means the key has no expiration time.
-
SetIFNE(
- ctx: context.Context,
- key: string,
- value: interface{},
- matchValue: interface{},
- expiration: time.Duration // Zero expiration means the key has no expiration time.
-
SetIFDEQ(
- ctx: context.Context,
- key: string,
- value: interface{},
- matchDigest: uint64, // A uint64 xxh3 hash value.
- expiration: time.Duration // Zero expiration means the key has no expiration time.
-
SetIFDNE(
- ctx: context.Context,
- key: string,
- value: interface{},
- matchDigest: uint64, // A uint64 xxh3 hash value.
- expiration: time.Duration // Zero expiration means the key has no expiration time.
-
Set(
db.StringSet("total_crashes", 0);
var res7 = db.StringIncrement("total_crashes");
Console.WriteLine(res7); // 1
var res8 = db.StringIncrement("total_crashes", 10);
Console.WriteLine(res8);
-
Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.
-
StringSet(
- key: RedisKey,
- value: RedisValue,
- expiry: TimeSpan?, // The expiry to set.
- when: When // Which condition to set the value under (defaults to always).
-
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.
-
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.
-
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.
-
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.
-
StringSet(
-
Increments the integer value of a key by one. Uses 0 as initial value if the key doesn't exist.
-
StringIncrement(
- key: RedisKey, // The key of the string.
- value: long, // The amount to increment by (defaults to 1).
- flags: CommandFlags // The flags to use for this operation.
-
StringIncrement(
- key: RedisKey, // The key of the string.
- value: double, // The amount to increment by (defaults to 1).
- flags: CommandFlags // The flags to use for this operation.
-
StringIncrement(
- key: Any, // The key of the string.
- -value: Any,
- flags: Any // The flags to use for this operation.
-
StringIncrement(
- key: Any, // The key of the string.
- -value: Any,
- flags: Any // The flags to use for this operation.
-
StringIncrement(
- key: RedisKey, // The key of the string.
- value: long, // The amount to increment by (defaults to 1).
- flags: CommandFlags // The flags to use for this operation.
-
StringIncrement(
-
Increments the integer value of a key by a number. Uses 0 as initial value if the key doesn't exist.
-
StringIncrement(
- key: RedisKey, // The key of the string.
- value: long, // The amount to increment by (defaults to 1).
- flags: CommandFlags // The flags to use for this operation.
-
StringIncrement(
- key: RedisKey, // The key of the string.
- value: double, // The amount to increment by (defaults to 1).
- flags: CommandFlags // The flags to use for this operation.
-
StringIncrement(
- key: Any, // The key of the string.
- -value: Any,
- flags: Any // The flags to use for this operation.
-
StringIncrement(
- key: Any, // The key of the string.
- -value: Any,
- flags: Any // The flags to use for this operation.
-
StringIncrement(
- key: RedisKey, // The key of the string.
- value: long, // The amount to increment by (defaults to 1).
- flags: CommandFlags // The flags to use for this operation.
-
StringIncrement(
$r->set('total_crashes', 0);
$res7 = $r->incr('total_crashes');
echo "$res7" . PHP_EOL;
// >>> 1
$res8 = $r->incrby('total_crashes', 10);
echo "$res8" . PHP_EOL;
// >>> 11
r.set('total_crashes', 0)
res7 = r.incr('total_crashes')
puts res7 # >>> 1
res8 = r.incrby('total_crashes', 10)
puts res8 # >>> 11
-
Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.
-
set(
- key: String,
- value: String,
- ex: Integer, // Set the specified expire time, in seconds.
- px: Integer, // Set the specified expire time, in milliseconds.
- exat: Integer, // Set the specified Unix time at which the key will expire, in seconds.
- pxat: Integer, // Set the specified Unix time at which the key will expire, in milliseconds.
- nx: Boolean, // Only set the key if it does not already exist.
- xx: Boolean, // Only set the key if it already exists.
- keepttl: Boolean, // Retain the time to live associated with the key.
- get: Boolean // Return the old string stored at key, or nil if key did not exist.
-
set(
if let Ok(res) = r.set("total_crashes", 0) {
let res: String = res;
println!("{res}"); // >>> OK
}
if let Ok(res) = r.incr("total_crashes", 1) {
let res: i32 = res;
println!("{res}"); // >>> 1
}
if let Ok(res) = r.incr("total_crashes", 10) {
let res: i32 = res;
println!("{res}"); // >>> 11
}
if let Ok(res) = r.set("total_crashes", 0).await {
let res: String = res;
println!("{res}"); // >>> OK
}
if let Ok(res) = r.incr("total_crashes", 1).await {
let res: i32 = res;
println!("{res}"); // >>> 1
}
if let Ok(res) = r.incr("total_crashes", 10).await {
let res: i32 = res;
println!("{res}"); // >>> 11
}
The INCR command parses the string value as an integer,
increments it by one, and finally sets the obtained value as the new value.
There are other similar commands like INCRBY,
DECR and DECRBY. Internally it's
always the same command, acting in a slightly different way.
What does it mean that INCR is atomic? That even multiple clients issuing INCR against the same key will never enter into a race condition. For instance, it will never happen that client 1 reads "10", client 2 reads "10" at the same time, both increment to 11, and set the new value to 11. The final value will always be 12 and the read-increment-set operation is performed while all the other clients are not executing a command at the same time.
Limits
By default, a single Redis string can be a maximum of 512 MB.
Bitwise and bitfield operations
To perform bitwise operations on a string, see the bitmaps data type docs. To store and manipulate integer values within a string, see the bitfields data type docs.
Performance
Most string operations are O(1), which means they're highly efficient.
However, be careful with the SUBSTR, GETRANGE, and SETRANGE commands, which can be O(n).
These random-access string commands may cause performance issues when dealing with large strings.
Alternatives
If you're storing structured data as a serialized string, you may also want to consider Redis hashes or JSON.
Learn more
- Redis Strings Explained is a short, comprehensive video explainer on Redis strings.
- Redis University's RU101 covers Redis strings in detail.