setrange.3valkey - Man Page
Overwrites a part of a string value with another by an offset. Creates the key if it doesn’t exist.
Synopsis
SETRANGE
key offset value
Description
Overwrites part of the string stored at key, starting at the specified offset, for the entire length of value. If the offset is larger than the current length of the string at key, the string is padded with zero-bytes to make offset fit. Non-existing keys are considered as empty strings, so this command will make sure it holds a string large enough to be able to set value at offset.
Note that the maximum offset that you can set is 2^29 -1 (536870911), as Valkey Strings are limited to 512 megabytes. If you need to grow beyond this size, you can use multiple keys.
Warning: When setting the last possible byte and the string value stored at key does not yet hold a string value, or holds a small string value, Valkey needs to allocate all intermediate memory which can block the server for some time. On a 2010 MacBook Pro, setting byte number 536870911 (512MB allocation) takes ~300ms, setting byte number 134217728 (128MB allocation) takes ~80ms, setting bit number 33554432 (32MB allocation) takes ~30ms and setting bit number 8388608 (8MB allocation) takes ~8ms. Note that once this first allocation is done, subsequent calls to SETRANGE
for the same key will not have the allocation overhead.
Patterns
Thanks to SETRANGE
and the analogous GETRANGE
commands, you can use Valkey strings as a linear array with O(1) random access. This is a very fast and efficient storage in many real world use cases.
Reply
valkey-protocol(7) Integer reply: the length of the string after it was modified by the command.
Complexity
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.
Acl Categories
@slow @string @write
History
- Available since: 2.2.0
Examples
Basic usage:
127.0.0.1:6379> SET key1 "Hello World" OK 127.0.0.1:6379> SETRANGE key1 6 "Valkey" (integer) 12 127.0.0.1:6379> GET key1 "Hello Valkey"
Example of zero padding:
127.0.0.1:6379> SETRANGE key2 6 "Valkey" (integer) 12 127.0.0.1:6379> GET key2 "\x00\x00\x00\x00\x00\x00Valkey"
See Also
append(3valkey), decr(3valkey), decrby(3valkey), get(3valkey), getdel(3valkey), getex(3valkey), getrange(3valkey), incr(3valkey), incrby(3valkey), incrbyfloat(3valkey), lcs(3valkey), mget(3valkey), mset(3valkey), msetnx(3valkey), set(3valkey), strlen(3valkey)