title: SETBIT

summary: Sets or clears the bit at offset of the string value. Creates the key if it doesn't exist.

title: Overview

text:
Sets or clears the bit at _offset_ in the string value stored at _key_.

The bit is either set or cleared depending on _value_, which can be either 0 or
1.

When _key_ does not exist, a new string value is created.
The string is grown to make sure it can hold a bit at _offset_.
The _offset_ argument is required to be greater than or equal to 0, and smaller
than 2^32 (this limits bitmaps to 512MB).
When the string at _key_ is grown, added bits are set to 0.

**Warning**: When setting the last possible bit (_offset_ equal to 2^32 -1) and
the string value stored at _key_ does not yet hold a string value, or holds a
small string value, Redis needs to allocate all intermediate memory which can
block the server for some time.
On a 2010 MacBook Pro, setting bit number 2^32 -1 (512MB allocation) takes
~300ms, setting bit number 2^30 -1 (128MB allocation) takes ~80ms, setting bit
number 2^28 -1 (32MB allocation) takes ~30ms and setting bit number 2^26 -1 (8MB
allocation) takes ~8ms.
Note that once this first allocation is done, subsequent calls to `SETBIT` for
the same _key_ will not have the allocation overhead.

title: Examples

text:
SETBIT mykey 7 1
SETBIT mykey 7 0
GET mykey

title: Pattern: accessing the entire bitmap

text:
There are cases when you need to set all the bits of single bitmap at once, for
example when initializing it to a default non-zero value. It is possible to do
this with multiple calls to the `SETBIT` command, one for each bit that needs to
be set. However, so as an optimization you can use a single [`SET`]() command to set
the entire bitmap.

Bitmaps are not an actual data type, but a set of bit-oriented operations
defined on the String type (for more information refer to the
[Bitmaps section of the Data Types Introduction page][ti]). This means that
bitmaps can be used with string commands, and most importantly with [`SET`]() and
[`GET`]().

Because Redis' strings are binary-safe, a bitmap is trivially encoded as a bytes
stream. The first byte of the string corresponds to offsets 0..7 of
the bitmap, the second byte to the 8..15 range, and so forth.

For example, after setting a few bits, getting the string value of the bitmap
would look like this:

[code example]

By getting the string representation of a bitmap, the client can then parse the
response's bytes by extracting the bit values using native bit operations in its
native programming language. Symmetrically, it is also possible to set an entire
bitmap by performing the bits-to-bytes encoding in the client and calling [`SET`]()
with the resultant string.

[ti]: /develop/data-types-intro#bitmaps

title: Pattern: setting multiple bits

text:
`SETBIT` excels at setting single bits, and can be called several times when
multiple bits need to be set. To optimize this operation you can replace
multiple `SETBIT` calls with a single call to the variadic [`BITFIELD`]() command
and the use of fields of type `u1`.

For example, the example above could be replaced by:

[code example]

title: Advanced Pattern: accessing bitmap ranges

text:
It is also possible to use the [`GETRANGE`]() and [`SETRANGE`]() string commands to
efficiently access a range of bit offsets in a bitmap. Below is a sample
implementation in idiomatic Redis Lua scripting that can be run with the [`EVAL`]()
command:

[code example]

**Note:** the implementation for getting a range of bit offsets from a bitmap is
left as an exercise to the reader.

title: Return information

text:
**RESP2:**

[Integer reply](../../develop/reference/protocol-spec#integers): the original bit value stored at _offset_.

**RESP3:**

[Integer reply](../../develop/reference/protocol-spec#integers): the original bit value stored at _offset_.

code:
> SETBIT bitmapsarestrings 2 1
> SETBIT bitmapsarestrings 3 1
> SETBIT bitmapsarestrings 5 1
> SETBIT bitmapsarestrings 10 1
> SETBIT bitmapsarestrings 11 1
> SETBIT bitmapsarestrings 14 1
> GET bitmapsarestrings
"42"

section_id: pattern-accessing-the-entire-bitmap

code: > BITFIELD bitsinabitmap SET u1 2 1 SET u1 3 1 SET u1 5 1 SET u1 10 1 SET u1 11 1 SET u1 14 1

section_id: pattern-setting-multiple-bits

code:
--[[
Sets a bitmap range

Bitmaps are stored as Strings in Redis. A range spans one or more bytes,
so we can call [`SETRANGE`]() when entire bytes need to be set instead of flipping
individual bits. Also, to avoid multiple internal memory allocations in
Redis, we traverse in reverse.
Expected input:
  KEYS[1] - bitfield key
  ARGV[1] - start offset (0-based, inclusive)
  ARGV[2] - end offset (same, should be bigger than start, no error checking)
  ARGV[3] - value (should be 0 or 1, no error checking)
]]--

-- A helper function to stringify a binary string to semi-binary format
local function tobits(str)
  local r = ''
  for i = 1, string.len(str) do
    local c = string.byte(str, i)
    local b = ' '
    for j = 0, 7 do
      b = tostring(bit.band(c, 1)) .. b
      c = bit.rshift(c, 1)
    end
    r = r .. b
  end
  return r
end

-- Main
local k = KEYS[1]
local s, e, v = tonumber(ARGV[1]), tonumber(ARGV[2]), tonumber(ARGV[3])

-- First treat the dangling bits in the last byte
local ms, me = s % 8, (e + 1) % 8
if me > 0 then
  local t = math.max(e - me + 1, s)
  for i = e, t, -1 do
    redis.call('SETBIT', k, i, v)
  end
  e = t
end

-- Then the danglings in the first byte
if ms > 0 then
  local t = math.min(s - ms + 7, e)
  for i = s, t, 1 do
    redis.call('SETBIT', k, i, v)
  end
  s = t + 1
end

-- Set a range accordingly, if at all
local rs, re = s / 8, (e + 1) / 8
local rl = re - rs
if rl > 0 then
  local b = '\255'
  if 0 == v then
    b = '\0'
  end
  redis.call('SETRANGE', k, rs, string.rep(b, rl))
end


title: SETEX

summary: Sets the string value and expiration time of a key. Creates the key if it doesn't exist.

page_type: content

title: Overview

role: overview

text:
Set `key` to hold the string `value` and set `key` to timeout after a given
number of seconds.
This command is equivalent to:

[code example]

An error is returned when `seconds` is invalid.

title: Examples

role: example

text:
SETEX mykey 10 "Hello"
TTL mykey
GET mykey

title: See also

role: related

text: [`TTL`]()

title: Redis Software and Redis Cloud compatibility

role: content

text:
| Redis
Software | Redis
Cloud | Notes |
|:----------------------|:-----------------|:------|
| ✅ Standard
<nobr>✅ Active-Active</nobr> | ✅ Standard
<nobr>✅ Active-Active</nobr> |  |

title: Return information

role: returns

text:
**RESP2:**

[Simple string reply](../../develop/reference/protocol-spec#simple-strings): `OK`.

**RESP3:**

[Simple string reply](../../develop/reference/protocol-spec#simple-strings): `OK`.

code: SET key value EX seconds

section_id: overview


title: SETNX

summary: Set the string value of a key only when the key doesn't exist.

title: Overview

text:
Set `key` to hold string `value` if `key` does not exist.
In that case, it is equal to [`SET`]().
When `key` already holds a value, no operation is performed.
`SETNX` is short for "**SET** if **N**ot e**X**ists".

title: Examples

text:
SETNX mykey "Hello"
SETNX mykey "World"
GET mykey

title: Design pattern: Locking with `SETNX`

text:
**Please note that:**

1. 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.
2. We document the old pattern anyway because certain existing implementations link to this page as a reference. Moreover it is an interesting example of how Redis commands can be used in order to mount programming primitives.
3. Anyway even assuming a single-instance locking primitive, starting with 2.6.12 it is possible to create a much simpler locking primitive, equivalent to the one discussed here, using the [`SET`]() command to acquire the lock, and a simple Lua script to release the lock. The pattern is documented in the [`SET`]() command page.

That said, `SETNX` can be used, and was historically used, as a locking primitive. For example, to acquire the lock of the key `foo`, the client could try the
following:

[code example]

If `SETNX` returns `1` the client acquired the lock, setting the `lock.foo` key
to the Unix time at which the lock should no longer be considered valid.
The client will later use `DEL lock.foo` in order to release the lock.

If `SETNX` returns `0` the key is already locked by some other client.
We can either return to the caller if it's a non blocking lock, or enter a loop
retrying to hold the lock until we succeed or some kind of timeout expires.

title: Handling deadlocks

text:
In the above locking algorithm there is a problem: what happens if a client
fails, crashes, or is otherwise not able to release the lock?
It's possible to detect this condition because the lock key contains a UNIX
timestamp.
If such a timestamp is equal to the current Unix time the lock is no longer
valid.

When this happens we can't just call [`DEL`]() against the key to remove the lock
and then try to issue a `SETNX`, as there is a race condition here, when
multiple clients detected an expired lock and are trying to release it.

* C1 and C2 read `lock.foo` to check the timestamp, because they both received
  `0` after executing `SETNX`, as the lock is still held by C3 that crashed
  after holding the lock.
* C1 sends `DEL lock.foo`
* C1 sends `SETNX lock.foo` and it succeeds
* C2 sends `DEL lock.foo`
* C2 sends `SETNX lock.foo` and it succeeds
* **ERROR**: both C1 and C2 acquired the lock because of the race condition.

Fortunately, it's possible to avoid this issue using the following algorithm.
Let's see how C4, our sane client, uses the good algorithm:

*   C4 sends `SETNX lock.foo` in order to acquire the lock

*   The crashed client C3 still holds it, so Redis will reply with `0` to C4.

*   C4 sends `GET lock.foo` to check if the lock expired.
    If it is not, it will sleep for some time and retry from the start.

*   Instead, if the lock is expired because the Unix time at `lock.foo` is older
    than the current Unix time, C4 tries to perform:

    [code example]

*   Because of the [`GETSET`]() semantic, C4 can check if the old value stored at
    `key` is still an expired timestamp.
    If it is, the lock was acquired.

*   If another client, for instance C5, was faster than C4 and acquired the lock
    with the [`GETSET`]() operation, the C4 [`GETSET`]() operation will return a non
    expired timestamp.
    C4 will simply restart from the first step.
    Note that even if C4 set the key a bit a few seconds in the future this is
    not a problem.

In order to make this locking algorithm more robust, a
client holding a lock should always check the timeout didn't expire before
unlocking the key with [`DEL`]() because client failures can be complex, not just
crashing but also blocking a lot of time against some operations and trying
to issue [`DEL`]() after a lot of time (when the LOCK is already held by another
client).

title: Return information

text:
**RESP2:**

One of the following:
* [Integer reply](../../develop/reference/protocol-spec#integers): `0` if the key was not set.
* [Integer reply](../../develop/reference/protocol-spec#integers): `1` if the key was set.

**RESP3:**

One of the following:
* [Integer reply](../../develop/reference/protocol-spec#integers): `0` if the key was not set.
* [Integer reply](../../develop/reference/protocol-spec#integers): `1` if the key was set.

code: SETNX lock.foo <current Unix time + lock timeout + 1>

section_id: design-pattern-locking-with-setnx

code: GETSET lock.foo <current Unix timestamp + lock timeout + 1>

section_id: handling-deadlocks


title: SETRANGE

summary: Overwrites a part of a string value with another by an offset. Creates the key if it doesn't exist.

title: Overview

text:
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 Redis
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, Redis
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.

title: Patterns

text:
Thanks to `SETRANGE` and the analogous [`GETRANGE`]() commands, you can use Redis
strings as a linear array with O(1) random access.
This is a very fast and efficient storage in many real world use cases.

title: Examples

text:
Basic usage:

SET key1 "Hello World"
SETRANGE key1 6 "Redis"
GET key1

Example of zero padding:

SETRANGE key2 6 "Redis"
GET key2

title: Return information

text:
**RESP2:**

[Integer reply](../../develop/reference/protocol-spec#integers): the length of the string after it was modified by the command.

**RESP3:**

[Integer reply](../../develop/reference/protocol-spec#integers): the length of the string after it was modified by the command.


title: SHUTDOWN

summary: Synchronously saves the database(s) to disk and shuts down the Redis server.

title: Overview

text:
The command behavior is the following:

* If there are any replicas lagging behind in replication:
  * Pause clients attempting to write by performing a [`CLIENT PAUSE`]() with the `WRITE` option.
  * Wait up to the configured `shutdown-timeout` (default 10 seconds) for replicas to catch up the replication offset.
* Stop all the clients.
* Perform a blocking SAVE if at least one **save point** is configured.
* Flush the Append Only File if AOF is enabled.
* Quit the server.

If persistence is enabled this commands makes sure that Redis is switched off
without any data loss.

Note: A Redis instance that is configured for not persisting on disk (no AOF
configured, nor "save" directive) will not dump the RDB file on `SHUTDOWN`, as
usually you don't want Redis instances used only for caching to block on when
shutting down.

Also note: If Redis receives one of the signals `SIGTERM` and `SIGINT`, the same shutdown sequence is performed.
See also [Signal Handling]().

title: Modifiers

text:
It is possible to specify optional modifiers to alter the behavior of the command.
Specifically:

* **SAVE** will force a DB saving operation even if no save points are configured.
* **NOSAVE** will prevent a DB saving operation even if one or more save points are configured.
* **NOW** skips waiting for lagging replicas, i.e. it bypasses the first step in the shutdown sequence.
* **FORCE** ignores any errors that would normally prevent the server from exiting.
  For details, see the following section.
* **ABORT** cancels an ongoing shutdown and cannot be combined with other flags.

title: Conditions where a SHUTDOWN fails

text:
When a save point is configured or the **SAVE** modifier is specified, the shutdown may fail if the RDB file can't be saved.
Then, the server continues to run in order to ensure no data loss.
This may be bypassed using the **FORCE** modifier, causing the server to exit anyway.

When the Append Only File is enabled the shutdown may fail because the
system is in a state that does not allow to safely immediately persist
on disk.

Normally if there is an AOF child process performing an AOF rewrite, Redis
will simply kill it and exit.
However, there are situations where it is unsafe to do so and, unless the **FORCE** modifier is specified, the **SHUTDOWN** command will be refused with an error instead.
This happens in the following situations:

* The user just turned on AOF, and the server triggered the first AOF rewrite in order to create the initial AOF file. In this context, stopping will result in losing the dataset at all: once restarted, the server will potentially have AOF enabled without having any AOF file at all.
* A replica with AOF enabled, reconnected with its master, performed a full resynchronization, and restarted the AOF file, triggering the initial AOF creation process. In this case not completing the AOF rewrite is dangerous because the latest dataset received from the master would be lost. The new master can actually be even a different instance (if the **REPLICAOF** or **SLAVEOF** command was used in order to reconfigure the replica), so it is important to finish the AOF rewrite and start with the correct data set representing the data set in memory when the server was terminated.

There are situations when we want just to terminate a Redis instance ASAP, regardless of what its content is.
In such a case, the command **SHUTDOWN NOW NOSAVE FORCE** can be used.
In versions before 7.0, where the **NOW** and **FORCE** flags are not available, the right combination of commands is to send a **CONFIG appendonly no** followed by a **SHUTDOWN NOSAVE**.
The first command will turn off the AOF if needed, and will terminate the AOF rewriting child if there is one active.
The second command will not have any problem to execute since the AOF is no longer enabled.

title: Minimize the risk of data loss

text:
Since Redis 7.0, the server waits for lagging replicas up to a configurable `shutdown-timeout`, by default 10 seconds, before shutting down.
This provides a best effort minimizing the risk of data loss in a situation where no save points are configured and AOF is disabled.
Before version 7.0, shutting down a heavily loaded master node in a diskless setup was more likely to result in data loss.
To minimize the risk of data loss in such setups, it's advised to trigger a manual [`FAILOVER`]() (or [`CLUSTER FAILOVER`]()) to demote the master to a replica and promote one of the replicas to be the new master, before shutting down a master node.

title: Behavior change history

text: *   `>= 7.0.0`: Introduced waiting for lagging replicas before exiting.

text:
| Redis
Software | Redis
Cloud | Notes |
|:----------------------|:-----------------|:------|
| ❌ Standard
<nobr>❌ Active-Active</nobr> | ❌ Standard
<nobr>❌ Active-Active</nobr> |  |

title: Return information

text:
**RESP2:**

[Simple string reply](../../develop/reference/protocol-spec#simple-strings): `OK` if _ABORT_ was specified and shutdown was aborted. On successful shutdown, nothing is returned because the server quits and the connection is closed. On failure, an error is returned.

**RESP3:**

[Simple string reply](../../develop/reference/protocol-spec#simple-strings): `OK` if _ABORT_ was specified and shutdown was aborted. On successful shutdown, nothing is returned because the server quits and the connection is closed. On failure, an error is returned.


title: SINTER

summary: Returns the intersect of multiple sets.

title: Overview

text:
This command's behavior varies in clustered Redis environments. See the [multi-key operations]() page for more information.

Returns the members of the set resulting from the intersection of all the given
sets.

For example:

[code example]

Keys that do not exist are considered to be empty sets.
With one of the keys being an empty set, the resulting set is also empty (since
set intersection with an empty set always results in an empty set).

title: Examples

text:
SADD key1 "a"
SADD key1 "b"
SADD key1 "c"
SADD key2 "c"
SADD key2 "d"
SADD key2 "e"
SINTER key1 key2

text:
| Redis
Software | Redis
Cloud | Notes |
|:----------------------|:-----------------|:------|
| ✅ Standard
<nobr>✅ Active-Active</nobr> | ✅ Standard
<nobr>✅ Active-Active</nobr> |  |

title: Return information

text:
**RESP2:**

[Array reply](../../develop/reference/protocol-spec#arrays): an array with the members of the resulting set.

**RESP3:**

[Set reply](../../develop/reference/protocol-spec#sets): a set with the members of the resulting set.

code:
key1 = {a,b,c,d}
key2 = {c}
key3 = {a,c,e}
SINTER key1 key2 key3 = {c}


title: SINTERCARD

summary: Returns the number of members of the intersect of multiple sets.

title: Overview

text:
This command's behavior varies in clustered Redis environments. See the [multi-key operations]() page for more information.

This command is similar to [`SINTER`](), but instead of returning the result set, it returns just the cardinality of the result.
Returns the cardinality of the set which would result from the intersection of all the given sets.

Keys that do not exist are considered to be empty sets.
With one of the keys being an empty set, the resulting set is also empty (since set intersection with an empty set always results in an empty set).

By default, the command calculates the cardinality of the intersection of all given sets.
When provided with the optional `LIMIT` argument (which defaults to 0 and means unlimited), if the intersection cardinality reaches limit partway through the computation, the algorithm will exit and yield limit as the cardinality.
Such implementation ensures a significant speedup for queries where the limit is lower than the actual intersection cardinality.

title: Examples

text:
SADD key1 "a"
SADD key1 "b"
SADD key1 "c"
SADD key1 "d"
SADD key2 "c"
SADD key2 "d"
SADD key2 "e"
SINTER key1 key2
SINTERCARD 2 key1 key2
SINTERCARD 2 key1 key2 LIMIT 1

title: Return information

text:
**RESP2:**

[Integer reply](../../develop/reference/protocol-spec#integers): the number of elements in the resulting intersection.

**RESP3:**

[Integer reply](../../develop/reference/protocol-spec#integers): the number of elements in the resulting intersection.


title: SINTERSTORE

summary: Stores the intersect of multiple sets in a key.

title: Overview

text:
This command's behavior varies in clustered Redis environments. See the [multi-key operations]() page for more information.

This command is equal to [`SINTER`](), but instead of returning the resulting set,
it is stored in `destination`.

If `destination` already exists, it is overwritten.

title: Examples

text:
SADD key1 "a"
SADD key1 "b"
SADD key1 "c"
SADD key2 "c"
SADD key2 "d"
SADD key2 "e"
SINTERSTORE key key1 key2
SMEMBERS key

title: Return information

text:
**RESP2:**

[Integer reply](../../develop/reference/protocol-spec#integers): the number of elements in the resulting set.

**RESP3:**

[Integer reply](../../develop/reference/protocol-spec#integers): the number of elements in the result set.


title: SISMEMBER

summary: Determines whether a member belongs to a set.

title: Overview

text: Returns if `member` is a member of the set stored at `key`.

title: Examples

text:
SADD myset "one"
SISMEMBER myset "one"
SISMEMBER myset "two"

title: Return information

text:
**RESP2:**

One of the following:
* [Integer reply](../../develop/reference/protocol-spec#integers): `0` if the element is not a member of the set, or when the key does not exist.
* [Integer reply](../../develop/reference/protocol-spec#integers): `1` if the element is a member of the set.

**RESP3:**

One of the following:
* [Integer reply](../../develop/reference/protocol-spec#integers): `0` if the element is not a member of the set, or when the key does not exist.
* [Integer reply](../../develop/reference/protocol-spec#integers): `1` if the element is a member of the set.


title: SLAVEOF

summary: Sets a Redis server as a replica of another, or promotes it to being a master.

title: Overview

text:
**A note about the word slave used in this man page and command name**: starting with Redis version 5, if not for backward compatibility, the Redis project no longer uses the word slave. Please use the new command [`REPLICAOF`](). The command `SLAVEOF` will continue to work for backward compatibility.

The `SLAVEOF` command can change the replication settings of a replica on the fly.
If a Redis server is already acting as replica, the command `SLAVEOF` NO ONE will
turn off the replication, turning the Redis server into a MASTER.
In the proper form `SLAVEOF` hostname port will make the server a replica of
another server listening at the specified hostname and port.

If a server is already a replica of some master, `SLAVEOF` hostname port will stop
the replication against the old server and start the synchronization against the
new one, discarding the old dataset.

The form `SLAVEOF` NO ONE will stop replication, turning the server into a
MASTER, but will not discard the replication.
So, if the old master stops working, it is possible to turn the replica into a
master and set the application to use this new master in read/write.
Later when the other Redis server is fixed, it can be reconfigured to work as a
replica.

text:
| Redis
Software | Redis
Cloud | Notes |
|:----------------------|:-----------------|:------|
| ❌ Standard
<nobr>❌ Active-Active</nobr> | ❌ Standard
<nobr>❌ Active-Active</nobr> | Deprecated as of Redis v5.0.0. |

title: Return information

text:
**RESP2:**

[Simple string reply](../../develop/reference/protocol-spec#simple-strings): `OK`.

**RESP3:**

[Simple string reply](../../develop/reference/protocol-spec#simple-strings): `OK`.


title: SLOWLOG

summary: A container for slow log commands.

title: Content

text:
The Redis Slow Log is a system to log queries that exceeded a specified execution time.
The execution time does not include I/O operations like talking with the client, just the time needed to execute the command (this is the only stage of command execution where the thread is blocked and cannot serve other requests).

A new entry is added to the slow log whenever a command exceeds the execution time threshold defined by the `slowlog-log-slower-than` configuration directive.

The maximum number of entries in the slow log is governed by the `slowlog-max-len` configuration directive.
This is a container command for slow log management commands.

See [`SLOWLOG GET`]() for a description of what's stored in the Redis slow log. To see the list of available commands use the [`SLOWLOG HELP`]() command.


title: SLOWLOG GET

summary: Returns the slow log's entries.

title: Overview

text:
The `SLOWLOG GET` command returns entries from the slow log in chronological order.

The Redis Slow Log is a system to log queries that exceeded a specified execution time.
The execution time does not include I/O operations like talking with the client, sending the reply and so forth, but just the time needed to actually execute the command (this is the only stage of command execution where the thread is blocked and can not serve other requests in the meantime).

A new entry is added to the slow log whenever a command exceeds the execution time threshold defined by the `slowlog-log-slower-than` configuration directive.
The maximum number of entries in the slow log is governed by the `slowlog-max-len` configuration directive.

By default the command returns latest ten entries in the log. The optional `count` argument limits the number of returned entries, so the command returns at most up to `count` entries, the special number -1 means return all entries.

Each entry from the slow log is comprised of the following six values:

1. A unique progressive identifier for every slow log entry.
2. The unix timestamp at which the logged command was processed.
3. The amount of time needed for its execution, in microseconds.
4. The array composing the arguments of the command.
5. Client IP address and port.
6. Client name if set via the [`CLIENT SETNAME`]() command.

The entry's unique ID can be used in order to avoid processing slow log entries multiple times (for instance you may have a script sending you an email alert for every new slow log entry).
The ID is never reset in the course of the Redis server execution, only a server
restart will reset it.

text:
| Redis
Software | Redis
Cloud | Notes |
|:----------------------|:-----------------|:------|
| ✅ Standard
<nobr>✅ Active-Active</nobr> | ✅ Standard
<nobr>✅ Active-Active</nobr> | Not supported for [scripts](). Also, the client IP address, port, and name are not returned by Redis Software. |

title: Return information

text:
**RESP2:**

[Array reply](../../develop/reference/protocol-spec#arrays): a list of slow log entries per the above format.

**RESP3:**

[Array reply](../../develop/reference/protocol-spec#arrays): a list of slow log entries per the above format.


title: SLOWLOG HELP

summary: Show helpful text about the different subcommands

title: Overview

text: The `SLOWLOG HELP` command returns a helpful text describing the different subcommands.

text:
| Redis
Software | Redis
Cloud | Notes |
|:----------------------|:-----------------|:------|
| ❌ Standard
<nobr>❌ Active-Active</nobr> | ❌ Standard
<nobr>❌ Active-Active</nobr> |  |

title: Return information

text:
**RESP2:**

[Array reply](../../develop/reference/protocol-spec#arrays): a list of sub-commands and their descriptions.

**RESP3:**

[Array reply](../../develop/reference/protocol-spec#arrays): a list of sub-commands and their descriptions.


title: SLOWLOG LEN

summary: Returns the number of entries in the slow log.

title: Overview

text:
This command returns the current number of entries in the slow log.

A new entry is added to the slow log whenever a command exceeds the execution time threshold defined by the `slowlog-log-slower-than` configuration directive.
The maximum number of entries in the slow log is governed by the `slowlog-max-len` configuration directive.
Once the slog log reaches its maximal size, the oldest entry is removed whenever a new entry is created.
The slow log can be cleared with the [`SLOWLOG RESET`]() command.

text:
| Redis
Software | Redis
Cloud | Notes |
|:----------------------|:-----------------|:------|
| ✅ Standard
<nobr>✅ Active-Active</nobr> | ✅ Standard
<nobr>✅ Active-Active</nobr> | Not supported for [scripts](). |

title: Return information

text:
**RESP2:**

[Integer reply](../../develop/reference/protocol-spec#integers): the number of entries in the slow log.

**RESP3:**

[Integer reply](../../develop/reference/protocol-spec#integers): the number of entries in the slow log.


title: SLOWLOG RESET

summary: Clears all entries from the slow log.

title: Overview

text:
This command resets the slow log, clearing all entries in it.

Once deleted the information is lost forever.

title: Return information


title: SMEMBERS

summary: Returns all members of a set.

title: Examples

text:
#### Code Examples

Foundational: Retrieve all members of a set using SMEMBERS (returns unordered collection, useful for iterating all set members)

**Difficulty:** Beginner

**Commands:** SADD, SMEMBERS

**Complexity:**
- SADD: O(1)
- SMEMBERS: O(N)

**Redis CLI:**

[code example]

**Available in:** Redis CLI, C# (Synchronous), Go, Java (Asynchronous - Lettuce), Java (Reactive - Lettuce), Java (Synchronous - Jedis), JavaScript (Node.js), PHP, Python

**C# (Synchronous):**

[code example]

**Go:**

[code example]

**Java (Asynchronous - Lettuce):**

[code example]

**Java (Reactive - Lettuce):**

[code example]

**Java (Synchronous - Jedis):**

[code example]

**JavaScript (Node.js):**

[code example]

**PHP:**

[code example]

**Python:**

[code example]

Give these commands a try in the interactive console:

SADD myset "Hello"
SADD myset "World"
SMEMBERS myset

text:
| Redis
Software | Redis
Cloud | Notes |
|:----------------------|:-----------------|:------|
| ✅ Standard
<nobr>✅ Active-Active</nobr> | ✅ Standard
<nobr>✅ Active-Active</nobr> |  |

title: Return information

text:
**RESP2:**

[Array reply](../../develop/reference/protocol-spec#arrays): an array with all the members of the set.

**RESP3:**

[Set reply](../../develop/reference/protocol-spec#sets): a set with all the members of the set.

code:
redis> SADD myset "Hello"
(integer) 1
redis> SADD myset "World"
(integer) 1
redis> SMEMBERS myset
1) "Hello"
2) "World"

section_id: examples

code:
long sMembersResult1 = db.SetAdd(
            "myset", ["Hello", "World"]
        );
        Console.WriteLine(sMembersResult1); // >>> 2

        RedisValue[] sMembersResult2 = db.SetMembers("myset");
        Array.Sort(sMembersResult2);
        Console.WriteLine(string.Join(", ", sMembersResult2));
        // >>> Hello, World

code:
sAddResult, err := rdb.SAdd(ctx, "myset", "Hello", "World").Result()

	if err != nil {
		panic(err)
	}

	fmt.Println(sAddResult) // >>> 2

	sMembersResult, err := rdb.SMembers(ctx, "myset").Result()

	if err != nil {
		panic(err)
	}

	fmt.Println(sMembersResult) // >>> [Hello World]

code:
CompletableFuture<Void> smembers = asyncCommands.sadd("myset", "Hello", "World").thenCompose(r -> {
                return asyncCommands.smembers("myset");
            })
                    .thenAccept(System.out::println)
                    // >>> [Hello, World]
                    .toCompletableFuture();

code:
Mono<Void> smembers = reactiveCommands.sadd("myset", "Hello", "World").doOnNext(r -> {
                System.out.println(r); // >>> 2
            }).flatMap(r -> reactiveCommands.smembers("myset").collectList()).doOnNext(r -> {
                System.out.println(r); // >>> [Hello, World]
            }).then();

code:
long sMembersResult1 = jedis.sadd("myset", "Hello", "World");
        System.out.println(sMembersResult1); // >>> 2

        Set<String> sMembersResult2 = jedis.smembers("myset");
        System.out.println(sMembersResult2.stream().sorted().collect(toList()));
        // >>> [Hello, World]

code:
const res4 = await client.sAdd('myset', ['Hello', 'World']);
console.log(res4);  // 2

const res5 = await client.sMembers('myset')
console.log(res5);  // ['Hello', 'World']

code:
$res4 = $r->sadd('myset', ['Hello', 'World']);
        echo $res4 . PHP_EOL;
        // >>> 2

        $res5 = $r->smembers('myset');
        sort($res5);
        echo json_encode($res5) . PHP_EOL;
        // >>> ["Hello","World"]

code:
res4 = r.sadd("myset", "Hello", "World")
print(res4)  # >>> 2

res5 = r.smembers("myset")
print(res5)  # >>> {'Hello', 'World'}


title: SMISMEMBER

summary: Determines whether multiple members belong to a set.

title: Overview

text:
Returns whether each `member` is a member of the set stored at `key`.

For every `member`, `1` is returned if the value is a member of the set, or `0` if the element is not a member of the set or if `key` does not exist.

title: Examples

text:
SADD myset "one"
SADD myset "one"
SMISMEMBER myset "one" "notamember"

title: Return information

text:
**RESP2:**

[Array reply](../../develop/reference/protocol-spec#arrays): a list representing the membership of the given elements, in the same order as they are requested.

**RESP3:**

[Array reply](../../develop/reference/protocol-spec#arrays): a list representing the membership of the given elements, in the same order as they are requested.


title: SMOVE

summary: Moves a member from one set to another.

title: Overview

text:
This command's behavior varies in clustered Redis environments. See the [multi-key operations]() page for more information.

Move `member` from the set at `source` to the set at `destination`.
This operation is atomic.
In every given moment the element will appear to be a member of `source` **or**
`destination` for other clients.

If the source set does not exist or does not contain the specified element, no
operation is performed and `0` is returned.
Otherwise, the element is removed from the source set and added to the
destination set.
When the specified element already exists in the destination set, it is only
removed from the source set.

title: Examples

text:
SADD myset "one"
SADD myset "two"
SADD myotherset "three"
SMOVE myset myotherset "two"
SMEMBERS myset
SMEMBERS myotherset

title: Return information

text:
**RESP2:**

One of the following:
* [Integer reply](../../develop/reference/protocol-spec#integers): `1` if the element is moved.
* [Integer reply](../../develop/reference/protocol-spec#integers): `0` if the element is not a member of _source_ and no operation was performed.

**RESP3:**

One of the following:
* [Integer reply](../../develop/reference/protocol-spec#integers): `1` if the element is moved.
* [Integer reply](../../develop/reference/protocol-spec#integers): `0` if the element is not a member of _source_ and no operation was performed.


title: SORT

summary: Sorts the elements in a list, a set, or a sorted set, optionally storing the result.

title: Overview

text:
Returns or stores the elements contained in the [list][tdtl], [set][tdts] or
[sorted set][tdtss] at `key`.

There is also the [`SORT_RO`]() read-only variant of this command.

By default, sorting is numeric and elements are compared by their value
interpreted as double precision floating point number.
This is `SORT` in its simplest form:

[tdtl]: /develop/data-types#lists
[tdts]: /develop/data-types#set
[tdtss]: /develop/data-types#sorted-sets

[code example]

Assuming `mylist` is a list of numbers, this command will return the same list
with the elements sorted from small to large.
In order to sort the numbers from large to small, use the `DESC` modifier:

[code example]

When `mylist` contains string values and you want to sort them
lexicographically, use the `ALPHA` modifier:

[code example]

Redis is UTF-8 aware, assuming you correctly set the `LC_COLLATE` environment
variable.

The number of returned elements can be limited using the `LIMIT` modifier.
This modifier takes the `offset` argument, specifying the number of elements to
skip and the `count` argument, specifying the number of elements to return from
starting at `offset`.
The following example will return 10 elements of the sorted version of `mylist`,
starting at element 0 (`offset` is zero-based):

[code example]

Almost all modifiers can be used together.
The following example will return the first 5 elements, lexicographically sorted
in descending order:

[code example]

title: Sorting by external keys

text:
Sometimes you want to sort elements using external keys as weights to compare
instead of comparing the actual elements in the list, set or sorted set.
Let's say the list `mylist` contains the elements `1`, `2` and `3` representing
unique IDs of objects stored in `object_1`, `object_2` and `object_3`.
When these objects have associated weights stored in `weight_1`, `weight_2` and
`weight_3`, `SORT` can be instructed to use these weights to sort `mylist` with
the following statement:

[code example]

The `BY` option takes a pattern (equal to `weight_*` in this example) that is
used to generate the keys that are used for sorting.
These key names are obtained substituting the first occurrence of `*` with the
actual value of the element in the list (`1`, `2` and `3` in this example).

title: Skip sorting the elements

text:
The `BY` option can also take a non-existent key, which causes `SORT` to skip
the sorting operation.
This is useful if you want to retrieve external keys (see the `GET` option
below) without the overhead of sorting.

[code example]

title: Retrieving external keys

text:
Our previous example returns just the sorted IDs.
In some cases, it is more useful to get the actual objects instead of their IDs
(`object_1`, `object_2` and `object_3`).
Retrieving external keys based on the elements in a list, set or sorted set can
be done with the following command:

[code example]

The `GET` option can be used multiple times in order to get more keys for every
element of the original list, set or sorted set.

It is also possible to `GET` the element itself using the special pattern `#`:

[code example]

title: Restrictions for using external keys

role: limits

text:
Before 7.4, when enabling `Redis cluster-mode` there is no way to guarantee the existence of the external keys on the node which the command is processed on. In this case, any use of [`GET`]() or `BY` which reference external key pattern will cause the command to fail with an error.

Starting from 7.4, pattern with hash tag can be mapped to a slot, and so in `Redis cluster-mode`, the use of `BY` or [`GET`]() is allowed when pattern contains hash tag and implies a specific slot which the key is also in, which means any key matching this pattern must be in the same slot as the key, and therefore in the same node. For example, in cluster mode, `{mylist}weight_*` is acceptable as a pattern when sorting `mylist`, while pattern `{abc}weight_*` will be denied, causing the command to fail with an error.

To use pattern with hash tag, see [Hash tags]() for more information.

Starting from Redis 7.0, any use of [`GET`]() or `BY` which reference external key pattern will only be allowed in case the current user running the command has full key read permissions.
Full key read permissions can be set for the user by, for example, specifying `'%R~*'` or `'~*` with the relevant command access rules.
You can check the [`ACL SETUSER`]() command manual for more information on setting ACL access rules.
If full key read permissions aren't set, the command will fail with an error.

title: Storing the result of a SORT operation

text:
By default, `SORT` returns the sorted elements to the client.
With the `STORE` option, the result will be stored as a list at the specified
key instead of being returned to the client.

[code example]

An interesting pattern using `SORT ... STORE` consists in associating an
[`EXPIRE`]() timeout to the resulting key so that in applications where the result
of a `SORT` operation can be cached for some time.
Other clients will use the cached list instead of calling `SORT` for every
request.
When the key will timeout, an updated version of the cache can be created by
calling `SORT ... STORE` again.

Note that for correctly implementing this pattern it is important to avoid
multiple clients rebuilding the cache at the same time.
Some kind of locking is needed here (for instance using [`SETNX`]()).

title: Using hashes in `BY` and `GET`

text:
It is possible to use `BY` and `GET` options against hash fields with the
following syntax:

[code example]

The string `->` is used to separate the key name from the hash field name.
The key is substituted as documented above, and the hash stored at the resulting
key is accessed to retrieve the specified hash field.

title: Return information

text:
**RESP2:**

[Array reply](../../develop/reference/protocol-spec#arrays): without passing the _STORE_ option, the command returns a list of sorted elements.
[Integer reply](../../develop/reference/protocol-spec#integers): when the _STORE_ option is specified, the command returns the number of sorted elements in the destination list.

**RESP3:**

[Array reply](../../develop/reference/protocol-spec#arrays): without passing the _STORE_ option, the command returns a list of sorted elements.
[Integer reply](../../develop/reference/protocol-spec#integers): when the _STORE_ option is specified, the command returns the number of sorted elements in the destination list.

code: SORT mylist

code: SORT mylist DESC

code: SORT mylist ALPHA

code: SORT mylist LIMIT 0 10

code: SORT mylist LIMIT 0 5 ALPHA DESC

code: SORT mylist BY weight_*

section_id: sorting-by-external-keys

code: SORT mylist BY nosort

section_id: skip-sorting-the-elements

code: SORT mylist BY weight_* GET object_*

section_id: retrieving-external-keys

code: SORT mylist BY weight_* GET object_* GET #

code: SORT mylist BY weight_* STORE resultkey

section_id: storing-the-result-of-a-sort-operation

code: SORT mylist BY weight_*->fieldname GET object_*->fieldname

section_id: using-hashes-in-by-and-get


title: SORT_RO

summary: Returns the sorted elements of a list, a set, or a sorted set.

title: Overview

text:
Read-only variant of the [`SORT`]() command. It is exactly like the original [`SORT`]() but refuses the `STORE` option and can safely be used in read-only replicas.

Since the original [`SORT`]() has a `STORE` option it is technically flagged as a writing command in the Redis command table. For this reason read-only replicas in a Redis Cluster will redirect it to the master instance even if the connection is in read-only mode (see the [`READONLY`]() command of Redis Cluster).

The `SORT_RO` variant was introduced in order to allow [`SORT`]() behavior in read-only replicas without breaking compatibility on command flags.

See original [`SORT`]() for more details.

title: Examples

text: [code example]

title: Return information

text:
**RESP2:**

[Array reply](../../develop/reference/protocol-spec#arrays): a list of sorted elements.

**RESP3:**

[Array reply](../../develop/reference/protocol-spec#arrays): a list of sorted elements.

code: SORT_RO mylist BY weight_*->fieldname GET object_*->fieldname


title: SPOP

summary: Returns one or more random members from a set after removing them. Deletes the set if the last member was popped.

title: Overview

text:
Removes and returns one or more random members from the set value store at `key`.

This operation is similar to [`SRANDMEMBER`](), that returns one or more random elements from a set but does not remove it.

By default, the command pops a single member from the set. When provided with
the optional `count` argument, the reply will consist of up to `count` members,
depending on the set's cardinality.

title: Examples

text:
SADD myset "one"
SADD myset "two"
SADD myset "three"
SPOP myset
SMEMBERS myset
SADD myset "four"
SADD myset "five"
SPOP myset 3
SMEMBERS myset

title: Distribution of returned elements

text: Note that this command is not suitable when you need a guaranteed uniform distribution of the returned elements. For more information about the algorithms used for `SPOP`, look up both the Knuth sampling and Floyd sampling algorithms.

text:
| Redis
Software | Redis
Cloud | Notes |
|:----------------------|:-----------------|:------|
| ✅ Standard
<nobr>✅ Active-Active</nobr> | ✅ Standard
<nobr>✅ Active-Active</nobr> |  |

title: Return information

text:
**RESP2:**

One of the following:
* [Nil reply](../../develop/reference/protocol-spec#bulk-strings): if the key does not exist.
* [Bulk string reply](../../develop/reference/protocol-spec#bulk-strings): when called without the _count_ argument, the removed member.
* [Array reply](../../develop/reference/protocol-spec#arrays): when called with the _count_ argument, a list of the removed members.

**RESP3:**

One of the following:
* [Null reply](../../develop/reference/protocol-spec#nulls): if the key does not exist.
* [Bulk string reply](../../develop/reference/protocol-spec#bulk-strings): when called without the _count_ argument, the removed member.
* [Array reply](../../develop/reference/protocol-spec#arrays): when called with the _count_ argument, a list of the removed members.


title: SPUBLISH

summary: Post a message to a shard channel

title: Overview

text:
Posts a message to the given shard channel.

In Redis Cluster, shard channels are assigned to slots by the same algorithm used to assign keys to slots.
A shard message must be sent to a node that owns the slot the shard channel is hashed to.
The cluster makes sure that published shard messages are forwarded to all the nodes in the shard, so clients can subscribe to a shard channel by connecting to any one of the nodes in the shard.

For more information about sharded pubsub, see [Sharded Pubsub]().

title: Examples

text:
For example the following command publishes to the `orders` channel with a subscriber already waiting for message(s).

[code example]

title: Return information

text:
**RESP2:**

[Integer reply](../../develop/reference/protocol-spec#integers): the number of clients that the message was sent to. Note that in a Redis Cluster, only clients that are connected to the same node as the publishing client are included in the count

**RESP3:**

[Integer reply](../../develop/reference/protocol-spec#integers): the number of clients that the message was sent to. Note that in a Redis Cluster, only clients that are connected to the same node as the publishing client are included in the count

code:
> spublish orders hello
(integer) 1


title: SRANDMEMBER

summary: Get one or multiple random members from a set

title: Overview

text:
When called with just the `key` argument, return a random element from the set value stored at `key`.

If the provided `count` argument is positive, return an array of **distinct elements**.
The array's length is either `count` or the set's cardinality ([`SCARD`]()), whichever is lower.

If called with a negative `count`, the behavior changes and the command is allowed to return the **same element multiple times**.
In this case, the number of returned elements is the absolute value of the specified `count`.

title: Examples

text:
SADD myset one two three
SRANDMEMBER myset
SRANDMEMBER myset 2
SRANDMEMBER myset -5

title: Specification of the behavior when count is passed

text:
When the `count` argument is a positive value this command behaves as follows:

* No repeated elements are returned.
* If `count` is bigger than the set's cardinality, the command will only return the whole set without additional elements.
* The order of elements in the reply is not truly random, so it is up to the client to shuffle them if needed.

When the `count` is a negative value, the behavior changes as follows:

* Repeating elements are possible.
* Exactly `count` elements, or an empty array if the set is empty (non-existing key), are always returned.
* The order of elements in the reply is truly random.

title: Distribution of returned elements

text:
Note: this section is relevant only for Redis 5 or below, as Redis 6 implements a fairer algorithm.

The distribution of the returned elements is far from perfect when the number of elements in the set is small, this is due to the fact that we used an approximated random element function that does not really guarantees good distribution.

The algorithm used, that is implemented inside dict.c, samples the hash table buckets to find a non-empty one. Once a non empty bucket is found, since we use chaining in our hash table implementation, the number of elements inside the bucket is checked and a random element is selected.

This means that if you have two non-empty buckets in the entire hash table, and one has three elements while one has just one, the element that is alone in its bucket will be returned with much higher probability.

title: Return information

text:
**RESP2:**

One of the following:
* [Bulk string reply](../../develop/reference/protocol-spec#bulk-strings): without the additional _count_ argument, the command returns a randomly selected member, or a [Nil reply](../../develop/reference/protocol-spec#bulk-strings) when _key_ doesn't exist.
* [Array reply](../../develop/reference/protocol-spec#arrays): when the optional _count_ argument is passed, the command returns an array of members, or an empty array when _key_ doesn't exist.

**RESP3:**

One of the following:
* [Bulk string reply](../../develop/reference/protocol-spec#bulk-strings): without the additional _count_ argument, the command returns a randomly selected member, or a [Null reply](../../develop/reference/protocol-spec#nulls) when _key_ doesn't exist.
* [Array reply](../../develop/reference/protocol-spec#arrays): when the optional _count_ argument is passed, the command returns an array of members, or an empty array when _key_ doesn't exist.


title: SREM

summary: Removes one or more members from a set. Deletes the set if the last member was removed.

title: Overview

text:
Remove the specified members from the set stored at `key`.
Specified members that are not a member of this set are ignored.
If `key` does not exist, it is treated as an empty set and this command returns
`0`.

An error is returned when the value stored at `key` is not a set.

title: Examples

text:
SADD myset "one"
SADD myset "two"
SADD myset "three"
SREM myset "one"
SREM myset "four"
SMEMBERS myset

title: Return information

text:
**RESP2:**

[Integer reply](../../develop/reference/protocol-spec#integers): the number of members that were removed from the set, not including non existing members.

**RESP3:**

[Integer reply](../../develop/reference/protocol-spec#integers): Number of members that were removed from the set, not including non existing members.


title: SSCAN

summary: Iterates over members of a set.

title: Overview

text: See [`SCAN`]() for `SSCAN` documentation.

title: Return information

text:
**RESP2:**

[Array reply](../../develop/reference/protocol-spec#arrays): specifically, an array with two elements:
* The first element is a [Bulk string reply](../../develop/reference/protocol-spec#bulk-strings) that represents an unsigned 64-bit number, the cursor.
* The second element is an [Array reply](../../develop/reference/protocol-spec#arrays) with the names of scanned members.

**RESP3:**

[Array reply](../../develop/reference/protocol-spec#arrays): specifically, an array with two elements:
* The first element is a [Bulk string reply](../../develop/reference/protocol-spec#bulk-strings) that represents an unsigned 64-bit number, the cursor.
* The second element is an [Array reply](../../develop/reference/protocol-spec#arrays) with the names of scanned members.


title: SSUBSCRIBE

summary: Listens for messages published to shard channels.

title: Overview

text:
Subscribes the client to the specified shard channels.

In a Redis cluster, shard channels are assigned to slots by the same algorithm used to assign keys to slots.
Client(s) can subscribe to a node covering a slot (primary/replica) to receive the messages published.
All the specified shard channels needs to belong to a single slot to subscribe in a given `SSUBSCRIBE` call,
A client can subscribe to channels across different slots over separate `SSUBSCRIBE` call.

For more information about sharded Pub/Sub, see [Sharded Pub/Sub]().

title: Examples

text: [code example]

title: Return information

text:
**RESP2:**

When successful, this command doesn't return anything. Instead, for each shard channel, one message with the first element being the string `ssubscribe` is pushed as a confirmation that the command succeeded. Note that this command can also return a -MOVED redirect.

**RESP3:**

When successful, this command doesn't return anything. Instead, for each shard channel, one message with the first element being the string 'ssubscribe' is pushed as a confirmation that the command succeeded. Note that this command can also return a -MOVED redirect.

code:
> ssubscribe orders
Reading messages... (press Ctrl-C to quit)
1) "ssubscribe"
2) "orders"
3) (integer) 1
1) "smessage"
2) "orders"
3) "hello"


title: STRLEN

summary: Returns the length of a string value.

title: Overview

text:
Returns the length of the string value stored at `key`.
An error is returned when `key` holds a non-string value.

title: Examples

text:
SET mykey "Hello world"
STRLEN mykey
STRLEN nonexisting

text:
| Redis
Software | Redis
Cloud | Notes |
|:----------------------|:-----------------|:------|
| ✅ Standard
<nobr>✅ Active-Active</nobr> | ✅ Standard
<nobr>✅ Active-Active</nobr> |  |

title: Return information

text:
**RESP2:**

[Integer reply](../../develop/reference/protocol-spec#integers): the length of the string stored at key, or 0 when the key does not exist.

**RESP3:**

[Integer reply](../../develop/reference/protocol-spec#integers): the length of the string stored at key, or 0 when the key does not exist.


title: SUBSCRIBE

summary: Listens for messages published to channels.

title: Overview

text:
Subscribes the client to the specified channels.

Once the client enters the subscribed state it is not supposed to issue any
other commands, except for additional `SUBSCRIBE`, [`SSUBSCRIBE`](), [`PSUBSCRIBE`](), [`UNSUBSCRIBE`](), [`SUNSUBSCRIBE`](),
[`PUNSUBSCRIBE`](), [`PING`](), [`RESET`]() and [`QUIT`]() commands.
However, if RESP3 is used (see [`HELLO`]()) it is possible for a client to issue any commands while in subscribed state.

For more information, see [Pub/sub]().

title: Behavior change history

text: *   `>= 6.2.0`: [`RESET`]() can be called to exit subscribed state.

title: Return information

text:
**RESP2:**

When successful, this command doesn't return anything. Instead, for each channel, one message with the first element being the string `subscribe` is pushed as a confirmation that the command succeeded.

**RESP3:**

When successful, this command doesn't return anything. Instead, for each channel, one message with the first element being the string `subscribe` is pushed as a confirmation that the command succeeded.


title: SUBSTR

summary: Returns a substring from a string value.

title: Overview

text:
Returns the substring of the string value stored at `key`, determined by the
offsets `start` and `end` (both are inclusive).
Negative offsets can be used in order to provide an offset starting from the end
of the string.
So -1 means the last character, -2 the penultimate and so forth.

The function handles out of range requests by limiting the resulting range to
the actual length of the string.

title: Examples

text:
SET mykey "This is a string"
GETRANGE mykey 0 3
GETRANGE mykey -3 -1
GETRANGE mykey 0 -1
GETRANGE mykey 10 100

text:
| Redis
Software | Redis
Cloud | Notes |
|:----------------------|:-----------------|:------|
| ❌ Standard
<nobr>❌ Active-Active</nobr> | ❌ Standard
<nobr>❌ Active-Active</nobr> | Deprecated as of Redis v2.0.0. |

title: Return information

text:
**RESP2:**

[Bulk string reply](../../develop/reference/protocol-spec#bulk-strings): the substring of the string value stored at key, determined by the offsets start and end (both are inclusive).

**RESP3:**

[Bulk string reply](../../develop/reference/protocol-spec#bulk-strings): the substring of the string value stored at key, determined by the offsets start and end (both are inclusive).


title: SUNION

summary: Returns the union of multiple sets.

title: Overview

text:
This command's behavior varies in clustered Redis environments. See the [multi-key operations]() page for more information.

Returns the members of the set resulting from the union of all the given sets.

For example:

[code example]

Keys that do not exist are considered to be empty sets.

title: Examples

text:
SADD key1 "a"
SADD key1 "b"
SADD key1 "c"
SADD key2 "c"
SADD key2 "d"
SADD key2 "e"
SUNION key1 key2

title: Return information

text:
**RESP2:**

[Array reply](../../develop/reference/protocol-spec#arrays): a list with members of the resulting set.

**RESP3:**

[Set reply](../../develop/reference/protocol-spec#sets): a set with the members of the resulting set.

code:
key1 = {a,b,c,d}
key2 = {c}
key3 = {a,c,e}
SUNION key1 key2 key3 = {a,b,c,d,e}


title: SUNIONSTORE

summary: Stores the union of multiple sets in a key.

title: Overview

text:
This command's behavior varies in clustered Redis environments. See the [multi-key operations]() page for more information.

This command is equal to [`SUNION`](), but instead of returning the resulting set,
it is stored in `destination`.

If `destination` already exists, it is overwritten.

title: Examples

text:
SADD key1 "a"
SADD key1 "b"
SADD key1 "c"
SADD key2 "c"
SADD key2 "d"
SADD key2 "e"
SUNIONSTORE key key1 key2
SMEMBERS key

title: Return information

text:
**RESP2:**

[Integer reply](../../develop/reference/protocol-spec#integers): the number of elements in the resulting set.

**RESP3:**

[Integer reply](../../develop/reference/protocol-spec#integers): Number of the elements in the resulting set.


title: SUNSUBSCRIBE

summary: Stops listening to messages posted to shard channels.

title: Overview

text:
Unsubscribes the client from the given shard channels, or from all of them if none is given.

When no shard channels are specified, the client is unsubscribed from all the previously subscribed shard channels.
In this case a message for every unsubscribed shard channel will be sent to the client.

Note: The global channels and shard channels needs to be unsubscribed from separately.

For more information about sharded Pub/Sub, see [Sharded Pub/Sub]().

title: Return information

text:
**RESP2:**

When successful, this command doesn't return anything. Instead, for each shard channel, one message with the first element being the string `sunsubscribe` is pushed as a confirmation that the command succeeded.

**RESP3:**

When successful, this command doesn't return anything. Instead, for each shard channel, one message with the first element being the string `sunsubscribe` is pushed as a confirmation that the command succeeded.


title: SWAPDB

summary: Swaps two Redis databases.

title: Overview

text:
This command swaps two Redis databases, so that immediately all the
clients connected to a given database will see the data of the other database, and
the other way around. Example:

    SWAPDB 0 1

This will swap database 0 with database 1. All the clients connected with database 0 will immediately see the new data, exactly like all the clients connected with database 1 will see the data that was formerly of database 0.

title: Examples

text: [code example]

text:
| Redis
Software | Redis
Cloud | Notes |
|:----------------------|:-----------------|:------|
| ❌ Standard
<nobr>❌ Active-Active</nobr> | ❌ Standard
<nobr>❌ Active-Active</nobr> |  |

title: Return information

text:
**RESP2:**

[Simple string reply](../../develop/reference/protocol-spec#simple-strings): `OK`.

**RESP3:**

[Simple string reply](../../develop/reference/protocol-spec#simple-strings): `OK`.

code: SWAPDB 0 1


title: SYNC

summary: An internal command used in replication.

title: Overview

text:
Initiates a replication stream from the master.

The `SYNC` command is called by Redis replicas for initiating a replication
stream from the master. It has been replaced in newer versions of Redis by
 [`PSYNC`]().

For more information about replication in Redis please check the
[replication page][tr].

[tr]: /operate/oss_and_stack/management/replication

title: Return information

text:
**RESP2:**

**Non-standard return value**, a bulk transfer of the data followed by `PING` and write requests from the master.

**RESP3:**

**Non-standard return value**, a bulk transfer of the data followed by `PING` and write requests from the master.


title: TDIGEST.ADD

title: Overview

text: Adds one or more observations to a t-digest sketch.

title: Required arguments

text:
key

is the key name for an existing t-digest sketch.

value

is the floating-point value of an observation.

title: Examples

text:
redis> TDIGEST.ADD t 1 2 3
OK

redis> TDIGEST.ADD t string
(error) ERR T-Digest: error parsing val parameter

text:
| Redis
Software | Redis
Cloud | Notes |
|:----------------------|:-----------------|:------|
| ✅ Supported
 | <nobr>✅ Flexible & Annual</nobr>
✅ Free & Fixed</nobr> |  |

title: Return information

text:
**RESP2:**

One of the following:

* [Simple string reply]() `OK` if executed correctly.
* [Simple error reply]() in these cases: the given key does not exist or the value parameter is of the incorrect type.

**RESP3:**

One of the following:

* [Simple string reply]() `OK` if executed correctly.
* [Simple error reply]() in these cases: the given key does not exist or the value parameter is of the incorrect type.


title: TDIGEST.BYRANK

title: Overview

text:
Returns, for each input rank, a floating-point estimation of the value with that rank.
Multiple estimations can be retrieved in a single call.

title: Required arguments

text:
key

is the key name of an existing t-digest sketch.

rank

Ranks for which the values should be retrieved.

0 is the rank of the value of the smallest observation.

_n_-1 is the rank of the value of the largest observation, where _n_ denotes the number of observations that have been added to the sketch.

title: Example

text:
redis> TDIGEST.CREATE t COMPRESSION 1000
OK
redis> TDIGEST.ADD t 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5
OK
redis> TDIGEST.BYRANK t 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
 1) "1"
 2) "2"
 3) "2"
 4) "3"
 5) "3"
 6) "3"
 7) "4"
 8) "4"
 9) "4"
10) "4"
11) "5"
12) "5"
13) "5"
14) "5"
15) "5"
16) "inf"

title: Return information

text:
**RESP2:**

One of the following:

* [Array]() of [bulk strings]() as floating-points, populated with value_1, value_2, ..., value_R:
    * an accurate result when `rank` is `0`, the value of the smallest observation.
    * an accurate result when `rank` is _n_-1, the value of the largest observation, where _n_ denotes the number of observations added to the sketch.
    * `inf` when `rank` is equal to _n_ or larger than _n_.
    * `nan` for all ranks when the given sketch is empty.
* [Simple error reply]() in these cases: the given key does not exist or is of an incorrect type, rank parsing errors, or incorrect number of arguments.

**RESP3:**

One of the following:

* [Array]() of [doubles]() as floating-points, populated with value_1, value_2, ..., value_R:
    * an accurate result when `rank` is `0`, the value of the smallest observation.
    * an accurate result when `rank` is _n_-1, the value of the largest observation, where _n_ denotes the number of observations added to the sketch.
    * `inf` when `rank` is equal to _n_ or larger than _n_.
    * `nan` for all ranks when the given sketch is empty.
* [Simple error reply]() in these cases: the given key does not exist or is of an incorrect type, rank parsing errors, or incorrect number of arguments.


title: TDIGEST.BYREVRANK

summary: Returns, for each input reverse rank, an estimation of the floating-point value with that reverse rank

title: Overview

text:
Returns, for each input reverse rank (`revrank`), an estimation of the floating-point value with that reverse rank.
Multiple estimations can be retrieved in a single call.

title: Required arguments

text:
key

is the key name of an existing t-digest sketch.

revrank

Reverse ranks for which the values should be retrieved.

0 is the reverse rank of the value of the largest observation.

_n_-1 is the reverse rank of the value of the smallest observation, where _n_ denotes the number of observations added to the sketch.

title: Examples

text:
redis> TDIGEST.CREATE t COMPRESSION 1000
OK
redis> TDIGEST.ADD t 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5
OK
redis> TDIGEST.BYREVRANK t 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
 1) "5"
 2) "5"
 3) "5"
 4) "5"
 5) "5"
 6) "4"
 7) "4"
 8) "4"
 9) "4"
10) "3"
11) "3"
12) "3"
13) "2"
14) "2"
15) "1"
16) "-inf"

title: Return information

text:
**RESP2:**

One of the following:

* [Array]() of [bulk strings]() as floating-points, populated with value_1, value_2, ..., value_R:
    * an accurate result when `rank` is `0`, the value of the largest observation.
    * an accurate result when `rank` is _n_-1, the value of the smallest observation, where _n_ denotes the number of observations added to the sketch.
    * `inf` when `rank` is equal to _n_ or larger than _n_.
    * `nan` for all ranks when the given sketch is empty.
* [Simple error reply]() in these cases: the given key does not exist or is of an incorrect type, rank parsing errors, or an incorrect number of arguments.

**RESP3:**

One of the following:

* [Array]() of [doubles]() as floating-points, populated with value_1, value_2, ..., value_R:
    * an accurate result when `rank` is `0`, the value of the largest observation.
    * an accurate result when `rank` is _n_-1, the value of the smallest observation, where _n_ denotes the number of observations added to the sketch.
    * `inf` when `rank` is equal to _n_ or larger than _n_.
    * `nan` for all ranks when the given sketch is empty.
* [Simple error reply]() in these cases: the given key does not exist or is of an incorrect type, rank parsing errors, or an incorrect number of arguments.


title: TDIGEST.CDF

summary: Returns, for each input value, an estimation of the floating-point fraction of (observations smaller than the given value + half the observations equal to the given value)

title: Overview

text:
Returns, for each input value, an estimation of the floating-point fraction of (_observations smaller than the given value_ + _half the observations equal to the given value_).
Multiple fractions can be retrieved in a single call.

title: Required arguments

text:
key

is the key name for an existing t-digest sketch.

value

are the values for which the CDF (Cumulative Distribution Function) should be retrieved.

title: Examples

text:
redis> TDIGEST.CREATE t COMPRESSION 1000
OK
redis> TDIGEST.ADD t 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5
OK
redis> TDIGEST.CDF t 0 1 2 3 4 5 6
1) "0"
2) "0.033333333333333333"
3) "0.13333333333333333"
4) "0.29999999999999999"
5) "0.53333333333333333"
6) "0.83333333333333337"
7) "1"

text:
| Redis
Software | Redis
Cloud | Notes |
|:----------------------|:-----------------|:------|
| ✅ Supported
 | ✅ Flexible & Annual
✅ Free & Fixed</nobr> |  |

title: Return information

text:
**RESP2:**

One of the following:

* [Array]() of [bulk string replies]() as floating-points, populated with fraction_1, fraction_2, ..., fraction_N.
All values are `nan` if the given sketch is empty.
* [Simple error reply]() in these cases: the given key does not exist or is of an incorrect type, value parsing errors, or an incorrect number of arguments.

**RESP3:**

One of the following:

* [Array]() of [doubles]() populated with fraction_1, fraction_2, ..., fraction_N.
All values are `nan` if the given sketch is empty.
* [Simple error reply]() in these cases: the given key does not exist or is of an incorrect type, value parsing errors, or an incorrect number of arguments.


title: TDIGEST.CREATE

title: Overview

text: Allocates memory and initializes a new t-digest sketch.

title: Required arguments

text:
key

is the key name for this new t-digest sketch.

title: Optional arguments

role: parameters

text:
COMPRESSION compression

is a controllable tradeoff between accuracy and memory consumption. 100 is a common value for normal uses and also the default if not specified. 1000 is more accurate. For more information on scaling of accuracy versus the compression value see [_The t-digest: Efficient estimates of distributions_](https://www.sciencedirect.com/science/article/pii/S2665963820300403).

title: Example

text:
redis> TDIGEST.CREATE t COMPRESSION 100
OK

title: Return information

text:
**RESP2:**

One of the following:

* [Simple string reply]() `OK` if executed correctly.
* [Simple error reply]() in these cases: incorrect key type or incorrect keyword.

**RESP3:**

One of the following:

* [Simple string reply]() `OK` if executed correctly.
* [Simple error reply]() in these cases: incorrect key type or incorrect keyword.


title: TDIGEST.INFO

title: Overview

text: Returns information and statistics about a t-digest sketch.

title: Required arguments

text:
key

is the key name for an existing t-digest sketch.

title: Examples

text:
redis> TDIGEST.CREATE t
OK
redis> TDIGEST.ADD t 1 2 3 4 5
OK
redis> TDIGEST.INFO t
 1) Compression
 2) (integer) 100
 3) Capacity
 4) (integer) 610
 5) Merged nodes
 6) (integer) 0
 7) Unmerged nodes
 8) (integer) 5
 9) Merged weight
10) (integer) 0
11) Unmerged weight
12) (integer) 5
13) Observations
14) (integer) 5
15) Total compressions
16) (integer) 0
17) Memory usage
18) (integer) 9768

title: Return information

text:
**RESP2:**

One of the following:

* [Array reply]() with information about the given sketch as name-value pairs:

    | Name
[Simple string reply]() | Description
    | ---------------------------- | -
    | `Compression`        | [Integer reply]()
 The compression (controllable trade-off between accuracy and memory consumption) of the sketch
    | `Capacity`           | [Integer reply]()
 Size of the buffer used for storing the centroids and for the incoming unmerged observations
    | `Merged nodes`       | [Integer reply]()
 Number of merged observations
    | `Unmerged nodes`     | [Integer reply]()
 Number of buffered nodes (uncompressed observations)
    | `Merged weight`      | [Integer reply]()
 Weight of values of the merged nodes
    | `Unmerged weight`    | [Integer reply]()
 Weight of values of the unmerged nodes (uncompressed observations)
    | `Observations`       | [Integer reply]()
 Number of observations added to the sketch
    | `Total compressions` | [Integer reply]()
 Number of times this sketch compressed data together
    | `Memory usage`       | [Integer reply]()
 Number of bytes allocated for the sketch
* [Simple error reply]() in these cases: the given key does not exist or is of an incorrect type or an incorrect number of arguments.

**RESP3:**

One of the following:

* [Map reply]() with information about the given sketch as name-value pairs:

    | Name
[Simple string reply]() | Description
    | ---------------------------- | -
    | `Compression`        | [Integer reply]()
 The compression (controllable trade-off between accuracy and memory consumption) of the sketch
    | `Capacity`           | [Integer reply]()
 Size of the buffer used for storing the centroids and for the incoming unmerged observations
    | `Merged nodes`       | [Integer reply]()
 Number of merged observations
    | `Unmerged nodes`     | [Integer reply]()
 Number of buffered nodes (uncompressed observations)
    | `Merged weight`      | [Integer reply]()
 Weight of values of the merged nodes
    | `Unmerged weight`    | [Integer reply]()
 Weight of values of the unmerged nodes (uncompressed observations)
    | `Observations`       | [Integer reply]()
 Number of observations added to the sketch
    | `Total compressions` | [Integer reply]()
 Number of times this sketch compressed data together
    | `Memory usage`       | [Integer reply]()
 Number of bytes allocated for the sketch
* [Simple error reply]() in these cases: the given key does not exist or is of an incorrect type or an incorrect number of arguments.


title: TDIGEST.MAX

title: Overview

text: Returns the maximum observation value from a t-digest sketch.

title: Required arguments

title: Examples

text:
redis> TDIGEST.CREATE t
OK
redis> TDIGEST.MAX t
"nan"
redis> TDIGEST.ADD t 3 4 1 2 5
OK
redis>TDIGEST.MAX t
"5"

title: Return information

text:
**RESP2:**

One of the following:

* [Bulk string reply]() as floating-point representing the maximum observation value from the given sketch. The result is always accurate. `nan` is returned if the sketch is empty.
* [Simple string reply]() in these cases: incorrect number of arguments or incorrect key type.

**RESP3:**

One of the following:

* [Double reply]() representing the maximum observation value from the given sketch. The result is always accurate. `nan` is returned if the sketch is empty.
* [Simple string reply]() in these cases: incorrect number of arguments or incorrect key type.


title: TDIGEST.MERGE

title: Overview

text:
This command's behavior varies in clustered Redis environments. See the [multi-key operations]() page for more information.

Merges multiple t-digest sketches into a single sketch.

title: Required arguments

text:
destination-key

is the key name for a t-digest sketch to merge observation values to.

If `destination-key` does not exist, a new sketch is created.

If `destination-key` is an existing sketch, its values are merged with the values of the source keys. To override the destination key contents use `OVERRIDE`.

numkeys

the number of sketches from which to merge observation values (one or more).

source-key

Each `source-key` is a key name for a t-digest sketch from which to merge observation values.

title: Optional arguments

text:
COMPRESSION compression

is a controllable tradeoff between accuracy and memory consumption. 100 is a common value for normal uses and also the default if not specified. 1000 is more accurate. For more information on scaling of accuracy versus the compression value see [_The t-digest: Efficient estimates of distributions_](https://www.sciencedirect.com/science/article/pii/S2665963820300403).

When `COMPRESSION` is not specified:
- If `destination-key` does not exist or if `OVERRIDE` is specified, the compression is set to the maximum value among all source sketches.
- If `destination-key` already exists and `OVERRIDE` is not specified, its compression is not changed.

OVERRIDE

If `destination-key` already exists and `OVERRIDE` is specified, the key is overwritten.

title: Examples

text:
redis> TDIGEST.CREATE {metrics}:m1
OK
redis> TDIGEST.CREATE {metrics}:m2
OK
redis> TDIGEST.ADD {metrics}:m1 10.0 20.0
OK
redis> TDIGEST.ADD {metrics}:m2 30.0 40.0
OK
redis> TDIGEST.MERGE {metrics}:m 2 {metrics}:m1 {metrics}:m2
OK
redis> TDIGEST.BYRANK {metrics}:m 0 1 2 3 4
1) "10"
2) "20"
3) "30"
4) "40"
5) "inf"

title: Return information

text:
**RESP2:**

One of the following:

* [Simple string reply]() `OK` if successful.
* [Simple error reply]() in the following cases: incorrect key type, incorrect keyword, or incorrect number of arguments.

**RESP3:**

One of the following:

* [Simple string reply]() `OK` if successful.
* [Simple error reply]() in the following cases: incorrect key type, incorrect keyword, or incorrect number of arguments.


title: TDIGEST.MIN

title: Overview

text: Returns the minimum observation value from a t-digest sketch.

title: Required arguments

title: Examples

text:
redis> TDIGEST.CREATE t
OK
redis> TDIGEST.MIN t
"nan"
redis> TDIGEST.ADD t 3 4 1 2 5
OK
redis> TDIGEST.MIN t
"1"

text:
| Redis
Software | Redis
Cloud | Notes |
|:----------------------|:-----------------|:------|
| ✅ Supported
 | ✅ Flexible & Annual
✅ Free & Fixed</nobr> |  |

title: Return information

text:
**RESP2:**

One of the following:

* [Bulk string reply]() as floating-point representing the minimum observation value from the given sketch. The result is always accurate. `nan` is returned if the sketch is empty.
* [Simple string reply]() in these cases: incorrect number of arguments or incorrect key type.

**RESP3:**

One of the following:

* [Double reply]() representing the minimum observation value from the given sketch. The result is always accurate. `nan` is returned if the sketch is empty.
* [Simple string reply]() in these cases: incorrect number of arguments or incorrect key type.


title: TDIGEST.QUANTILE

title: Overview

text:
Returns, for each input fraction, a floating-point estimation of the value that is smaller than the given fraction of observations.
Multiple quantiles can be retrieved in a single call.

title: Required arguments

text:
key

is the key name for an existing t-digest sketch.

quantile

is the input fraction between 0 and 1 inclusively.

title: Examples

text:
redis> TDIGEST.CREATE t COMPRESSION 1000
OK
redis> TDIGEST.ADD t 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5
OK
redis> TDIGEST.QUANTILE t 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
 1) "1"
 2) "2"
 3) "3"
 4) "3"
 5) "4"
 6) "4"
 7) "4"
 8) "5"
 9) "5"
10) "5"
11) "5"

title: Return information

text:
**RESP2:**

One of the following:

* [Array]() of [bulk string replies]() as floating-point estimates, populated with value_1, value_2, ..., value_N.
    * an accurate result when `quantile` is `0`, the value of the smallest observation.
    * an accurate result when `quantile` is `1`, the value of the largest observation.
    * `nan` for all quantiles when the given sketch is empty.
* [Simple error reply]() in these cases: the given key does not exist or is of an incorrect type, quantile parsing errors, or incorrect number of arguments.

**RESP3:**

One of the following:

* [Array]() of [double replies]() as estimates, populated with value_1, value_2, ..., value_N.
    * an accurate result when `quantile` is `0`, the value of the smallest observation.
    * an accurate result when `quantile` is `1`, the value of the largest observation.
    * `nan` for all quantiles when the given sketch is empty.
* [Simple error reply]() in these cases: the given key does not exist or is of an incorrect type, quantile parsing errors, or incorrect number of arguments.


title: TDIGEST.RANK

summary: Returns, for each floating-point input value, the estimated rank of the value (the number of observations in the sketch that are smaller than the value + half the number of observations that are equal to the value)

title: Overview

text:
Returns, for each floating-point input value, the estimated rank of the value (_the number of observations in the sketch that are smaller than the value_ + _half the number of observations that are equal to the value_).
Multiple ranks can be retrieved in a single call.

title: Required arguments

text:
key

is the key name for an existing t-digest sketch.

value

is the input value for which the rank should be estimated.

title: Examples

text:
redis> TDIGEST.CREATE s COMPRESSION 1000
OK
redis> TDIGEST.ADD s 10 20 30 40 50 60
OK
redis> TDIGEST.RANK s 0 10 20 30 40 50 60 70
1) (integer) -1
2) (integer) 0
3) (integer) 1
4) (integer) 2
5) (integer) 3
6) (integer) 4
7) (integer) 5
8) (integer) 6
redis> TDIGEST.REVRANK s 0 10 20 30 40 50 60 70
1) (integer) 6
2) (integer) 5
3) (integer) 4
4) (integer) 3
5) (integer) 2
6) (integer) 1
7) (integer) 0
8) (integer) -1

redis> TDIGEST.CREATE s COMPRESSION 1000
OK
redis> TDIGEST.ADD s 10 10 10 10 20 20
OK
redis> TDIGEST.RANK s 10 20
1) (integer) 2
2) (integer) 5
redis> TDIGEST.REVRANK s 10 20
1) (integer) 4
2) (integer) 1

text:
| Redis
Software | Redis
Cloud | Notes |
|:----------------------|:-----------------|:------|
| ✅ Supported
 | <nobr>✅ Flexible & Annual</nobr>
✅ Free & Fixed</nobr> |  |

title: Return information

text:
**RESP2:**

One of the following:

* [Array]() of [integers]() populated with rank_1, rank_2, ..., rank_V:
    * `-1` when `value` is smaller than the value of the smallest observation.
    * The number of observations when `value` is larger than the value of the largest observation.
    * Otherwise, an estimation of the number of (_observations smaller than `value`_ + _half the observations equal to `value`_).

    `0` is the rank of the value of the smallest observation.

    _n_-1 is the rank of the value of the largest observation, where _n_ denotes the number of observations added to the sketch.

    All values are `-2` if the sketch is empty.
* [Simple error reply]() in these cases: the given key does not exist or is of an incorrect type, quantile parsing errors, or incorrect number of arguments.

**RESP3:**

One of the following:

* [Array]() of [integers]() populated with rank_1, rank_2, ..., rank_V:
    * `-1` when `value` is smaller than the value of the smallest observation.
    * The number of observations when `value` is larger than the value of the largest observation.
    * Otherwise, an estimation of the number of (_observations smaller than `value`_ + _half the observations equal to `value`_).

    `0` is the rank of the value of the smallest observation.

    _n_-1 is the rank of the value of the largest observation, where _n_ denotes the number of observations added to the sketch.

    All values are `-2` if the sketch is empty.
* [Simple error reply]() in these cases: the given key does not exist or is of an incorrect type, quantile parsing errors, or incorrect number of arguments.


title: TDIGEST.RESET

summary: Resets a t-digest sketch (empties the sketch and re-initializes it).

title: Overview

text: Resets a t-digest sketch: empties the sketch and re-initializes it.

title: Required arguments

text:
key

is the key name for an existing t-digest sketch.

title: Example

text:
redis> TDIGEST.RESET t
OK

title: Return information

text:
**RESP2:**

One of the following:

* [Simple string reply]() `OK` if executed correctly.
* [Simple error reply]() in these cases: key does not exist or is of the wrong type, or incorrect number of arguments.

**RESP3:**

One of the following:

* [Simple string reply]() `OK` if executed correctly.
* [Simple error reply]() in these cases: key does not exist or is of the wrong type, or incorrect number of arguments.


title: TDIGEST.REVRANK

summary: Returns, for each floating-point input value, the estimated reverse rank of the value (the number of observations in the sketch that are larger than the value + half the number of observations that are equal to the value)

title: Overview

text:
Returns, for each floating-point input value, the estimated reverse rank of the value (_the number of observations in the sketch that are larger than the value_ + _half the number of observations that are equal to the value_).
Multiple reverse ranks can be retrieved in a single call.

title: Required arguments

text:
key

is the key name for an existing t-digest sketch.

value

is the input value for which the reverse rank should be estimated.

title: Return value

text:
[Array reply]() - an array of integers populated with revrank_1, revrank_2, ..., revrank_V:

- -1 - when `value` is larger than the value of the largest observation.
- The number of observations - when `value` is smaller than the value of the smallest observation.
- Otherwise: an estimation of the number of (observations larger than `value` + half the observations equal to `value`).

0 is the reverse rank of the value of the largest observation.

_n_-1 is the reverse rank of the value of the smallest observation; _n_ denotes the number of observations added to the sketch.

All values are -2 if the sketch is empty.

title: Examples

title: Return information

text:
**RESP2:**

One of the following:

* [Array]() of [integers]() populated with revrank_1, revrank_2, ..., revrank_V:
    * `-1` when `value` is larger than the value of the largest observation.
    * The number of observations when `value` is smaller than the value of the smallest observation.
    * Otherwise, an estimation of the number of (_observations larger than `value`_ + _half the observations equal to `value`_).

    `0` is the reverse rank of the value of the largest observation.

    _n_-1 is the rank of the value of the smallest observation, where _n_ denotes the number of observations added to the sketch.

    All values are `-2` if the sketch is empty.
* [Simple error reply]() in these cases: the given key does not exist or is of an incorrect type, quantile parsing errors, or incorrect number of arguments.

**RESP3:**

One of the following:

* [Array]() of [integers]() populated with revrank_1, revrank_2, ..., revrank_V:
    * `-1` when `value` is larger than the value of the largest observation.
    * The number of observations when `value` is smaller than the value of the smallest observation.
    * Otherwise, an estimation of the number of (_observations larger than `value`_ + _half the observations equal to `value`_).

    `0` is the reverse rank of the value of the largest observation.

    _n_-1 is the rank of the value of the smallest observation, where _n_ denotes the number of observations added to the sketch.

    All values are `-2` if the sketch is empty.
* [Simple error reply]() in these cases: the given key does not exist or is of an incorrect type, quantile parsing errors, or incorrect number of arguments.


title: TDIGEST.TRIMMED_MEAN

title: Overview

text: Returns an estimation of the mean value from the sketch, excluding observation values outside the low and high cutoff quantiles.

title: Required arguments

text:
key

is the key name for an existing t-digest sketch.

low_cut_quantile

a floating-point value in the range [0..1]. It must be lower than `high_cut_quantile`.

When equal to 0, no low cut.

When greater than 0, exclude observation values lower than this quantile.

high_cut_quantile

a floating-point value in the range [0..1]. It must be higher than `low_cut_quantile`.

When less than 1, exclude observation values greater than or equal to this quantile.

When equal to 1, no high cut.

title: Examples

text:
redis> TDIGEST.CREATE t COMPRESSION 1000
OK
redis> TDIGEST.ADD t 1 2 3 4 5 6 7 8 9 10
OK
redis> TDIGEST.TRIMMED_MEAN t 0.1 0.6
"4"
redis> TDIGEST.TRIMMED_MEAN t 0.3 0.9
"6.5"
redis> TDIGEST.TRIMMED_MEAN t 0 1
"5.5"

text:
| Redis
Software | Redis
Cloud | Notes |
|:----------------------|:-----------------|:------|
| ✅ Supported
 | ✅ Flexible & Annual
✅ Free & Fixed</nobr> |  |

title: Return information

text:
**RESP2:**

One of the following:

* [Bulk string reply]() as a floating-point estimation of the mean value.
* `nan` if the sketch is empty.
* [Simple error reply]() in these cases: the given key does not exist or is of an incorrect type, quantiles out of range [0..1], or incorrect number of arguments.

**RESP3:**

One of the following:

* [Double reply]() as an estimation of the mean value.
* `nan` if the sketch is empty.
* [Simple error reply]() in these cases: the given key does not exist or is of an incorrect type, quantiles out of range [0..1], or incorrect number of arguments.


title: TIME

summary: Returns the server time.

title: Overview

text:
The `TIME` command returns the current server time as a two items lists: a Unix
timestamp and the amount of microseconds already elapsed in the current second.
Basically the interface is very similar to the one of the `gettimeofday` system
call.

title: Examples

text:
TIME
TIME

text:
| Redis
Software | Redis
Cloud | Notes |
|:----------------------|:-----------------|:------|
| ✅ Standard
<nobr>✅ Active-Active</nobr> | ✅ Standard
<nobr>✅ Active-Active</nobr> |  |

title: Return information

text:
**RESP2:**

[Array reply](../../develop/reference/protocol-spec#arrays): specifically, a two-element array consisting of the Unix timestamp in seconds and the microseconds' count.

**RESP3:**

[Array reply](../../develop/reference/protocol-spec#arrays): specifically, a two-element array consisting of the Unix timestamp in seconds and the microseconds' count.


title: TOPK.ADD

title: Overview

text:
Adds an item to a Top-k sketch.
Multiple items can be added at the same time.
If an item enters the Top-K sketch, the item that is expelled (if any) is returned.
This allows dynamic heavy-hitter detection of items being entered or expelled from Top-K sketch.

title: Parameters

text:
* **key**: the name of the sketch where items are added.
* **item**: the items to be added.

title: Example

text: [code example]

text:
| Redis
Software | Redis
Cloud | Notes |
|:----------------------|:-----------------|:------|
| ✅ Supported
 | <nobr>✅ Flexible & Annual</nobr>
✅ Free & Fixed</nobr> |  |

title: Return information

text:
**RESP2:**

One of the following:

* [Array]() of [bulk string replies]() containing either dropped elements or [nil (null bulk string)]().
* [Simple error reply]() in these cases: incorrect number of arguments or non-existant key.

**RESP3:**

One of the following:

* [Array]() of [bulk string replies]() containing either dropped elements or [null]().
* [Simple error reply]() in these cases: incorrect number of arguments, non-existant key, or key of the incorrect type.

code:
redis> TOPK.ADD topk foo bar 42
1) (nil)
2) baz
3) (nil)

section_id: example


title: TOPK.COUNT

summary: Return the count for one or more items in a sketch

title: Overview

text:
Returns counts for each item present in the sketch.
Multiple items can be requested at once.
Please note this number will never be higher than the real count and will likely be lower.

This command has been deprecated. The count value is not a representative of
the number of appearances of an item.

title: Parameters

text:
* **key**: the name of the sketch where items are to be counted.
* **item**: the items to be counted.

title: Examples

text: [code example]

title: Return information

text:
**RESP2:**

One of the following:

* [Array]() of [integer replies]() representing the count of each specified item. For non-existant items, `0` is returned.
* [Simple error reply]() in these cases: incorrect number of arguments, non-existant key, or key of the incorrect type.

**RESP3:**

One of the following:

* [Array]() of [integer replies]() representing the count of each specified item. For non-existant items, `0` is returned.
* [Simple error reply]() in these cases: incorrect number of arguments, non-existant key, or key of the incorrect type.

code:
redis> TOPK.COUNT topk foo 42 nonexist
1) (integer) 3
2) (integer) 1
3) (integer) 0


title: TOPK.INCRBY

summary: Increases the count of one or more items by increment

title: Overview

text:
Increase the score of an item in the data structure by `increment`.
Multiple items' scores can be increased at once.
If an item enters the Top-K list, the item that is expelled (if any) is returned.

title: Parameters

text:
* **key**: the name of the sketch.
* **item**: the items to be incremented.
* **increment**: the value by which items will be incremented. The `increment` must be greater or equal to 1 and less than or equal to 100,000 to avoid server freeze.

title: Return

text: [Array]() of [Simple string reply]() - if an element was dropped from the TopK list, [Nil reply]() otherwise..

title: Example

text: [code example]

title: Return information

text:
**RESP2:**

One of the following:

* [Array]() of [bulk string replies]() containing either dropped elements or [nil (null bulk string)]().
* [Simple error reply]() in these cases: incorrect number of arguments, non-existant key, key of the incorrect type, or an incorrect increment (less than 0 or greater than 100,000).

**RESP3:**

One of the following:

* [Array]() of [bulk string replies]() containing either dropped elements or [null]().
* [Simple error reply]() in these cases: incorrect number of arguments, non-existant key, key of the incorrect type, or an incorrect increment (less than 0 or greater than 100,000).

code:
redis> TOPK.INCRBY topk foo 3 bar 2 42 30
1) (nil)
2) (nil)
3) foo


title: TOPK.INFO

summary: Returns information about a sketch

title: Overview

text: Returns number of required items (k), width, depth, and decay values of a given sketch.

title: Parameters

text: * **key**: the name of the sketch.

title: Examples

text: [code example]

title: Return information

text:
**RESP2:**

One of the following:

* [Array reply]() of [simple string]() and [integer]() pairs. For decay, a [simple string reply]() is used to represent the floating point value.
* [Simple error reply]() in these cases: incorrect number of arguments, non-existant key, or key of the incorrect type.

**RESP3:**

One of the following:

* [A map]() of [simple string]() and [integer]() pairs. For decay, a [double reply]() is used to represent the floating point value.
* [Simple error reply]() in these cases: incorrect number of arguments, non-existant key, or key of the incorrect type.


title: TOPK.LIST

summary: Return the full list of items in the Top-K sketch

title: Overview

text: Return the full list of items in Top-K sketch.

title: Parameters

text:
* **key**: the name of the sketch.
* **WITHCOUNT**: the count of each element is also returned.

title: Examples

text:
[code example]

[code example]

text:
| Redis
Software | Redis
Cloud | Notes |
|:----------------------|:-----------------|:------|
| ✅ Supported
 | ✅ Flexible & Annual
✅ Free & Fixed</nobr> |  |

title: Return information

text:
k (or less) items in the given Top-k sketch. The list is sorted by decreased count estimation.

**RESP2:**

One of the following:

* [Array]() of [bulk string replies]() representing the names of items in the given sketch. If `WITHCOUNT` is requested, an [array]() of [bulk string reply]() and
[integer reply]() pairs, representing the names of the items in the sketch together with their counts.
* [Simple error reply]() in these cases: invalid arguments, non-existant key, or key of the incorrect type.

**RESP3:**

One of the following:

* [Array]() of [bulk string replies]() representing the names of items in the given sketch. If `WITHCOUNT` is requested, an [array]() of [bulk string reply]() and
[integer reply]() pairs, representing the names of the items in the sketch together with their counts.
* [Simple error reply]() in these cases: invalid arguments, non-existant key, or key of the incorrect type.

code:
TOPK.LIST topk
1) foo
2) 42
3) bar

code:
TOPK.LIST topk WITHCOUNT
1) foo
2) (integer) 12
3) 42
4) (integer) 7
5) bar
6) (integer) 2


title: TOPK.QUERY

summary: Checks whether one or more items are in a sketch

title: Overview

text: Checks whether one or more items are one of the Top-K items.

title: Parameters

text:
* **key**: the name of the sketch.
* **item**: the items to be queried.

title: Example

text: [code example]

title: Return information

text:
**RESP2:**

One of the following:

* [Array]() of [integer replies](): `1` if an item is in the Top-K or `0` otherwise.
* [Simple error reply]() in these cases: non-existant key or key of the incorrect type.

**RESP3:**

* [Array]() of [boolean replies](): `true` if an item is in the Top-K or `false` otherwise.
* [Simple error reply]() in these cases: non-existant key or key of the incorrect type.

code:
redis> TOPK.QUERY topk 42 nonexist
1) (integer) 1
2) (integer) 0


title: TOPK.RESERVE

title: Overview

text: Initializes a Top-K sketch with specified parameters.

title: Parameters

text:
* **key**: the name of the Top-k sketch.
* **topk**: the number of top (k) occurring items to keep.

Optional parameters
* **width**: Number of counters kept in each array. (Default 8)
* **depth**: Number of arrays. (Default 7)
* **decay**: The probability of reducing a counter in an occupied bucket (decay ^ bucket[i].counter). As the counter gets higher, the likelihood of a reduction is lower. (Default 0.9)

title: Example

text: [code example]

title: Return information

text:
**RESP2:**

One of the following:

* [Simple string reply]() `OK` if executed correctly.
* [Simple error reply]() in these cases: incorrect number of arguments, invalid decay value, or key already exists.

**RESP3:**

One of the following:

* [Simple string reply]() `OK` if executed correctly.
* [Simple error reply]() in these cases: incorrect number of arguments, invalid decay value, or key already exists.

code:
redis> TOPK.RESERVE topk 50 2000 7 0.925
OK


title: TOUCH

summary: Returns the number of existing keys out of those specified after updating the time they were last accessed.

title: Overview

text:
This command's behavior varies in clustered Redis environments. See the [multi-key operations]() page for more information.

Alters the last access time of a key(s).
A key is ignored if it does not exist.

title: Examples

text:
SET key1 "Hello"
SET key2 "World"
TOUCH key1 key2

text:
| Redis
Software | Redis
Cloud | Notes |
|:----------------------|:-----------------|:------|
| ✅ Standard
<nobr>✅ Active-Active</nobr> | ✅ Standard
<nobr>✅ Active-Active</nobr> |  |

title: Return information

text:
**RESP2:**

[Integer reply](../../develop/reference/protocol-spec#integers): the number of touched keys.

**RESP3:**

[Integer reply](../../develop/reference/protocol-spec#integers): the number of touched keys.