ProtectedconstructorOptionaloptions: BaseClientConfigurationProtecteddefaultProtectedisProtected ReadonlypromiseAppends a value to a key. If key does not exist it is created and set as an empty string,
so APPEND will be similar to set in this special case.
The key of the string.
The key of the string.
The length of the string after appending the value.
https://valkey.io/commands/append/|valkey.io for more details.
const len = await client.append("key", "Hello");
console.log(len);
// Output: 5
// Indicates that "Hello" has been appended to the value of "key", which was initially
// empty, resulting in a new value of "Hello" with a length of 5 - similar to the set operation.
len = await client.append("key", " world");
console.log(result);
// Output: 11
// Indicates that " world" has been appended to the value of "key", resulting in a
// new value of "Hello world" with a length of 11.
Counts the number of set bits (population counting) in the string stored at key. The options argument can
optionally be provided to count the number of bits in a specific string interval.
The key for the string to count the set bits of.
Optionaloptions: BitOffsetOptionsThe offset options - see BitOffsetOptions.
If options is provided, returns the number of set bits in the string interval specified by options.
If options is not provided, returns the number of set bits in the string stored at key.
Otherwise, if key is missing, returns 0 as it is treated as an empty string.
https://valkey.io/commands/bitcount/|valkey.io for more details.
console.log(await client.bitcount("my_key1"));
// Output: 2
// The string stored at `my_key1` contains 2 set bits.
console.log(await client.bitcount("my_key2", { start: 1 }));
// Output: 8
// From the second to to the last bytes of the string stored at `my_key2` are contain 8 set bits.
console.log(await client.bitcount("my_key2", { start: 1, end: 3 }));
// Output: 2
// The second to fourth bytes of the string stored at `my_key2` contain 2 set bits.
console.log(await client.bitcount("my_key3", { start: 1, end: 1, indexType: BitmapIndexType.BIT }));
// Output: 1
// Indicates that the second bit of the string stored at `my_key3` is set.
console.log(await client.bitcount("my_key3", { start: -1, end: -1, indexType: BitmapIndexType.BIT }));
// Output: 1
// Indicates that the last bit of the string stored at `my_key3` is set.
Reads or modifies the array of bits representing the string that is held at key based on the specified
subcommands.
The key of the string.
The subcommands to be performed on the binary value of the string at key, which could be
any of the following:
An array of results from the executed subcommands:
https://valkey.io/commands/bitfield/|valkey.io for more details.
await client.set("key", "A"); // "A" has binary value 01000001
const result = await client.bitfield("key", [new BitFieldSet(new UnsignedEncoding(2), new BitOffset(1), 3), new BitFieldGet(new UnsignedEncoding(2), new BitOffset(1))]);
console.log(result);
// Output: [2, 3]
// The old value at offset 1 with an unsigned encoding of 2 was 2. The new value at offset 1 with an unsigned encoding of 2 is 3.
Reads the array of bits representing the string that is held at key based on the specified subcommands.
The key of the string.
The BitFieldGet subcommands to be performed.
An array of results from the BitFieldGet subcommands.
https://valkey.io/commands/bitfield_ro/|valkey.io for more details.
Perform a bitwise operation between multiple keys (containing string values) and store the result in the
destination.
The bitwise operation to perform.
The key that will store the resulting string.
The list of keys to perform the bitwise operation on.
The size of the string stored in destination.
https://valkey.io/commands/bitop/|valkey.io for more details.
await client.set("key1", "A"); // "A" has binary value 01000001
await client.set("key2", "B"); // "B" has binary value 01000010
const result1 = await client.bitop(BitwiseOperation.AND, "destination", ["key1", "key2"]);
console.log(result1);
// Output: 1
// The size of the resulting string stored in "destination" is 1.
const result2 = await client.get("destination");
console.log(result2);
// Output: "@"
// "@" has binary value 01000000
Returns the position of the first bit matching the given bit value. The optional starting offset
start is a zero-based index, with 0 being the first byte of the list, 1 being the next byte and so on.
The offset can also be a negative number indicating an offset starting at the end of the list, with -1 being
the last byte of the list, -2 being the penultimate, and so on.
The key of the string.
The bit value to match. Must be 0 or 1.
Optionaloptions: BitOffsetOptions(Optional) The BitOffsetOptions.
The position of the first occurrence of bit in the binary value of the string held at key.
If start was provided, the search begins at the offset indicated by start.
https://valkey.io/commands/bitpos/|valkey.io for details.
await client.set("key1", "A1"); // "A1" has binary value 01000001 00110001
const result1 = await client.bitpos("key1", 1);
console.log(result1);
// Output: 1
// The first occurrence of bit value 1 in the string stored at `key1` is at the second position.
const result2 = await client.bitpos("key1", 1, { start: -1 });
console.log(result2);
// Output: 10
// The first occurrence of bit value 1, starting at the last byte in the string stored at `key1`, is at the eleventh position.
await client.set("key1", "A12"); // "A12" has binary value 01000001 00110001 00110010
const result3 = await client.bitpos("key1", 1, { start: 1, end: -1 });
console.log(result3);
// Output: 10
// The first occurrence of bit value 1 in the second byte to the last byte of the string stored at `key1` is at the eleventh position.
const result4 = await client.bitpos("key1", 1, { start: 2, end: 9, indexType: BitmapIndexType.BIT });
console.log(result4);
// Output: 7
// The first occurrence of bit value 1 in the third to tenth bits of the string stored at `key1` is at the eighth position.
Blocks the connection until it pops atomically and removes the left/right-most element to the
list stored at source depending on whereFrom, and pushes the element at the first/last element
of the list stored at destination depending on whereTo.
BLMOVE is the blocking variant of lmove.
The key to the source list.
The key to the destination list.
The ListDirection to remove the element from.
The ListDirection to add the element to.
The number of seconds to wait for a blocking operation to complete. A value of 0 will block indefinitely.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
The popped element, or null if source does not exist or if the operation timed-out.
https://valkey.io/commands/blmove/|valkey.io for details.
await client.lpush("testKey1", ["two", "one"]); // The key `testKey1` has a list ["one", "two"] after this operation.
await client.lpush("testKey2", ["four", "three"]); // The key `testKey2` has a list ["three", "four"] after this operation.
const result = await client.blmove("testKey1", "testKey2", ListDirection.LEFT, ListDirection.LEFT, 0.1);
console.log(result);
// Output: "one"
// Removes "one" from the list at key `testKey1` and adds it to the left of the list at `testKey2`.
const updated_array1 = await client.lrange("testKey1", 0, -1);
console.log(updated_array1);
// Output: "two"
// The elements in the list at `testKey1` after blmove command.
const updated_array2 = await client.lrange("testKey2", 0, -1);
console.log(updated_array2);
// Output: ["one", "three", "four"]
// The elements in the list at `testKey2` after blmove command.
Blocks the connection until it pops one or more elements from the first non-empty list from the
provided key. BLMPOP is the blocking variant of lmpop.
An array of keys.
The direction based on which elements are popped from - see ListDirection.
The number of seconds to wait for a blocking operation to complete. A value of 0 will block indefinitely.
Optionaloptions: { count?: number } & DecoderOption(Optional) Additional parameters:
count: the maximum number of popped elements. If not specified, pops one member.decoder: see DecoderOption.A Record which stores the key name where elements were popped out and the array of popped elements.
If no member could be popped and the timeout expired, returns null.
https://valkey.io/commands/blmpop/|valkey.io for more details.
Blocking list pop primitive.
Pop an element from the head of the first list that is non-empty,
with the given keys being checked in the order that they are given.
Blocks the connection when there are no elements to pop from any of the given lists.
The keys of the lists to pop from.
The timeout in seconds.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
array containing the key from which the element was popped and the value of the popped element,
formatted as [key, value]. If no element could be popped and the timeout expired, returns null.https://valkey.io/commands/blpop/|valkey.io for more details.
Blocking list pop primitive.
Pop an element from the tail of the first list that is non-empty,
with the given keys being checked in the order that they are given.
Blocks the connection when there are no elements to pop from any of the given lists.
The keys of the lists to pop from.
The timeout in seconds.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
array containing the key from which the element was popped and the value of the popped element,
formatted as [key, value]. If no element could be popped and the timeout expired, returns null.https://valkey.io/commands/brpop/|valkey.io for more details.
Pops a member-score pair from the first non-empty sorted set, with the given keys being
checked in the order they are provided. Blocks the connection when there are no members
to pop from any of the given sorted sets. BZMPOP is the blocking variant of zmpop.
The keys of the sorted sets.
The element pop criteria - either ScoreFilter.MIN or ScoreFilter.MAX to pop the member with the lowest/highest score accordingly.
The number of seconds to wait for a blocking operation to complete. A value of 0 will block indefinitely.
Optionaloptions: { count?: number } & DecoderOption(Optional) Additional parameters:
count: the maximum number of popped elements. If not specified, pops one member.decoder: see DecoderOption.A two-element array containing the key name of the set from which the element
was popped, and a SortedSetDataType of the popped elements.
If no member could be popped, returns null.
https://valkey.io/commands/bzmpop/|valkey.io for more details.
await client.zadd("zSet1", { one: 1.0, two: 2.0, three: 3.0 });
await client.zadd("zSet2", { four: 4.0 });
console.log(await client.bzmpop(["zSet1", "zSet2"], ScoreFilter.MAX, 0.1, 2));
// Output:
// [ "zSet1", [
// { element: 'three', score: 3 },
// { element: 'two', score: 2 }
// ] ]
// `three` with score 3 and `two` with score 2 were popped from `zSet1`
Blocks the connection until it removes and returns a member with the highest score from the
first non-empty sorted set, with the given key being checked in the order they
are provided.
BZPOPMAX is the blocking variant of zpopmax.
The keys of the sorted sets.
The number of seconds to wait for a blocking operation to complete. A value of
0 will block indefinitely. Since 6.0.0: timeout is interpreted as a double instead of an integer.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
An array containing the key where the member was popped out, the member, itself, and the member score.
If no member could be popped and the timeout expired, returns null.
https://valkey.io/commands/zpopmax/|valkey.io for more details.
Blocks the connection until it removes and returns a member with the lowest score from the
first non-empty sorted set, with the given key being checked in the order they
are provided.
BZPOPMIN is the blocking variant of zpopmin.
The keys of the sorted sets.
The number of seconds to wait for a blocking operation to complete. A value of
0 will block indefinitely. Since 6.0.0: timeout is interpreted as a double instead of an integer.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
An array containing the key where the member was popped out, the member, itself, and the member score.
If no member could be popped and the timeout expired, returns null.
https://valkey.io/commands/bzpopmin/|valkey.io for more details.
Gets the name of the primary's connection.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
The name of the client connection as a string if a name is set, or null if no name is assigned.
https://valkey.io/commands/client-getname/|valkey.io for more details.
Returns the current connection ID.
The ID of the connection.
https://valkey.io/commands/client-id/|valkey.io for details.
Terminate the client by closing all associated resources, including the socket and any active promises. All open promises will be closed with an exception.
OptionalerrorMessage: stringIf defined, this error message will be passed along with the exceptions when closing all open promises.
Reads the configuration parameters of the running server. Starting from server version 7, command supports multiple parameters.
A list of configuration parameter names to retrieve values for.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
A map of values corresponding to the configuration parameters.
https://valkey.io/commands/config-get/|valkey.io for details.
Resets the statistics reported by the server using the INFO and LATENCY HISTOGRAM commands.
always "OK".
https://valkey.io/commands/config-resetstat/|valkey.io for details.
Rewrites the configuration file with the current configuration.
"OK" when the configuration was rewritten properly. Otherwise, an error is thrown.
https://valkey.io/commands/config-rewrite/|valkey.io for details.
Sets configuration parameters to the specified values. Starting from server version 7, command supports multiple parameters.
A map consisting of configuration parameters and their respective values to set.
"OK" when the configuration was set properly. Otherwise an error is thrown.
https://valkey.io/commands/config-set/|valkey.io for details.
ProtectedconfigureProtectedconfigureProtectedconnectCopies the value stored at the source to the destination key. If destinationDB is specified,
the value will be copied to the database specified, otherwise the current database will be used.
When replace is true, removes the destination key first if it already exists, otherwise performs
no action.
The key to the source value.
The key where the value should be copied to.
Optionaloptions: { destinationDB?: number; replace?: boolean }(Optional) Additional parameters:
destinationDB: the alternative logical database index for the destination key.
If not provided, the current database will be used.replace: if true, the destination key should be removed before copying the
value to it. If not provided, no action will be performed if the key already exists.true if source was copied, false if the source was not copied.
https://valkey.io/commands/copy/|valkey.io for more details.
Since Valkey version 6.2.0. destinationDB parameter for cluster mode is supported since Valkey 9.0.0 and above
const result = await client.copy("set1", "set2");
console.log(result); // Output: true - "set1" was copied to "set2".
const result = await client.copy("set1", "set2", { replace: true });
console.log(result); // Output: true - "set1" was copied to "set2".
const result = await client.copy("set1", "set2", { destinationDB: 1, replace: false });
console.log(result); // Output: true - "set1" was copied to "set2".
ProtectedcreateProtectedcreateProtectedcreateProtectedcreateProtectedcreateInternalCreates a promise that resolves or rejects based on the result of a command request.
The type of the result expected from the promise.
A single command or an array of commands to be executed, array of commands represents a batch and not a single command.
Optional settings for the write operation, including route, batch options and decoder.
Indicates whether the operation should be executed atomically (AKA as a Transaction, in the case of a batch). Defaults to false.
Determines whether to raise an error if any of the commands fails, in the case of a Batch and not a single command. Defaults to false.
A promise that resolves with the result of the command(s) or rejects with an error.
Executes a single command, without checking inputs. Every part of the command, including subcommands, should be added as a separate value in args.
Note: An error will occur if the string decoder is used with commands that return only bytes as a response.
A list including the command name and arguments for the custom command.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
The executed custom command return value.
Glide Wiki for details on the restrictions and limitations of the custom command API.
Returns the number of keys in the currently selected database.
The number of keys in the currently selected database.
https://valkey.io/commands/dbsize/|valkey.io for more details.
Decrements the number stored at key by one. If key does not exist, it is set to 0 before performing the operation.
The key to decrement its value.
the value of key after the decrement.
https://valkey.io/commands/decr/|valkey.io for details.
Decrements the number stored at key by amount. If key does not exist, it is set to 0 before performing the operation.
The key to decrement its value.
The amount to decrement.
the value of key after the decrement.
https://valkey.io/commands/decrby/|valkey.io for details.
Removes the specified keys. A key is ignored if it does not exist.
The keys we wanted to remove.
The number of keys that were removed.
https://valkey.io/commands/del/|valkey.io for details.
In cluster mode, if keys in keys map to different hash slots,
the command will be split across these slots and executed separately for each.
This means the command is atomic only at the slot level. If one or more slot-specific
requests fail, the entire call will return the first encountered error, even
though some requests may have succeeded while others did not.
If this behavior impacts your application logic, consider splitting the
request into sub-requests per slot to ensure atomicity.
Serialize the value stored at key in a Valkey-specific format and return it to the user.
The key to serialize.
The serialized value of the data stored at key. If key does not exist, null will be returned.
https://valkey.io/commands/dump/|valkey.io for details.
Echoes the provided message back.
The message to be echoed back.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
The provided message.
https://valkey.io/commands/echo|valkey.io for more details.
ProtectedensureExecute a batch by processing the queued commands.
Notes:
WATCH command, EXEC will return null.A Batch object containing a list of commands to be executed.
Determines how errors are handled within the batch response.
true, the first the first encountered error in the batch will be raised as an exception of type RequestError
after all retries and reconnections have been exhausted.false, errors will be included as part of the batch response, allowing the caller to process both successful and failed commands together.
In this case, error details will be provided as instances of RequestError in the response list.Optionaloptions: BaseBatchOptions & DecoderOption(Optional) See BatchOptions and DecoderOption.
A list of results corresponding to the execution of each command in the transaction.
If a command returns a value, it will be included in the list. If a command doesn't return a value,
the list entry will be null.
If the transaction failed due to a WATCH command, exec will return null.
// Example 1: Atomic Batch (Transaction) with Options
const transaction = new Batch(true) // Atomic (Transactional)
.set("key", "value")
.get("key");
const result = await client.exec(transaction, false, {timeout: 1000}); // Execute the transaction with raiseOnError = false and a timeout of 1000ms
console.log(result); // Output: ['OK', 'value']
// Example 2: Non-Atomic Batch (Pipelining) with Options
const pipeline = new Batch(false) // Non-Atomic (Pipelining)
.set("key1", "value1")
.set("key2", "value2")
.get("key1")
.get("key2");
const result = await client.exec(pipeline, false, {timeout: 1000}); // Execute the pipeline with raiseOnError = false and a timeout of 1000ms
console.log(result); // Output: ['OK', 'OK', 'value1', 'value2']
Returns the number of keys in keys that exist in the database.
The keys list to check.
The number of keys that exist. If the same existing key is mentioned in keys multiple times,
it will be counted multiple times.
In cluster mode, if keys in keys map to different hash slots,
the command will be split across these slots and executed separately for each.
This means the command is atomic only at the slot level. If one or more slot-specific
requests fail, the entire call will return the first encountered error, even
though some requests may have succeeded while others did not.
If this behavior impacts your application logic, consider splitting the
request into sub-requests per slot to ensure atomicity.
https://valkey.io/commands/exists/|valkey.io for details.
Sets a timeout on key in seconds. After the timeout has expired, the key will automatically be deleted.
If key already has an existing expire set, the time to live is updated to the new value.
If seconds is non-positive number, the key will be deleted rather than expired.
The timeout will only be cleared by commands that delete or overwrite the contents of key.
The key to set timeout on it.
The timeout in seconds.
Optionaloptions: { expireOption?: ExpireOptions }(Optional) Additional parameters:
expireOption: the expire option - see ExpireOptions.true if the timeout was set. false if the timeout was not set. e.g. key doesn't exist,
or operation skipped due to the provided arguments.
https://valkey.io/commands/expire/|valkey.io for details.
Sets a timeout on key. It takes an absolute Unix timestamp (seconds since January 1, 1970) instead of specifying the number of seconds.
A timestamp in the past will delete the key immediately. After the timeout has expired, the key will automatically be deleted.
If key already has an existing expire set, the time to live is updated to the new value.
The timeout will only be cleared by commands that delete or overwrite the contents of key.
The key to set timeout on it.
The timeout in an absolute Unix timestamp.
Optionaloptions: { expireOption?: ExpireOptions }(Optional) Additional parameters:
expireOption: the expire option - see ExpireOptions.true if the timeout was set. false if the timeout was not set. e.g. key doesn't exist,
or operation skipped due to the provided arguments.
https://valkey.io/commands/expireat/|valkey.io for details.
Returns the absolute Unix timestamp (since January 1, 1970) at which the given key will expire, in seconds.
To get the expiration with millisecond precision, use pexpiretime.
The key to determine the expiration value of.
The expiration Unix timestamp in seconds, -2 if key does not exist or -1 if key exists but has no associated expire.
https://valkey.io/commands/expiretime/|valkey.io for details.
const result1 = await client.expiretime("myKey");
console.log(result1);
// Output: -2
// `myKey` doesn't exist.
const result2 = await client.set("myKey", "value");
const result3 = await client.expireTime("myKey");
console.log(result3);
// Output: -1
// `myKey` has no associated expiration.
client.expire(myKey, 60);
const result3 = await client.expireTime("myKey");
console.log(result3);
// Output: 123456
// The Unix timestamp (in seconds) when `myKey` will expire.
Invokes a previously loaded function.
The function name.
A list of keys accessed by the function. To ensure the correct execution of functions,
all names of keys that a function accesses must be explicitly provided as keys.
A list of function arguments and it should not represent names of keys.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
The invoked function's return value.
https://valkey.io/commands/fcall/|valkey.io for more details.
Invokes a previously loaded read-only function.
The function name.
A list of keys accessed by the function. To ensure the correct execution of functions,
all names of keys that a function accesses must be explicitly provided as keys.
A list of function arguments and it should not represent names of keys.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
The invoked function's return value.
https://valkey.io/commands/fcall/|valkey.io for more details.
Deletes all the keys of all the existing databases. This command never fails.
Optionalmode: FlushMode(Optional) The flushing mode, could be either FlushMode.SYNC or FlushMode.ASYNC.
"OK".
https://valkey.io/commands/flushall/|valkey.io for more details.
Deletes all the keys of the currently selected database. This command never fails.
Optionalmode: FlushMode(Optional) The flushing mode, could be either FlushMode.SYNC or FlushMode.ASYNC.
"OK".
https://valkey.io/commands/flushdb/|valkey.io for more details.
Deletes a library and all its functions.
The library name to delete.
A simple "OK" response.
https://valkey.io/commands/function-delete/|valkey.io for details.
Returns the serialized payload of all loaded libraries.
The serialized payload of all loaded libraries.
https://valkey.io/commands/function-dump/|valkey.io for details.
Deletes all function libraries.
Optionalmode: FlushMode(Optional) The flushing mode, could be either FlushMode.SYNC or FlushMode.ASYNC.
A simple "OK" response.
https://valkey.io/commands/function-flush/|valkey.io for details.
Kills a function that is currently executing.
FUNCTION KILL terminates read-only functions only.
FUNCTION KILL runs on all nodes of the server, including primary and replicas.
"OK" if function is terminated. Otherwise, throws an error.
https://valkey.io/commands/function-kill/|valkey.io for details.
Returns information about the functions and libraries.
Optionaloptions: FunctionListOptions & DecoderOption(Optional) See FunctionListOptions and DecoderOption.
Info about all or selected libraries and their functions in FunctionListResponse format.
https://valkey.io/commands/function-list/|valkey.io for details.
// Request info for specific library including the source code
const result1 = await client.functionList({ libNamePattern: "myLib*", withCode: true });
// Request info for all libraries
const result2 = await client.functionList();
console.log(result2); // Output:
// [{
// "library_name": "myLib5_backup",
// "engine": "LUA",
// "functions": [{
// "name": "myfunc",
// "description": null,
// "flags": [ "no-writes" ],
// }],
// "library_code": "#!lua name=myLib5_backup \n redis.register_function('myfunc', function(keys, args) return args[1] end)"
// }]
Loads a library to Valkey.
The source code that implements the library.
Optionaloptions: { replace?: boolean } & DecoderOption(Optional) Additional parameters:
replace: Whether the given library should overwrite a library with the same name if it
already exists.decoder: see DecoderOption.The library name that was loaded.
https://valkey.io/commands/function-load/|valkey.io for details.
Restores libraries from the serialized payload returned by functionDump.
The serialized data from functionDump.
Optionalpolicy: FunctionRestorePolicy(Optional) A policy for handling existing libraries, see FunctionRestorePolicy. FunctionRestorePolicy.APPEND is used by default.
"OK".
https://valkey.io/commands/function-restore/|valkey.io for details.
Returns information about the function that's currently running and information about the available execution engines.
FUNCTION STATS runs on all nodes of the server, including primary and replicas. The response includes a mapping from node address to the command response for that node.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
A Record where the key is the node address and the value is a Record with two keys:
- "running_script": Information about the running script, or null if no script is running.
- "engines": Information about available engines and their stats.
- see example for more details.
https://valkey.io/commands/function-stats/|valkey.io for details.
const response = await client.functionStats();
console.log(response); // Example output:
// {
// "127.0.0.1:6379": { // Response from the primary node
// "running_script": {
// "name": "foo",
// "command": ["FCALL", "foo", "0", "hello"],
// "duration_ms": 7758
// },
// "engines": {
// "LUA": {
// "libraries_count": 1,
// "functions_count": 1
// }
// }
// },
// "127.0.0.1:6380": { // Response from a replica node
// "running_script": null,
// "engines": {
// "LUA": {
// "libraries_count": 1,
// "functions_count": 1
// }
// }
// }
// }
Adds geospatial members with their positions to the specified sorted set stored at key.
If a member is already a part of the sorted set, its position is updated.
The key of the sorted set.
A mapping of member names to their corresponding positions - see GeospatialData. The command will report an error when the user attempts to index coordinates outside the specified ranges.
Optionaloptions: GeoAddOptionsThe GeoAdd options - see GeoAddOptions.
The number of elements added to the sorted set. If changed is set to
true in the options, returns the number of elements updated in the sorted set.
https://valkey.io/commands/geoadd/|valkey.io for more details.
const options = {updateMode: ConditionalChange.ONLY_IF_EXISTS, changed: true};
const membersToCoordinates = new Map<string, GeospatialData>([
["Palermo", { longitude: 13.361389, latitude: 38.115556 }],
]);
const num = await client.geoadd("mySortedSet", membersToCoordinates, options);
console.log(num);
// Output: 1
// Indicates that the position of an existing member in the sorted set `mySortedSet` has been updated.
Returns the distance between member1 and member2 saved in the geospatial index stored at key.
The key of the sorted set.
The name of the first member.
The name of the second member.
Optionaloptions: { unit?: GeoUnit }(Optional) Additional parameters:
unit: the unit of distance measurement - see GeoUnit.
If not specified, the GeoUnit.METERS is used as a default unit.The distance between member1 and member2. Returns null, if one or both members do not exist,
or if the key does not exist.
https://valkey.io/commands/geodist/|valkey.io for more details.
Returns the GeoHash strings representing the positions of all the specified members in the sorted set stored at key.
The key of the sorted set.
The array of members whose GeoHash strings are to be retrieved.
An array of GeoHash strings representing the positions of the specified members stored at key.
If a member does not exist in the sorted set, a null value is returned for that member.
https://valkey.io/commands/geohash/|valkey.io for more details.
Returns the positions (longitude, latitude) of all the specified members of the
geospatial index represented by the sorted set at key.
The key of the sorted set.
The members for which to get the positions.
A 2D Array which represents positions (longitude and latitude) corresponding to the
given members. The order of the returned positions matches the order of the input members.
If a member does not exist, its position will be null.
https://valkey.io/commands/geopos/|valkey.io for more details.
const data = new Map([["Palermo", { longitude: 13.361389, latitude: 38.115556 }], ["Catania", { longitude: 15.087269, latitude: 37.502669 }]]);
await client.geoadd("mySortedSet", data);
const result = await client.geopos("mySortedSet", ["Palermo", "Catania", "NonExisting"]);
// When added via GEOADD, the geospatial coordinates are converted into a 52 bit geohash, so the coordinates
// returned might not be exactly the same as the input values
console.log(result);
// Output:
// [
// [13.36138933897018433, 38.11555639549629859], // Returns the position of member `Palermo`
// [15.08726745843887329, 37.50266842333162032], // Returns the position of member `Catania`
// null // Returns null for non existent key.
// ]
Returns the members of a sorted set populated with geospatial information using geoadd, which are within the borders of the area specified by a given shape.
The key of the sorted set.
The query's center point options, could be one of:
The query's shape options, could be one of:
Optionaloptions: GeoSearchCommonResultOptions & {(Optional) Parameters to request additional information and configure sorting/limiting the results, see GeoSearchResultOptions and DecoderOption.
OptionalwithCoord?: booleanInclude the coordinate of the returned items.
OptionalwithDist?: booleanInclude the distance of the returned items from the specified center point.
The distance is returned in the same unit as specified for the searchBy argument.
OptionalwithHash?: booleanInclude the geohash of the returned items.
By default, returns an Array of members (locations) names.
If any of withCoord, withDist or withHash are set to true in GeoSearchResultOptions, a 2D Array returned,
where each sub-array represents a single item in the following order:
number, in the same unit specified for searchBy, if withDist is set to true.number, if withHash is set to true.array of floating point numbers, if withCoord is set to true.https://valkey.io/commands/geosearch/|valkey.io for more details.
const data = new Map<GlideString, GeospatialData>([["Palermo", { longitude: 13.361389, latitude: 38.115556 }], ["Catania", { longitude: 15.087269, latitude: 37.502669 }]]);
await client.geoadd("mySortedSet", data);
// search for locations within 200 km circle around stored member named 'Palermo'
const result1 = await client.geosearch("mySortedSet", { member: "Palermo" }, { radius: 200, unit: GeoUnit.KILOMETERS });
console.log(result1);
// Output: ['Palermo', 'Catania']
// Locations within the specified radius.
// search for locations in 200x300 mi rectangle centered at coordinate (15, 37), requesting additional info,
// limiting results by 2 best matches, ordered by ascending distance from the search area center
const result2 = await client.geosearch(
"mySortedSet",
{ position: { longitude: 15, latitude: 37 } },
{ width: 200, height: 300, unit: GeoUnit.MILES },
{
sortOrder: SortOrder.ASC,
count: 2,
withCoord: true,
withDist: true,
withHash: true,
},
);
console.log(result2);
// Output:
// [
// [
// 'Catania', // location name
// [
// 56.4413, // distance
// 3479447370796909, // geohash of the location
// [15.087267458438873, 37.50266842333162], // coordinates of the location
// ],
// ],
// [
// 'Palermo',
// [
// 190.4424,
// 3479099956230698,
// [13.361389338970184, 38.1155563954963],
// ],
// ],
// ]
Searches for members in a sorted set stored at source representing geospatial data
within a circular or rectangular area and stores the result in destination.
If destination already exists, it is overwritten. Otherwise, a new sorted set will be created.
To get the result directly, see geosearch.
The key of the destination sorted set.
The key of the sorted set.
The query's center point options, could be one of:
The query's shape options, could be one of:
Optionaloptions: GeoSearchStoreResultOptions(Optional) Parameters to request additional information and configure sorting/limiting the results, see GeoSearchStoreResultOptions.
The number of elements in the resulting sorted set stored at destination.
https://valkey.io/commands/geosearchstore/|valkey.io for more details.
const data = new Map([["Palermo", { longitude: 13.361389, latitude: 38.115556 }], ["Catania", { longitude: 15.087269, latitude: 37.502669 }]]);
await client.geoadd("mySortedSet", data);
// search for locations within 200 km circle around stored member named 'Palermo' and store in `destination`:
await client.geosearchstore("destination", "mySortedSet", { member: "Palermo" }, { radius: 200, unit: GeoUnit.KILOMETERS });
// query the stored results
const result1 = await client.zrangeWithScores("destination", { start: 0, end: -1 });
console.log(result1);
// Output:
// {
// Palermo: 3479099956230698, // geohash of the location is stored as element's score
// Catania: 3479447370796909
// }
// search for locations in 200x300 mi rectangle centered at coordinate (15, 37), requesting to store distance instead of geohashes,
// limiting results by 2 best matches, ordered by ascending distance from the search area center
await client.geosearchstore(
"destination",
"mySortedSet",
{ position: { longitude: 15, latitude: 37 } },
{ width: 200, height: 300, unit: GeoUnit.MILES },
{
sortOrder: SortOrder.ASC,
count: 2,
storeDist: true,
},
);
// query the stored results
const result2 = await client.zrangeWithScores("destination", { start: 0, end: -1 });
console.log(result2);
// Output:
// {
// Palermo: 190.4424, // distance from the search area center is stored as element's score
// Catania: 56.4413, // the distance is measured in units used for the search query (miles)
// }
Get the value associated with the given key, or null if no such key exists.
The key to retrieve from the database.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
If key exists, returns the value of key. Otherwise, return null.
https://valkey.io/commands/get/|valkey.io for details.
// Example usage of get method to retrieve the value of a key
const result = await client.get("key");
console.log(result);
// Output: 'value'
// Example usage of get method to retrieve the value of a key with Bytes decoder
const result = await client.get("key", { decoder: Decoder.Bytes });
console.log(result);
// Output: <Buffer 76 61 6c 75 65>
Returns the bit value at offset in the string value stored at key. offset must be greater than or equal
to zero.
The key of the string.
The index of the bit to return.
The bit at the given offset of the string. Returns 0 if the key is empty or if the offset exceeds
the length of the string.
https://valkey.io/commands/getbit/|valkey.io for more details.
ProtectedgetGets a string value associated with the given keyand deletes the key.
The key to retrieve from the database.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
If key exists, returns the value of key. Otherwise, return null.
https://valkey.io/commands/getdel/|valkey.io for details.
Get the value of key and optionally set its expiration. GETEX is similar to get.
The key to retrieve from the database.
Optionaloptions: { expiry: "persist" | { duration: number; type: TimeUnit } } & DecoderOption(Optional) Additional Parameters:
expiry: expiriation to the given key:
"persist" will retain the time to live associated with the key. Equivalent to PERSIST in the VALKEY API.
Otherwise, a TimeUnit and duration of the expire time should be specified.decoder: see DecoderOption.If key exists, returns the value of key as a string. Otherwise, return null.
https://valkey.io/commands/getex/|valkey.op for more details.
Returns the substring of the string value stored at key, determined by the byte 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. If key does not exist, an empty string is returned. If start
or end are out of range, returns the substring within the valid range of the string.
The key of the string.
The starting byte offset.
The ending byte offset.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
A substring extracted from the value stored at key.
https://valkey.io/commands/getrange/|valkey.io for details.
await client.set("mykey", "This is a string")
let result = await client.getrange("mykey", 0, 3)
console.log(result);
// Output: "This"
result = await client.getrange("mykey", -3, -1)
console.log(result);
// Output: "ing"
// extracted last 3 characters of a string
result = await client.getrange("mykey", 0, 100)
console.log(result);
// Output: "This is a string"
result = await client.getrange("mykey", 5, 6)
console.log(result);
// Output: ""
Return a statistics
Return an object that contains the statistics collected internally by GLIDE core
Removes the specified fields from the hash stored at key.
Specified fields that do not exist within this hash are ignored.
The key of the hash.
The fields to remove from the hash stored at key.
the number of fields that were removed from the hash, not including specified but non existing fields.
If key does not exist, it is treated as an empty hash and it returns 0.
https://valkey.io/commands/hdel/|valkey.io for details.
Returns if field is an existing field in the hash stored at key.
The key of the hash.
The field to check in the hash stored at key.
true the hash contains field. If the hash does not contain field, or if key does not exist, it returns false.
https://valkey.io/commands/hexists/|valkey.io for details.
Sets expiration time for hash fields in seconds. Creates the hash if it doesn't exist.
The key of the hash.
The expiration time in seconds.
The fields to set expiration for.
Optionaloptions: HExpireOptionsOptional parameters for the command.
An array of numbers indicating the result for each field:
- 1 if expiration was set successfully
- 0 if the specified condition (NX, XX, GT, LT) was not met
- -2 if the field does not exist or the key does not exist
- 2 when called with 0 seconds (field deleted)
https://valkey.io/commands/hexpire/|valkey.io for details.
// Set expiration for hash fields
const result = await client.hexpire("my_hash", 60, ["field1", "field2"]);
console.log(result); // [1, 1] - expiration set for both fields
Sets expiration time for hash fields using an absolute Unix timestamp in seconds. Creates the hash if it doesn't exist.
The key of the hash.
The expiration time as a Unix timestamp in seconds.
The fields to set expiration for.
Optionaloptions: HExpireOptionsOptional arguments for the HEXPIREAT command. See HExpireOptions.
An array of numbers indicating the result for each field:
- 1 if expiration was set successfully
- 0 if the specified condition (NX, XX, GT, LT) was not met
- -2 if the field does not exist or the key does not exist
- 2 when called with 0 seconds (field deleted)
https://valkey.io/commands/hexpireat/|valkey.io for details.
// Set expiration for hash fields using Unix timestamp
const futureTimestamp = Math.floor(Date.now() / 1000) + 3600; // 1 hour from now
const result = await client.hexpireat("my_hash", futureTimestamp, ["field1", "field2"]);
console.log(result); // [1, 1] - expiration set for both fields
// Set expiration only if fields don't have expiration
const futureTimestamp = Math.floor(Date.now() / 1000) + 7200; // 2 hours from now
const result = await client.hexpireat("my_hash", futureTimestamp, ["field1", "field2"], {
condition: HashExpirationCondition.ONLY_IF_NO_EXPIRY
});
console.log(result); // [1, 0] - expiration set for field1, condition not met for field2
// Set expiration with greater than condition
const futureTimestamp = Math.floor(Date.now() / 1000) + 10800; // 3 hours from now
const result = await client.hexpireat("my_hash", futureTimestamp, ["field1"], {
condition: HashExpirationCondition.ONLY_IF_GREATER_THAN_CURRENT
});
console.log(result); // [1] - expiration set because timestamp > current expiration
Returns the absolute Unix timestamp (in seconds) at which hash fields will expire.
The key of the hash.
The list of fields to get the expiration timestamp for.
An array of expiration timestamps in seconds for the specified fields:
https://valkey.io/commands/hexpiretime/|valkey.io for details.
Retrieve the value associated with field in the hash stored at key.
The key of the hash.
The field in the hash stored at key to retrieve from the database.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
the value associated with field, or null when field is not present in the hash or key does not exist.
https://valkey.io/commands/hget/|valkey.io for details.
Returns all fields and values of the hash stored at key.
The key of the hash.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
A list of fields and their values stored in the hash.
If key does not exist, it returns an empty list.
https://valkey.io/commands/hgetall/|valkey.io for details.
Gets hash fields and optionally sets their expiration.
The key of the hash.
The fields in the hash stored at key to retrieve from the database.
Optionaloptions: HGetExOptions & DecoderOptionOptional arguments for the HGETEX command. See HGetExOptions and see DecoderOption.
An array of values associated with the given fields,
in the same order as they are requested. For every field that does not exist
in the hash, a null value is returned. If key does not exist, returns an
array of null values.
// Get fields without setting expiration
const values = await client.hgetex("myHash", ["field1", "field2"]);
console.log(values); // ["value1", "value2"] or [null, null] if fields don't exist
// Get fields and set 30 second expiration
const valuesWithExpiry = await client.hgetex(
"myHash",
["field1", "field2"],
{ expiry: { type: TimeUnit.Seconds, count: 30 } }
);
console.log(valuesWithExpiry); // ["value1", "value2"] - fields now expire in 30s
// Get fields and remove expiration (make persistent)
const persistValues = await client.hgetex(
"myHash",
["field1", "field2"],
{ expiry: "PERSIST" }
);
console.log(persistValues); // ["value1", "value2"] - fields are now persistent
// Get fields and set millisecond precision expiration
const msValues = await client.hgetex(
"myHash",
["field3", "field4"],
{ expiry: { type: TimeUnit.Milliseconds, count: 2500 } }
);
console.log(msValues); // ["value3", "value4"] - fields expire in 2500ms
// Get fields and set Unix timestamp expiration
const timestampValues = await client.hgetex(
"myHash",
["field5"],
{ expiry: { type: TimeUnit.UnixMilliseconds, count: Date.now() + 60000 } }
);
console.log(timestampValues); // ["value5"] - field expires in 1 minute
Increments the number stored at field in the hash stored at key by increment.
By using a negative increment value, the value stored at field in the hash stored at key is decremented.
If field or key does not exist, it is set to 0 before performing the operation.
The key of the hash.
The field in the hash stored at key to increment its value.
The amount to increment.
the value of field in the hash stored at key after the increment.
https://valkey.io/commands/hincrby/|valkey.io for details.
Increment the string representing a floating point number stored at field in the hash stored at key by increment.
By using a negative increment value, the value stored at field in the hash stored at key is decremented.
If field or key does not exist, it is set to 0 before performing the operation.
The key of the hash.
The field in the hash stored at key to increment its value.
The amount to increment.
the value of field in the hash stored at key after the increment.
https://valkey.io/commands/hincrbyfloat/|valkey.io for details.
Returns all field names in the hash stored at key.
The key of the hash.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
A list of field names for the hash, or an empty list when the key does not exist.
https://valkey.io/commands/hkeys/|valkey.io for details.
// Example usage of the hkeys method:
await client.hset("my_hash", {"field1": "value1", "field2": "value2", "field3": "value3"});
const result = await client.hkeys("my_hash");
console.log(result);
// Output: ["field1", "field2", "field3"]
// Returns all the field names stored in the hash `my_hash`.
Returns the number of fields contained in the hash stored at key.
The key of the hash.
The number of fields in the hash, or 0 when the key does not exist.
https://valkey.io/commands/hlen/|valkey.io for more details.
Returns the values associated with the specified fields in the hash stored at key.
The key of the hash.
The fields in the hash stored at key to retrieve from the database.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
a list of values associated with the given fields, in the same order as they are requested.
For every field that does not exist in the hash, a null value is returned.
If key does not exist, it is treated as an empty hash and it returns a list of null values.
https://valkey.io/commands/hmget/|valkey.io for details.
Removes the expiration time associated with each specified field, causing them to persist.
The key of the hash.
The fields in the hash to remove expiration from.
An array of numbers indicating the result for each field:
- 1 if the field's expiration was removed successfully.
- -1 if the field exists but has no associated expiration.
- -2 if the field does not exist or the key does not exist.
https://valkey.io/commands/hpersist/|valkey.io for details.
Sets expiration time for hash fields in milliseconds. Creates the hash if it doesn't exist.
The key of the hash.
The expiration time in milliseconds.
The fields to set expiration for.
Optionaloptions: HExpireOptionsOptional arguments for the HPEXPIRE command. See HPExpireOptions.
An array of numbers indicating the result for each field:
- 1 if expiration was set successfully
- 0 if the specified condition (NX, XX, GT, LT) was not met
- -2 if the field does not exist or the key does not exist
- 2 when called with 0 milliseconds (field deleted)
https://valkey.io/commands/hpexpire/|valkey.io for details.
// Set expiration for hash fields in milliseconds
const result = await client.hpexpire("my_hash", 60000, ["field1", "field2"]);
console.log(result); // [1, 1] - expiration set for both fields
Sets expiration time for hash fields using an absolute Unix timestamp in milliseconds. Creates the hash if it doesn't exist.
The key of the hash.
The expiration time as a Unix timestamp in milliseconds.
The fields to set expiration for.
Optionaloptions: HExpireOptionsOptional arguments for the HPEXPIREAT command. See HExpireOptions.
An array of numbers indicating the result for each field:
- 1 if expiration was set successfully
- 0 if the specified condition (NX, XX, GT, LT) was not met
- -2 if the field does not exist or the key does not exist
- 2 when called with 0 milliseconds (field deleted)
https://valkey.io/commands/hpexpireat/|valkey.io for details.
// Set expiration for hash fields using Unix timestamp in milliseconds
const futureTimestamp = Date.now() + 3600000; // 1 hour from now
const result = await client.hpexpireat("my_hash", futureTimestamp, ["field1", "field2"]);
console.log(result); // [1, 1] - expiration set for both fields
// Set expiration only if fields don't have expiration
const futureTimestamp = Date.now() + 7200000; // 2 hours from now
const result = await client.hpexpireat("my_hash", futureTimestamp, ["field1", "field2"], {
condition: HashExpirationCondition.ONLY_IF_NO_EXPIRY
});
console.log(result); // [1, 0] - expiration set for field1, condition not met for field2
// Set expiration with greater than condition
const futureTimestamp = Date.now() + 10800000; // 3 hours from now
const result = await client.hpexpireat("my_hash", futureTimestamp, ["field1"], {
condition: HashExpirationCondition.ONLY_IF_GREATER_THAN_CURRENT
});
console.log(result); // [1] - expiration set because timestamp > current expiration
Returns the absolute Unix timestamp (in milliseconds) at which hash fields will expire.
The key of the hash.
The list of fields to get the expiration timestamp for.
An array of expiration timestamps in milliseconds for the specified fields:
https://valkey.io/commands/hpexpiretime/|valkey.io for details.
Returns the remaining time to live of hash fields that have a timeout, in milliseconds.
The key of the hash.
The list of fields to get the TTL for.
An array of TTL values in milliseconds for the specified fields:
https://valkey.io/commands/hpttl/|valkey.io for details.
Returns a random field name from the hash value stored at key.
The key of the hash.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
A random field name from the hash stored at key, or null when
the key does not exist.
https://valkey.io/commands/hrandfield/|valkey.io for more details.
Retrieves up to count random field names from the hash value stored at key.
The key of the hash.
The number of field names to return.
If count is positive, returns unique elements.
If negative, allows for duplicates.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
An array of random field names from the hash stored at key,
or an empty array when the key does not exist.
https://valkey.io/commands/hrandfield/|valkey.io for more details.
Retrieves up to count random field names along with their values from the hash
value stored at key.
The key of the hash.
The number of field names to return.
If count is positive, returns unique elements.
If negative, allows for duplicates.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
A 2D array of [fieldName, value] arrays, where fieldName is a random
field name from the hash and value is the associated value of the field name.
If the hash does not exist or is empty, the response will be an empty array.
https://valkey.io/commands/hrandfield/|valkey.io for more details.
Iterates incrementally over a hash.
The key of the set.
The cursor that points to the next iteration of results. A value of "0" indicates the start of the search.
Optionaloptions: BaseScanOptions & { noValues?: boolean } & DecoderOption(Optional) See HScanOptions and DecoderOption.
Optional ReadonlynoValues?: booleanIf true, the values of the fields are not included in the results. Supported from Valkey 8.0.0 and above.
An array of the cursor and the subset of the hash held by key.
The first element is always the cursor for the next iteration of results. "0" will be the cursor
returned on the last iteration of the hash. The second element is always an array of the subset of the
hash held in key. The array in the second element is a flattened series of string pairs,
where the value is at even indices and the value is at odd indices.
If options.noValues is set to true, the second element will only contain the fields without the values.
https://valkey.io/commands/hscan/|valkey.io for more details.
// Assume "key" contains a hash with multiple members
let newCursor = "0";
let result = [];
do {
result = await client.hscan(key1, newCursor, {
match: "*",
count: 3,
});
newCursor = result[0];
console.log("Cursor: ", newCursor);
console.log("Members: ", result[1]);
} while (newCursor !== "0");
// The output of the code above is something similar to:
// Cursor: 31 // The cursor after the first interation.
// Members: ['field 79', 'value 79', 'field 20', 'value 20', 'field 115', 'value 115'] // First 3 hash field-value pairs stored at the key `key1`
// Cursor: 39 // The cursor after the second interation.
// Members: ['field 63', 'value 63', 'field 293', 'value 293', 'field 162', 'value 162'] // The next 3 hash field-value pairs at key `key1`
// Cursor: 0 // The cursor after the last batch of elements is fetched.
// Members: ['field 55', 'value 55', 'field 24', 'value 24', 'field 90', 'value 90', 'field 113', 'value 113']
// You can get more than `count` elements in the result set. Read the count documentation for more information.
// Hscan with noValues
let newCursor = "0";
let result = [];
do {
result = await client.hscan(key1, newCursor, {
match: "*",
count: 3,
noValues: true,
});
newCursor = result[0];
console.log("Cursor: ", newCursor);
console.log("Members: ", result[1]);
} while (newCursor !== "0");
// The output of the code above is something similar to:
// Cursor: 31 // The cursor after the first interation.
// Members: ['field 79', 'field 20', 'field 115'] // First 3 hash fields stored at the key `key1`
// Cursor: 39 // The cursor after the second interation.
// Members: ['field 63', 'field 293', 'field 162'] // Next 3 hash fields stored at the key `key1`
// Cursor: 0 // The cursor after the last batch of elements is fetched.
// Members: ['field 55', 'field 24', 'field 90', 'field 113']
// You can get more than `count` elements in the result set. Read the count documentation for more information.
Sets the specified fields to their respective values in the hash stored at key.
The key of the hash.
A list of field names and their values.
The number of fields that were added.
https://valkey.io/commands/hset/|valkey.io for details.
// Example usage of the hset method using HashDataType as input type
const result = await client.hset("my_hash", [{"field": "field1", "value": "value1"}, {"field": "field2", "value": "value2"}]);
console.log(result);
// Output: 2
// Indicates that 2 fields were successfully set in the hash `my_hash`.
// Example usage of the hset method using Record<string, GlideString> as input
const result = await client.hset("my_hash", {"field1": "value", "field2": "value2"});
console.log(result);
// Output: 2
// Indicates that 2 fields were successfully set in the hash `my_hash`.
Sets hash fields with expiration times and optional conditional changes.
The key of the hash.
A map or array of field-value pairs to set.
Optionaloptions: HSetExOptionsOptional parameters including field conditional changes and expiry settings. See HSetExOptions.
A number of fields that were set.
// Set fields with 60 second expiration, only if none exist
const result = await client.hsetex(
"myHash",
{ field1: "value1", field2: "value2" },
{
fieldConditionalChange: HashFieldConditionalChange.ONLY_IF_NONE_EXIST,
expiry: { type: TimeUnit.Seconds, count: 60 }
}
);
console.log(result); // 2 - both fields were set with 60s expiration
// Set fields and keep existing TTL
const keepTtlResult = await client.hsetex(
"myHash",
{ field3: "value3" },
{ expiry: "KEEPTTL" }
);
console.log(keepTtlResult); // 1 - field was set, existing TTL preserved
// Set fields with millisecond precision expiration
const msResult = await client.hsetex(
"myHash",
{ field4: "value4" },
{ expiry: { type: TimeUnit.Milliseconds, count: 5000 } }
);
console.log(msResult); // 1 - field expires in 5000ms
// Set fields with Unix timestamp expiration
const timestampResult = await client.hsetex(
"myHash",
{ field5: "value5" },
{ expiry: { type: TimeUnit.UnixSeconds, count: Math.floor(Date.now() / 1000) + 3600 } }
);
console.log(timestampResult); // 1 - field expires in 1 hour
// Only update existing fields and keep their TTL
const updateResult = await client.hsetex(
"myHash",
{ field1: "newValue1" },
{
fieldConditionalChange: HashFieldConditionalChange.ONLY_IF_ALL_EXIST,
expiry: "KEEPTTL"
}
);
console.log(updateResult); // 0 or 1 depending on whether field1 exists
Sets field in the hash stored at key to value, only if field does not yet exist.
If key does not exist, a new key holding a hash is created.
If field already exists, this operation has no effect.
The key of the hash.
The field to set the value for.
The value to set.
true if the field was set, false if the field already existed and was not set.
https://valkey.io/commands/hsetnx/|valkey.io for more details.
Returns the string length of the value associated with field in the hash stored at key.
The key of the hash.
The field in the hash.
The string length or 0 if field or key does not exist.
https://valkey.io/commands/hstrlen/|valkey.io for details.
Returns the remaining time to live of hash fields that have a timeout, in seconds.
The key of the hash.
The fields in the hash stored at key to retrieve the TTL for.
An array of TTL values in seconds for the specified fields. - For fields with a timeout, returns the remaining time in seconds. - For fields that exist but have no associated expire, returns -1. - For fields that do not exist, returns -2.
https://valkey.io/commands/httl/|valkey.io for details.
Returns all values in the hash stored at key.
The key of the hash.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
a list of values in the hash, or an empty list when the key does not exist.
https://valkey.io/commands/hvals/|valkey.io for more details.
Increments the number stored at key by one. If key does not exist, it is set to 0 before performing the operation.
The key to increment its value.
the value of key after the increment.
https://valkey.io/commands/incr/|valkey.io for details.
Increments the number stored at key by amount. If key does not exist, it is set to 0 before performing the operation.
The key to increment its value.
The amount to increment.
the value of key after the increment.
https://valkey.io/commands/incrby/|valkey.io for details.
Increment the string representing a floating point number stored at key by amount.
By using a negative increment value, the result is that the value stored at key is decremented.
If key does not exist, it is set to 0 before performing the operation.
The key to increment its value.
The amount to increment.
the value of key after the increment.
https://valkey.io/commands/incrbyfloat/|valkey.io for details.
Gets information and statistics about the server.
Starting from server version 7, command supports multiple section arguments.
Optionalsections: InfoOptions[](Optional) A list of InfoOptions values specifying which sections of information to retrieve. When no parameter is provided, Default is assumed.
A string containing the information for the sections requested.
https://valkey.io/commands/info/|valkey.io for details.
Invokes a Lua script with its keys and arguments.
This method simplifies the process of invoking scripts on a Valkey server by using an object that represents a Lua script.
The script loading, argument preparation, and execution will all be handled internally. If the script has not already been loaded,
it will be loaded automatically using the SCRIPT LOAD command. After that, it will be invoked using the EVALSHA command.
The Lua script to execute.
Optionaloptions: { args?: GlideString[]; keys?: GlideString[] } & DecoderOption(Optional) Additional parameters:
keys : the keys that are used in the script.args: the arguments for the script.decoder: see DecoderOption.A value that depends on the script that was executed.
LOAD and https://valkey.io/commands/evalsha/|EVALSHA on valkey.io for details.
Returns UNIX TIME of the last DB save timestamp or startup timestamp if no save
was made since then.
UNIX TIME of the last DB save executed with success.
https://valkey.io/commands/lastsave/|valkey.io for more details.
Returns all the longest common subsequences combined between strings stored at key1 and key2.
The key that stores the first string.
The key that stores the second string.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
A String containing all the longest common subsequence combined between the 2 strings.
An empty String is returned if the keys do not exist or have no common subsequences.
https://valkey.io/commands/lcs/|valkey.io for more details.
Returns the indices and lengths of the longest common subsequences between strings stored at
key1 and key2.
The key that stores the first string.
The key that stores the second string.
Optionaloptions: { minMatchLen?: number; withMatchLen?: boolean }(Optional) Additional parameters:
withMatchLen: if true, include the length of the substring matched for the each match.minMatchLen: the minimum length of matches to include in the result.A Record containing the indices of the longest common subsequences between the
2 strings and the lengths of the longest common subsequences. The resulting map contains two
keys, "matches" and "len":
- "len" is mapped to the total length of the all longest common subsequences between the 2 strings
stored as an integer. This value doesn't count towards the minMatchLen filter.
- "matches" is mapped to a three dimensional array of integers that stores pairs
of indices that represent the location of the common subsequences in the strings held
by key1 and key2.
See example for more details.
https://valkey.io/commands/lcs/|valkey.io for more details.
await client.mset({"key1": "ohmytext", "key2": "mynewtext"});
const result = await client.lcsIdx("key1", "key2");
console.log(result);
// Output:
{
"matches" :
[
[ // first substring match is "text"
[4, 7], // in `key1` it is located between indices 4 and 7
[5, 8], // and in `key2` - in between 5 and 8
4 // the match length, returned if `withMatchLen` set to `true`
],
[ // second substring match is "my"
[2, 3], // in `key1` it is located between indices 2 and 3
[0, 1], // and in `key2` - in between 0 and 1
2 // the match length, returned if `withMatchLen` set to `true`
]
],
"len" : 6 // total length of the all matches found
}
Returns the total length of all the longest common subsequences between strings stored at key1 and key2.
The key that stores the first string.
The key that stores the second string.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
The total length of all the longest common subsequences between the 2 strings.
https://valkey.io/commands/lcs/|valkey.io for more details.
Returns the element at index index in the list stored at key.
The index is zero-based, so 0 means the first element, 1 the second element and so on.
Negative indices can be used to designate elements starting at the tail of the list.
Here, -1 means the last element, -2 means the penultimate and so forth.
The key of the list.
The index of the element in the list to retrieve.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
index in the list stored at key.
If index is out of range or if key does not exist, null is returned.https://valkey.io/commands/lindex/|valkey.io for more details.
Inserts element in the list at key either before or after the pivot.
The key of the list.
The relative position to insert into - either InsertPosition.Before or
InsertPosition.After the pivot.
An element of the list.
The new element to insert.
The list length after a successful insert operation.
If the key doesn't exist returns -1.
If the pivot wasn't found, returns 0.
https://valkey.io/commands/linsert/|valkey.io for more details.
Returns the length of the list stored at key.
The key of the list.
the length of the list at key.
If key does not exist, it is interpreted as an empty list and 0 is returned.
https://valkey.io/commands/llen/|valkey.io for details.
Atomically pops and removes the left/right-most element to the list stored at source
depending on whereTo, and pushes the element at the first/last element of the list
stored at destination depending on whereFrom, see ListDirection.
The key to the source list.
The key to the destination list.
The ListDirection to remove the element from.
The ListDirection to add the element to.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
The popped element, or null if source does not exist.
https://valkey.io/commands/lmove/|valkey.io for details.
await client.lpush("testKey1", ["two", "one"]); // The key `testKey1` has a list ["one", "two"] after this operation.
await client.lpush("testKey2", ["four", "three"]); // The key `testKey2` has a list ["three", "four"] after this operation.
const result = await client.lmove("testKey1", "testKey2", ListDirection.LEFT, ListDirection.LEFT);
console.log(result);
// Output: "one".
// Removes "one" from the list at key `testKey1` and adds it to the left of the list at `testKey2`.
const updated_array_key1 = await client.lrange("testKey1", 0, -1);
console.log(updated_array_key1);
// Output: ["two"]
// The elements in the list at `testKey1` after lmove command.
const updated_array_key2 = await client.lrange("testKey2", 0, -1);
console.log(updated_array_key2);
// Output: ["one", "three", "four"]
// The elements in the list at `testKey2` after lmove command.
Pops one or more elements from the first non-empty list from the provided keys.
An array of keys.
The direction based on which elements are popped from - see ListDirection.
Optionaloptions: { count?: number } & DecoderOption(Optional) Additional parameters:
count: the maximum number of popped elements. If not specified, pops one member.decoder: see DecoderOption.A Record which stores the key name where elements were popped out and the array of popped elements.
If no member could be popped, returns null.
https://valkey.io/commands/lmpop/|valkey.io for more details.
Displays a piece of generative computer art and the server version.
Optionaloptions: LolwutOptions(Optional) The LOLWUT options - see LolwutOptions.
A piece of generative computer art along with the current server version.
https://valkey.io/commands/lolwut/|valkey.io for more details.
Removes and returns the first elements of the list stored at key.
The command pops a single element from the beginning of the list.
The key of the list.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
The value of the first element.
If key does not exist null will be returned.
https://valkey.io/commands/lpop/|valkey.io for details.
Removes and returns up to count elements of the list stored at key, depending on the list's length.
The key of the list.
The count of the elements to pop from the list.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
A list of the popped elements will be returned depending on the list's length.
If key does not exist null will be returned.
https://valkey.io/commands/lpop/|valkey.io for details.
Returns the index of the first occurrence of element inside the list specified by key. If no
match is found, null is returned. If the count option is specified, then the function returns
an array of indices of matching elements within the list.
The name of the list.
The value to search for within the list.
Optionaloptions: LPosOptions(Optional) The LPOS options - see LPosOptions.
The index of element, or null if element is not in the list. If the count option
is specified, then the function returns an array of indices of matching elements within the list.
https://valkey.io/commands/lpos/|valkey.io for more details.
await client.rpush("myList", ["a", "b", "c", "d", "e", "e"]);
console.log(await client.lpos("myList", "e", { rank: 2 }));
// Output: 5
// The second occurrence of `e` is at index 5.
console.log(await client.lpos("myList", "e", { count: 3 }));
// Output: [ 4, 5 ]
// indices for the occurrences of `e` in list `myList`.
Inserts all the specified values at the head of the list stored at key.
elements are inserted one after the other to the head of the list, from the leftmost element to the rightmost element.
If key does not exist, it is created as empty list before performing the push operations.
The key of the list.
The elements to insert at the head of the list stored at key.
the length of the list after the push operations.
https://valkey.io/commands/lpush/|valkey.io for details.
Inserts specified values at the head of the list, only if key already
exists and holds a list.
The key of the list.
The elements to insert at the head of the list stored at key.
The length of the list after the push operation.
https://valkey.io/commands/lpushx/|valkey.io for details.
Returns the specified elements of the list stored at key.
The offsets start and end are zero-based indexes, with 0 being the first element of the list, 1 being the next element and so on.
These offsets can also be negative numbers indicating offsets starting at the end of the list,
with -1 being the last element of the list, -2 being the penultimate, and so on.
The key of the list.
The starting point of the range.
The end of the range.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
list of elements in the specified range.
If start exceeds the end of the list, or if start is greater than end, an empty list will be returned.
If end exceeds the actual end of the list, the range will stop at the actual end of the list.
If key does not exist an empty list will be returned.
https://valkey.io/commands/lrange/|valkey.io for details.
// Example usage of the lrange method with an existing list and positive indices
const result = await client.lrange("my_list", 0, 2);
console.log(result);
// Output: ["value1", "value2", "value3"]
// Returns the first 3 elements of the list.
Removes the first count occurrences of elements equal to element from the list stored at key.
The key of the list.
The count of the occurrences of elements equal to element to remove.
If count is positive : Removes elements equal to element moving from head to tail.
If count is negative : Removes elements equal to element moving from tail to head.
If count is 0 or count is greater than the occurrences of elements equal to element: Removes all elements equal to element.
The element to remove from the list.
the number of the removed elements.
If key does not exist, 0 is returned.
Sets the list element at index to element.
The index is zero-based, so 0 means the first element, 1 the second element and so on.
Negative indices can be used to designate elements starting at the tail of
the list. Here, -1 means the last element, -2 means the penultimate and so forth.
The key of the list.
The index of the element in the list to be set.
The new element to set at the specified index.
Always "OK".
https://valkey.io/commands/lset/|valkey.io for details.
Trim an existing list so that it will contain only the specified range of elements specified.
The offsets start and end are zero-based indexes, with 0 being the first element of the list, 1 being the next element and so on.
These offsets can also be negative numbers indicating offsets starting at the end of the list,
with -1 being the last element of the list, -2 being the penultimate, and so on.
The key of the list.
The starting point of the range.
The end of the range.
always "OK".
If start exceeds the end of the list, or if start is greater than end, the list is emptied and the key is removed.
If end exceeds the actual end of the list, it will be treated like the last element of the list.
If key does not exist the command will be ignored.
https://valkey.io/commands/ltrim/|valkey.io for details.
Retrieve the values of multiple keys.
A list of keys to retrieve values for.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
A list of values corresponding to the provided keys. If a key is not found, its corresponding value in the list will be null.
https://valkey.io/commands/mget/|valkey.io for details.
In cluster mode, if keys in keys map to different hash slots,
the command will be split across these slots and executed separately for each.
This means the command is atomic only at the slot level. If one or more slot-specific
requests fail, the entire call will return the first encountered error, even
though some requests may have succeeded while others did not.
If this behavior impacts your application logic, consider splitting the
request into sub-requests per slot to ensure atomicity.
Move key from the currently selected database to the database specified by dbIndex.
The key to move.
The index of the database to move key to.
true if key was moved, or false if the key already exists in the destination
database or does not exist in the source database.
https://valkey.io/commands/move/|valkey.io for more details.
Set multiple keys to multiple values in a single operation.
A list of key-value pairs to set.
A simple "OK" response.
https://valkey.io/commands/mset/|valkey.io for details.
In cluster mode, if keys in keyValueMap map to different hash slots,
the command will be split across these slots and executed separately for each.
This means the command is atomic only at the slot level. If one or more slot-specific
requests fail, the entire call will return the first encountered error, even
though some requests may have succeeded while others did not.
If this behavior impacts your application logic, consider splitting the
request into sub-requests per slot to ensure atomicity.
Sets multiple keys to values if the key does not exist. The operation is atomic, and if one or more keys already exist, the entire operation fails.
A list of key-value pairs to set.
true if all keys were set. false if no key was set.
https://valkey.io/commands/msetnx/|valkey.io for more details.
Returns the internal encoding for the Valkey object stored at key.
The key of the object to get the internal encoding of.
key exists, returns the internal encoding of the object stored at key as a string.
Otherwise, returns null.https://valkey.io/commands/object-encoding/|valkey.io for more details.
Returns the logarithmic access frequency counter of a Valkey object stored at key.
The key of the object to get the logarithmic access frequency counter of.
key exists, returns the logarithmic access frequency counter of the object
stored at key as a number. Otherwise, returns null.https://valkey.io/commands/object-freq/|valkey.io for more details.
Returns the time in seconds since the last access to the value stored at key.
The key of the object to get the idle time of.
If key exists, returns the idle time in seconds. Otherwise, returns null.
https://valkey.io/commands/object-idletime/|valkey.io for more details.
Returns the reference count of the object stored at key.
The key of the object to get the reference count of.
If key exists, returns the reference count of the object stored at key as a number.
Otherwise, returns null.
https://valkey.io/commands/object-refcount/|valkey.io for more details.
Removes the existing timeout on key, turning the key from volatile (a key with an expire set) to
persistent (a key that will never expire as no timeout is associated).
The key to remove the existing timeout on.
false if key does not exist or does not have an associated timeout, true if the timeout has been removed.
https://valkey.io/commands/persist/|valkey.io for more details.
Sets a timeout on key in milliseconds. After the timeout has expired, the key will automatically be deleted.
If key already has an existing expire set, the time to live is updated to the new value.
If milliseconds is non-positive number, the key will be deleted rather than expired.
The timeout will only be cleared by commands that delete or overwrite the contents of key.
The key to set timeout on it.
The timeout in milliseconds.
Optionaloptions: { expireOption?: ExpireOptions }(Optional) Additional parameters:
expireOption: the expire option - see ExpireOptions.true if the timeout was set. false if the timeout was not set. e.g. key doesn't exist,
or operation skipped due to the provided arguments.
https://valkey.io/commands/pexpire/|valkey.io for details.
Sets a timeout on key. It takes an absolute Unix timestamp (milliseconds since January 1, 1970) instead of specifying the number of milliseconds.
A timestamp in the past will delete the key immediately. After the timeout has expired, the key will automatically be deleted.
If key already has an existing expire set, the time to live is updated to the new value.
The timeout will only be cleared by commands that delete or overwrite the contents of key.
The key to set timeout on it.
The timeout in an absolute Unix timestamp.
Optionaloptions: { expireOption?: ExpireOptions }(Optional) Additional parameters:
expireOption: the expire option - see ExpireOptions.true if the timeout was set. false if the timeout was not set. e.g. key doesn't exist,
or operation skipped due to the provided arguments.
https://valkey.io/commands/pexpireat/|valkey.io for details.
Returns the absolute Unix timestamp (since January 1, 1970) at which the given key will expire, in milliseconds.
The key to determine the expiration value of.
The expiration Unix timestamp in seconds, -2 if key does not exist or -1 if key exists but has no associated expire.
https://valkey.io/commands/pexpiretime/|valkey.io for details.
const result1 = client.pexpiretime("myKey");
console.log(result1);
// Output: -2
// `myKey` doesn't exist.
const result2 = client.set(myKey, "value");
const result3 = client.pexpireTime(myKey);
console.log(result2);
// Output: -1
// `myKey` has no associated expiration.
client.expire(myKey, 60);
const result3 = client.pexpireTime(myKey);
console.log(result3);
// Output: 123456789
// The Unix timestamp (in milliseconds) when `myKey` will expire.
Adds all elements to the HyperLogLog data structure stored at the specified key.
Creates a new structure if the key does not exist.
When no elements are provided, and key exists and is a HyperLogLog, then no operation is performed.
The key of the HyperLogLog data structure to add elements into.
An array of members to add to the HyperLogLog stored at key.
true. Otherwise, returns false.https://valkey.io/commands/pfadd/|valkey.io for more details.
const result = await client.pfadd("hll_1", ["a", "b", "c"]);
console.log(result);
// Output: true
// Indicates that a data structure was created or modified.
const result = await client.pfadd("hll_2", []);
console.log(result);
// Output: true
// Indicates that a new empty data structure was created.
Estimates the cardinality of the data stored in a HyperLogLog structure for a single key or calculates the combined cardinality of multiple keys by merging their HyperLogLogs temporarily.
The keys of the HyperLogLog data structures to be analyzed.
0.https://valkey.io/commands/pfcount/|valkey.io for more details.
Merges multiple HyperLogLog values into a unique value. If the destination variable exists, it is treated as one of the source HyperLogLog data sets, otherwise a new HyperLogLog is created.
The key of the destination HyperLogLog where the merged data sets will be stored.
The keys of the HyperLogLog structures to be merged.
A simple "OK" response.
https://valkey.io/commands/pfmerge/|valkey.io for more details.
await client.pfadd("hll1", ["a", "b"]);
await client.pfadd("hll2", ["b", "c"]);
const result = await client.pfmerge("new_hll", ["hll1", "hll2"]);
console.log(result);
// Output: OK
// The value of `hll1` merged with `hll2` was stored in `new_hll`.
const count = await client.pfcount(["new_hll"]);
console.log(count);
// Output: 3
// The approximate cardinality of `new_hll` is 3.
Pings the server.
Optionaloptions: { message?: GlideString } & DecoderOption(Optional) Additional parameters:
message : a message to include in the PING command.
"PONG".decoder: see DecoderOption."PONG" if message is not provided, otherwise return a copy of message.
https://valkey.io/commands/ping/|valkey.io for details.
ProtectedprocessInternalReturns the remaining time to live of key that has a timeout, in milliseconds.
The key to return its timeout.
TTL in milliseconds, -2 if key does not exist, -1 if key exists but has no associated expire.
https://valkey.io/commands/pttl/|valkey.io for more details.
// Example usage of pttl method with an existing key
const result = await client.pttl("my_key");
console.log(result);
// Output: 5000
// Indicates that the key `my_key` has a remaining time to live of 5000 milliseconds.
Publish a message on pubsub channel.
Message to publish.
Channel to publish the message on.
https://valkey.io/commands/publish/|valkey.io for more details.
Lists the currently active channels. The command is routed to all nodes, and aggregates the response to a single array.
Optionaloptions: { pattern?: GlideString } & DecoderOption(Optional) Additional parameters:
pattern: A glob-style pattern to match active channels.
If not provided, all active channels are returned.decoder: see DecoderOption.A list of currently active channels matching the given pattern. If no pattern is specified, all active channels are returned.
https://valkey.io/commands/pubsub-channels/|valkey.io for more details.
Returns the number of unique patterns that are subscribed to by clients.
Note: This is the total number of unique patterns all the clients are subscribed to, not the count of clients subscribed to patterns. The command is routed to all nodes, and aggregates the response to the sum of all pattern subscriptions.
The number of unique patterns.
https://valkey.io/commands/pubsub-numpat/|valkey.io for more details.
Returns the number of subscribers (exclusive of clients subscribed to patterns) for the specified channels.
The list of channels to query for the number of subscribers.
Optionaloptions: DecoderOption(Optional) see DecoderOption.
A list of the channel names and their numbers of subscribers.
https://valkey.io/commands/pubsub-numsub/|valkey.io for more details.
Returns a random existing key name from the currently selected database.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
A random existing key name from the currently selected database.
https://valkey.io/commands/randomkey/|valkey.io for more details.
Manually refresh the IAM token for the current connection.
This method is only available if the client was created with IAM authentication. It triggers an immediate refresh of the IAM token and updates the connection.
Renames key to newkey.
If newkey already exists it is overwritten.
The key to rename.
The new name of the key.
key was successfully renamed, return "OK". If key does not exist, an error is thrown.https://valkey.io/commands/rename/|valkey.io for more details.
Renames key to newkey if newkey does not yet exist.
The key to rename.
The new name of the key.
key was successfully renamed, returns true. Otherwise, returns false.
If key does not exist, an error is thrown.https://valkey.io/commands/renamenx/|valkey.io for more details.
Create a key associated with a value that is obtained by deserializing the provided
serialized value (obtained via dump).
The key to create.
The expiry time (in milliseconds). If 0, the key will persist.
The serialized value to deserialize and assign to key.
Optionaloptions: RestoreOptions(Optional) Restore options RestoreOptions.
Return "OK" if the key was successfully restored with a value.
https://valkey.io/commands/restore/|valkey.io for details.
const result = await client.restore("myKey", 1000, value, {replace: true, absttl: true});
console.log(result); // Output: "OK"
Removes and returns the last elements of the list stored at key.
The command pops a single element from the end of the list.
The key of the list.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
The value of the last element.
If key does not exist null will be returned.
https://valkey.io/commands/rpop/|valkey.io for details.
Removes and returns up to count elements from the list stored at key, depending on the list's length.
The key of the list.
The count of the elements to pop from the list.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
A list of popped elements will be returned depending on the list's length.
If key does not exist null will be returned.
https://valkey.io/commands/rpop/|valkey.io for details.
Inserts all the specified values at the tail of the list stored at key.
elements are inserted one after the other to the tail of the list, from the leftmost element to the rightmost element.
If key does not exist, it is created as empty list before performing the push operations.
The key of the list.
The elements to insert at the tail of the list stored at key.
the length of the list after the push operations.
https://valkey.io/commands/rpush/|valkey.io for details.
Inserts specified values at the tail of the list, only if key already
exists and holds a list.
The key of the list.
The elements to insert at the tail of the list stored at key.
The length of the list after the push operation.
https://valkey.io/commands/rpushx/|valkey.io for details.
Adds the specified members to the set stored at key. Specified members that are already a member of this set are ignored.
If key does not exist, a new set is created before adding members.
The key to store the members to its set.
A list of members to add to the set stored at key.
The number of members that were added to the set, not including all the members already present in the set.
https://valkey.io/commands/sadd/|valkey.io for details.
Incrementally iterate over a collection of keys.
SCAN is a cursor based iterator. This means that at every call of the method,
the server returns an updated cursor that the user needs to use as the cursor argument in the next call.
An iteration starts when the cursor is set to "0", and terminates when the cursor returned by the server is "0".
A full iteration always retrieves all the elements that were present in the collection from the start to the end of a full iteration. Elements that were not constantly present in the collection during a full iteration, may be returned or not.
The cursor used for iteration. For the first iteration, the cursor should be set to "0".
Using a non-zero cursor in the first iteration,
or an invalid cursor at any iteration, will lead to undefined results.
Using the same cursor in multiple iterations will, in case nothing changed between the iterations,
return the same elements multiple times.
If the the db has changed, it may result in undefined behavior.
Optionaloptions: ScanOptions & DecoderOption(Optional) The options to use for the scan operation, see ScanOptions and DecoderOption.
A List containing the next cursor value and a list of keys, formatted as [cursor, [key1, key2, ...]]
https://valkey.io/commands/scan|valkey.io for more details.
// Example usage of scan method
let result = await client.scan('0');
console.log(result); // Output: ['17', ['key1', 'key2', 'key3', 'key4', 'key5', 'set1', 'set2', 'set3']]
let firstCursorResult = result[0];
result = await client.scan(firstCursorResult);
console.log(result); // Output: ['349', ['key4', 'key5', 'set1', 'hash1', 'zset1', 'list1', 'list2',
// 'list3', 'zset2', 'zset3', 'zset4', 'zset5', 'zset6']]
result = await client.scan(result[0]);
console.log(result); // Output: ['0', ['key6', 'key7']]
result = await client.scan(firstCursorResult, {match: 'key*', count: 2});
console.log(result); // Output: ['6', ['key4', 'key5']]
result = await client.scan("0", {type: ObjectType.Set});
console.log(result); // Output: ['362', ['set1', 'set2', 'set3']]
Returns the set cardinality (number of elements) of the set stored at key.
The key to return the number of its members.
The cardinality (number of elements) of the set, or 0 if key does not exist.
https://valkey.io/commands/scard/|valkey.io for details.
Checks existence of scripts in the script cache by their SHA1 digest.
List of SHA1 digests of the scripts to check.
A list of boolean values indicating the existence of each script.
https://valkey.io/commands/script-exists/|valkey.io for more details.
Flushes the Lua scripts cache.
Optionalmode: FlushMode(Optional) The flushing mode, could be either FlushMode.SYNC or FlushMode.ASYNC.
A simple "OK" response.
https://valkey.io/commands/script-flush/|valkey.io for more details.
Kills the currently executing Lua script, assuming no write operation was yet performed by the script.
A simple "OK" response.
https://valkey.io/commands/script-kill/|valkey.io for more details.
Returns the original source code of a script in the script cache.
The SHA1 digest of the script.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
The original source code of the script, if present in the cache. If the script is not found in the cache, an error is thrown.
https://valkey.io/commands/script-show|valkey.io for more details.
Computes the difference between the first set and all the successive sets in keys.
The keys of the sets to diff.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
A Set of elements representing the difference between the sets.
If a key in keys does not exist, it is treated as an empty set.
https://valkey.io/commands/sdiff/|valkey.io for more details.
Stores the difference between the first set and all the successive sets in keys into a new set at destination.
The key of the destination set.
The keys of the sets to diff.
The number of elements in the resulting set.
https://valkey.io/commands/sdiffstore/|valkey.io for more details.
Changes the currently selected database.
The index of the database to select.
A simple "OK" response.
https://valkey.io/commands/select/|valkey.io for details.
Set the given key with the given value. Return value is dependent on the passed options.
The key to store.
The value to store with the given key.
Optionaloptions: SetOptions & DecoderOption(Optional) See SetOptions and DecoderOption.
conditional in options is not set, the value will be set regardless of prior value existence.
If value isn't set because of onlyIfExists or onlyIfDoesNotExist or onlyIfEqual conditions, return null.
If returnOldValue is set, return the old value as a string.https://valkey.io/commands/set/|valkey.io for details.
// Example usage of set method to set a key-value pair
const result = await client.set("my_key", "my_value");
console.log(result); // Output: 'OK'
// Example usage of set method with conditional options and expiration
const result2 = await client.set("key", "new_value", {conditionalSet: "onlyIfExists", expiry: { type: TimeUnit.Seconds, count: 5 }});
console.log(result2);
// Output: 'OK'
// Set "new_value" to `key" only if `key` already exists, and set the key expiration to 5 seconds.
// Example usage of set method with conditional options and returning old value
const result3 = await client.set("key", "value", {conditionalSet: "onlyIfDoesNotExist", returnOldValue: true});
console.log(result3);
// Output: 'new_value'
// Returns the old value of `key`.
// Example usage of get method to retrieve the value of a key
const result4 = await client.get("key");
console.log(result4);
// Output: 'new_value'
// Value wasn't modified back to being "value" because of "NX" flag.
// Example usage of set method with conditional option IFEQ
await client.set("key", "value we will compare to");
const result5 = await client.set("key", "new_value", {conditionalSet: "onlyIfEqual", comparisonValue: "value we will compare to"});
console.log(result5);
// Output: 'OK'
// Set "new_value" to "key" only if comparisonValue is equal to the current value of "key".
const result6 = await client.set("key", "another_new_value", {conditionalSet: "onlyIfEqual", comparisonValue: "value we will compare to"});
console.log(result6);
// Output: null
// Value wasn't set because the comparisonValue is not equal to the current value of `key`. Value of `key` remains "new_value".
Sets or clears the bit at offset in the string value stored at key. The offset is a zero-based index, with
0 being the first element of the list, 1 being the next element, and so on. The offset must be less than
2^32 and greater than or equal to 0. If a key is non-existent then the bit at offset is set to value and
the preceding bits are set to 0.
The key of the string.
The index of the bit to be set.
The bit value to set at offset. The value must be 0 or 1.
The bit value that was previously stored at offset.
https://valkey.io/commands/setbit/|valkey.io for more details.
Overwrites part of the string stored at key, starting at the specified byte 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. Creates the key if it doesn't exist.
The key of the string to update.
The byte position in the string where value should be written.
The string written with offset.
The length of the string stored at key after it was modified.
https://valkey.io/commands/setrange/|valkey.io for more details.
Gets the intersection of all the given sets.
The keys of the sets to get the intersection.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
https://valkey.io/docs/latest/commands/sinter/|valkey.io for more details.
Gets the cardinality of the intersection of all the given sets.
The keys of the sets.
Optionaloptions: { limit?: number }(Optional) Additional parameters:
limit: the limit for the intersection cardinality value. If not specified, or set to 0, no limit is used.The cardinality of the intersection result. If one or more sets do not exist, 0 is returned.
https://valkey.io/commands/sintercard/|valkey.io for more details.
await client.sadd("set1", ["a", "b", "c"]);
await client.sadd("set2", ["b", "c", "d"]);
const result1 = await client.sintercard(["set1", "set2"]);
console.log(result1);
// Output: 2
// The intersection of `set1` and `set2` contains 2 elements: `b` and `c`.
const result2 = await client.sintercard(["set1", "set2"], { limit: 1 });
console.log(result2);
// Output: 1
// The computation stops early as the intersection cardinality reaches the limit of 1.
Stores the members of the intersection of all given sets specified by keys into a new set at destination.
The key of the destination set.
The keys from which to retrieve the set members.
The number of elements in the resulting set.
https://valkey.io/commands/sinterstore/|valkey.io for more details.
Returns if member is a member of the set stored at key.
The key of the set.
The member to check for existence in the set.
true if the member exists in the set, false otherwise.
If key doesn't exist, it is treated as an empty set and the command returns false.
https://valkey.io/commands/sismember/|valkey.io for more details.
Returns all the members of the set value stored at key.
The key to return its members.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
A Set containing all members of the set.
If key does not exist, it is treated as an empty set and this command returns an empty Set.
https://valkey.io/commands/smembers/|valkey.io for details.
Checks whether each member is contained in the members of the set stored at key.
The key of the set to check.
A list of members to check for existence in the set.
An array of boolean values, each indicating if the respective member exists in the set.
https://valkey.io/commands/smismember/|valkey.io for more details.
Moves member from the set at source to the set at destination, removing it from the source set.
Creates a new destination set if needed. The operation is atomic.
The key of the set to remove the element from.
The key of the set to add the element to.
The set element to move.
true on success, or false if the source set does not exist or the element is not a member of the source set.
https://valkey.io/commands/smove/|valkey.io for more details.
Sorts the elements in the list, set, or sorted set at key and returns the result.
The sort command can be used to sort elements based on different criteria and
apply transformations on sorted elements.
To store the result into a new key, see sortStore.
The key of the list, set, or sorted set to be sorted.
Optionaloptions: SortOptions & DecoderOption(Optional) The SortOptions and DecoderOption.
An Array of sorted elements.
https://valkey.io/commands/sort/|valkey.io for more details.
When in cluster mode, both key and the patterns specified in SortOptions.byPattern
and SortOptions.getPatterns must map to the same hash slot. The use of SortOptions.byPattern
and SortOptions.getPatterns in cluster mode is supported since Valkey version 8.0.
await client.hset("user:1", new Map([["name", "Alice"], ["age", "30"]]));
await client.hset("user:2", new Map([["name", "Bob"], ["age", "25"]]));
await client.lpush("user_ids", ["2", "1"]);
const result = await client.sort("user_ids", { byPattern: "user:*->age", getPattern: ["user:*->name"] });
console.log(result);
// Output: [ 'Bob', 'Alice' ]
// Returns a list of the names sorted by age
Sorts the elements in the list, set, or sorted set at key and returns the result.
The sortReadOnly command can be used to sort elements based on different criteria and
apply transformations on sorted elements.
This command is routed depending on the client's ReadFrom strategy.
The key of the list, set, or sorted set to be sorted.
Optionaloptions: SortOptions & DecoderOption(Optional) The SortOptions and DecoderOption.
An Array of sorted elements
https://valkey.io/commands/sort/|valkey.io for more details.
await client.hset("user:1", new Map([["name", "Alice"], ["age", "30"]]));
await client.hset("user:2", new Map([["name", "Bob"], ["age", "25"]]));
await client.lpush("user_ids", ["2", "1"]);
const result = await client.sortReadOnly("user_ids", { byPattern: "user:*->age", getPattern: ["user:*->name"] });
console.log(result);
// Output: [ 'Bob', 'Alice' ]
// Returns a list of the names sorted by age
Sorts the elements in the list, set, or sorted set at key and stores the result in
destination.
The sort command can be used to sort elements based on different criteria and
apply transformations on sorted elements, and store the result in a new key.
To get the sort result without storing it into a key, see sort or sortReadOnly.
The key of the list, set, or sorted set to be sorted.
The key where the sorted result will be stored.
Optionaloptions: SortOptions(Optional) The SortOptions.
The number of elements in the sorted key stored at destination.
https://valkey.io/commands/sort|valkey.io for more details.
When in cluster mode, key, destination and the patterns specified in SortOptions.byPattern
and SortOptions.getPatterns must map to the same hash slot. The use of SortOptions.byPattern
and SortOptions.getPatterns in cluster mode is supported since Valkey version 8.0.
await client.hset("user:1", new Map([["name", "Alice"], ["age", "30"]]));
await client.hset("user:2", new Map([["name", "Bob"], ["age", "25"]]));
await client.lpush("user_ids", ["2", "1"]);
const sortedElements = await client.sortStore("user_ids", "sortedList", { byPattern: "user:*->age", getPattern: ["user:*->name"] });
console.log(sortedElements);
// Output: 2
// number of elements sorted and stored
console.log(await client.lrange("sortedList", 0, -1));
// Output: [ 'Bob', 'Alice' ]
// Returns a list of the names sorted by age stored in `sortedList`
Removes and returns one random member from the set value store at key.
To pop multiple members, see spopCount.
The key of the set.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
the value of the popped member.
If key does not exist, null will be returned.
https://valkey.io/commands/spop/|valkey.io for details.
Removes and returns up to count random members from the set value store at key, depending on the set's length.
The key of the set.
The count of the elements to pop from the set.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
A Set containing the popped elements, depending on the set's length.
If key does not exist, an empty Set will be returned.
https://valkey.io/commands/spop/|valkey.io for details.
Returns a random element from the set value stored at key.
The key from which to retrieve the set member.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
A random element from the set, or null if key does not exist.
https://valkey.io/commands/srandmember/|valkey.io for more details.
Returns one or more random elements from the set value stored at key.
The key of the sorted set.
The number of members to return.
If count is positive, returns unique members.
If count is negative, allows for duplicates members.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
a list of members from the set. If the set does not exist or is empty, an empty list will be returned.
https://valkey.io/commands/srandmember/|valkey.io for more details.
Removes the specified members from the set stored at key. Specified members that are not a member of this set are ignored.
The key to remove the members from its set.
A list of members to remove from the set stored at key.
The number of members that were removed from the set, not including non existing members.
If key does not exist, it is treated as an empty set and this command returns 0.
https://valkey.io/commands/srem/|valkey.io for details.
Iterates incrementally over a set.
The key of the set.
The cursor that points to the next iteration of results. A value of "0" indicates the start of the search.
Optionaloptions: BaseScanOptions & DecoderOption(Optional) See BaseScanOptions and DecoderOption.
An array of the cursor and the subset of the set held by key. The first element is always the cursor and for the next iteration of results.
The cursor will be "0" on the last iteration of the set. The second element is always an array of the subset of the set held in key.
https://valkey.io/commands/sscan for details.
// Assume key contains a set with 200 members
let newCursor = "0";
let result = [];
do {
result = await client.sscan(key1, newCursor, {
match: "*",
count: 5,
});
newCursor = result[0];
console.log("Cursor: ", newCursor);
console.log("Members: ", result[1]);
} while (newCursor !== "0");
// The output of the code above is something similar to:
// Cursor: 8, Match: "f*"
// Members: ['field', 'fur', 'fun', 'fame']
// Cursor: 20, Count: 3
// Members: ['1', '2', '3', '4', '5', '6']
// Cursor: 0
// Members: ['1', '2', '3', '4', '5', '6']
Returns the length of the string value stored at key.
The key to check its length.
The length of the string value stored at key
If key does not exist, it is treated as an empty string, and the command returns 0.
https://valkey.io/commands/strlen/|valkey.io for more details.
Gets the union of all the given sets.
The keys of the sets.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
A Set of members which are present in at least one of the given sets.
If none of the sets exist, an empty Set will be returned.
https://valkey.io/commands/sunion/|valkey.io for more details.
await client.sadd("my_set1", ["member1", "member2"]);
await client.sadd("my_set2", ["member2", "member3"]);
const result1 = await client.sunion(["my_set1", "my_set2"]);
console.log(result1);
// Output: Set(3) {'member1', 'member2', 'member3'}
// Sets `my_set1` and `my_set2` have three unique members.
const result2 = await client.sunion(["my_set1", "non_existing_set"]);
console.log(result2);
// Output: Set(2) {'member1', 'member2'}
Stores the members of the union of all given sets specified by keys into a new set
at destination.
The key of the destination set.
The keys from which to retrieve the set members.
The number of elements in the resulting set.
https://valkey.io/commands/sunionstore/|valkey.io for details.
Returns the server time.
The current server time as an array with two items:
https://valkey.io/commands/time/|valkey.io for details.
ProtectedtoUpdates the last access time of the specified keys.
The keys to update the last access time of.
The number of keys that were updated. A key is ignored if it doesn't exist.
https://valkey.io/commands/touch/|valkey.io for more details.
In cluster mode, if keys in keys map to different hash slots,
the command will be split across these slots and executed separately for each.
This means the command is atomic only at the slot level. If one or more slot-specific
requests fail, the entire call will return the first encountered error, even
though some requests may have succeeded while others did not.
If this behavior impacts your application logic, consider splitting the
request into sub-requests per slot to ensure atomicity.
Returns the remaining time to live of key that has a timeout.
The key to return its timeout.
TTL in seconds, -2 if key does not exist or -1 if key exists but has no associated expire.
https://valkey.io/commands/ttl/|valkey.io for details.
// Example usage of the ttl method with existing key
const result = await client.ttl("my_key");
console.log(result);
// Output: 3600
// Indicates that `my_key` has a remaining time to live of 3600 seconds.
Returns the string representation of the type of the value stored at key.
The key to check its data type.
If the key exists, the type of the stored value is returned. Otherwise, a "none" string is returned.
https://valkey.io/commands/type/|valkey.io for more details.
Removes the specified keys. A key is ignored if it does not exist.
This command, similar to del, removes specified keys and ignores non-existent ones.
However, this command does not block the server, while https://valkey.io/commands/del|DEL does.
The keys we wanted to unlink.
The number of keys that were unlinked.
In cluster mode, if keys in keys map to different hash slots,
the command will be split across these slots and executed separately for each.
This means the command is atomic only at the slot level. If one or more slot-specific
requests fail, the entire call will return the first encountered error, even
though some requests may have succeeded while others did not.
If this behavior impacts your application logic, consider splitting the
request into sub-requests per slot to ensure atomicity.
https://valkey.io/commands/unlink/|valkey.io for details.
Flushes all the previously watched keys for a transaction. Executing a transaction will automatically flush all previously watched keys.
A simple "OK" response.
https://valkey.io/commands/unwatch/|valkey.io and Glide Wiki for more details.
Update the current connection with a new password.
This method is useful in scenarios where the server password has changed or when utilizing short-lived passwords for enhanced security. It allows the client to update its password to reconnect upon disconnection without the need to recreate the client instance. This ensures that the internal reconnection mechanism can handle reconnection seamlessly, preventing the loss of in-flight commands.
This method updates the client's internal password configuration and does not perform password rotation on the server side.
String | null. The new password to update the current password, or null to remove the current password.
Blocks the current client until all the previous write commands are successfully transferred and
acknowledged by at least numreplicas of replicas. If timeout is reached, the command returns
the number of replicas that were not yet reached.
The number of replicas to reach.
The timeout value specified in milliseconds. A value of 0 will block indefinitely.
The number of replicas reached by all the writes performed in the context of the current connection.
https://valkey.io/commands/wait/|valkey.io for more details.
Marks the given keys to be watched for conditional execution of a transaction. Transactions will only execute commands if the watched keys are not modified before execution of the transaction. Executing a transaction will automatically flush all previously watched keys.
The keys to watch.
A simple "OK" response.
https://valkey.io/commands/watch/|valkey.io and Glide Wiki for more details.
In cluster mode, if keys in keys map to different hash slots,
the command will be split across these slots and executed separately for each.
This means the command is atomic only at the slot level. If one or more slot-specific
requests fail, the entire call will return the first encountered error, even
though some requests may have succeeded while others did not.
If this behavior impacts your application logic, consider splitting the
request into sub-requests per slot to ensure atomicity.
const response = await client.watch(["sampleKey"]);
console.log(response);
// Output: "OK"
const transaction = new Batch(true).set("SampleKey", "foobar");
const result = await client.exec(transaction);
console.log(result);
// Output: "OK"
// Executes successfully and keys are unwatched.
const response = await client.watch(["sampleKey"]);
console.log(response);
// Output: "OK"
const transaction = new Batch(true).set("SampleKey", "foobar");
await client.set("sampleKey", "hello world");
const result = await client.exec(transaction);
console.log(result);
// Output: null
// null is returned when the watched key is modified before transaction execution.
ProtectedwriteInternalThe requests callback index.
A single command or an array of commands to be executed, array of commands represents a batch and not a single command.
Optionalroute: RoutesOptional routing information for the command.
OptionalcommandSpanPtr: number | Long | nullIndicates whether the operation should be executed atomically (AKA as a Transaction, in the case of a batch). Defaults to false.
Determines whether to raise an error if any of the commands fails, in the case of a Batch and not a single command. Defaults to false.
Optional settings for batch requests.
ProtectedwriteReturns the number of messages that were successfully acknowledged by the consumer group member of a stream. This command should be called on a pending message so that such message does not get processed again.
The key of the stream.
The consumer group name.
An array of entry ids.
The number of messages that were successfully acknowledged.
https://valkey.io/commands/xack/|valkey.io for details.
const entryId = await client.xadd("mystream", ["myfield", "mydata"]);
// read messages from streamId
const readResult = await client.xreadgroup(["myfield", "mydata"], "mygroup", "my0consumer");
// acknowledge messages on stream
console.log(await client.xack("mystream", "mygroup", [entryId]));
// Output: 1
Adds an entry to the specified stream stored at key. If the key doesn't exist, the stream is created.
The key of the stream.
field-value pairs to be added to the entry.
Optionaloptions: StreamAddOptions & DecoderOptionoptions detailing how to add to the stream.
The id of the added entry, or null if options.makeStream is set to false and no stream with the matching key exists.
https://valkey.io/commands/xadd/|valkey.io for more details.
Transfers ownership of pending stream entries that match the specified criteria.
The key of the stream.
The consumer group name.
The group consumer.
The minimum idle time for the message to be claimed.
Filters the claimed entries to those that have an ID equal or greater than the specified value.
Optionaloptions: { count?: number } & DecoderOption(Optional) Additional parameters:
count: the number of claimed entries. Default value is 100.decoder: see DecoderOption.A tuple containing the following elements:
XAUTOCLAIM. This ID is
equivalent to the next ID in the stream after the entries that were scanned, or "0-0" if
the entire stream was scanned.Record of the claimed entries.https://valkey.io/commands/xautoclaim/|valkey.io for more details.
const result = await client.xautoclaim("myStream", "myGroup", "myConsumer", 42, "0-0", { count: 25 });
console.log(result);
// Output:
// [
// "1609338788321-0", // value to be used as `start` argument
// // for the next `xautoclaim` call
// {
// "1609338752495-0": [ // claimed entries
// ["field 1", "value 1"],
// ["field 2", "value 2"]
// ]
// },
// [
// "1594324506465-0", // array of IDs of deleted messages,
// "1594568784150-0" // included in the response only on valkey 7.0.0 and above
// ]
// ]
Transfers ownership of pending stream entries that match the specified criteria.
The key of the stream.
The consumer group name.
The group consumer.
The minimum idle time for the message to be claimed.
Filters the claimed entries to those that have an ID equal or greater than the specified value.
Optionaloptions: { count?: number }(Optional) Additional parameters:
count: limits the number of claimed entries to the specified value. Default value is 100.An array containing the following elements:
XAUTOCLAIM. This ID is
equivalent to the next ID in the stream after the entries that were scanned, or "0-0" if
the entire stream was scanned.https://valkey.io/commands/xautoclaim/|valkey.io for more details.
const result = await client.xautoclaim("myStream", "myGroup", "myConsumer", 42, "0-0", { count: 25 });
console.log(result);
// Output:
// [
// "1609338788321-0", // value to be used as `start` argument
// // for the next `xautoclaim` call
// [
// "1609338752495-0", // claimed entries
// "1609338752495-1",
// ],
// [
// "1594324506465-0", // array of IDs of deleted messages,
// "1594568784150-0" // included in the response only on valkey 7.0.0 and above
// ]
// ]
Changes the ownership of a pending message.
The key of the stream.
The consumer group name.
The group consumer.
The minimum idle time for the message to be claimed.
An array of entry ids.
Optionaloptions: StreamClaimOptions & DecoderOption(Optional) See StreamClaimOptions and DecoderOption.
A Record of message entries that are claimed by the consumer.
https://valkey.io/commands/xclaim/|valkey.io for more details.
const result = await client.xclaim("myStream", "myGroup", "myConsumer", 42,
["1-0", "2-0", "3-0"], { idle: 500, retryCount: 3, isForce: true });
console.log(result);
// Output:
// {
// "2-0": [ // Stream Entry id
// ["duration", "1532"], // Entry data tuple containing the field and associated value.
// ["event-id", "5"],
// ["user-id", "7782813"]
// ]
// }
Changes the ownership of a pending message. This function returns an array with
only the message/entry IDs, and is equivalent to using JUSTID in the Valkey API.
The key of the stream.
The consumer group name.
The group consumer.
The minimum idle time for the message to be claimed.
An array of entry ids.
Optionaloptions: StreamClaimOptions(Optional) Stream claim options StreamClaimOptions.
An array of message ids claimed by the consumer.
https://valkey.io/commands/xclaim/|valkey.io for more details.
Removes the specified entries by id from a stream, and returns the number of entries deleted.
The key of the stream.
An array of entry ids.
The number of entries removed from the stream. This number may be less than the number of entries in
ids, if the specified ids don't exist in the stream.
https://valkey.io/commands/xdel/|valkey.io for more details.
Creates a new consumer group uniquely identified by groupname for the stream stored at key.
The key of the stream.
The newly created consumer group name.
Stream entry ID that specifies the last delivered entry in the stream from the new
group’s perspective. The special ID "$" can be used to specify the last entry in the stream.
Optionaloptions: StreamGroupOptions"OK".
https://valkey.io/commands/xgroup-create/|valkey.io for more details.
Creates a consumer named consumerName in the consumer group groupName for the stream stored at key.
The key of the stream.
The consumer group name.
The newly created consumer.
true if the consumer is created. Otherwise, returns false.
https://valkey.io/commands/xgroup-createconsumer/|valkey.io for more details.
Deletes a consumer named consumerName in the consumer group groupName for the stream stored at key.
The key of the stream.
The consumer group name.
The consumer to delete.
The number of pending messages the consumer had before it was deleted.
https://valkey.io/commands/xgroup-delconsumer/|valkey.io for more details.
Destroys the consumer group groupname for the stream stored at key.
The key of the stream.
true if the consumer group is destroyed. Otherwise, false.
https://valkey.io/commands/xgroup-destroy/|valkey.io for more details.
Sets the last delivered ID for a consumer group.
The key of the stream.
The consumer group name.
The stream entry ID that should be set as the last delivered ID for the consumer group.
Optionaloptions: { entriesRead?: number }(Optional) Additional parameters:
entriesRead: the number of stream entries already read by the group.
This option can only be specified if you are using Valkey version 7.0.0 or above."OK".
https://valkey.io/commands/xgroup-setid|valkey.io for more details.
Returns the list of all consumers and their attributes for the given consumer group of the
stream stored at key.
The key of the stream.
The consumer group name.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
An Array of Records, where each mapping contains the attributes
of a consumer for the given consumer group of the stream at key.
https://valkey.io/commands/xinfo-consumers/|valkey.io for more details.
const result = await client.xinfoConsumers("my_stream", "my_group");
console.log(result);
// Output:
// [
// {
// "name": "Alice", // The consumer name.
// "pending": 1, // The number of entries in Pending entries list.
// "idle": 9104628, // The time passed since last attempted interaction.
// "inactive": 18104698 // The time passed since last successful interaction. Added in Valkey 7.2.0.
// },
// ...
// ]
Returns the list of all consumer groups and their attributes for the stream stored at key.
The key of the stream.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
An array of maps, where each mapping represents the
attributes of a consumer group for the stream at key.
https://valkey.io/commands/xinfo-groups/|valkey.io for details.
const result = await client.xinfoGroups("my_stream");
console.log(result);
// Output:
// [
// {
// "name": "mygroup", // The consumer group name.
// "consumers": 2, // Number of consumers in the group.
// "pending": 2, // The length of the group's pending entry list.
// "last-delivered-id": "1638126030001-0", // The id of the last delivered entry to the consumers.
// "entries-read": 2, // The read counter. Added in Valkey 7.0.0.
// "lag": 0 // The number of entries that are still waiting to be delivered. Added in Valkey 7.0.0.
// },
// {
// "name": "some-other-group",
// "consumers": 1,
// "pending": 0,
// "last-delivered-id": "0-0",
// "entries-read": null, // Added in Valkey 7.0.0.
// "lag": 1 // Added in Valkey 7.0.0.
// }
// ]
Returns information about the stream stored at key.
The key of the stream.
Optionaloptions: { fullOptions?: number | boolean } & DecoderOption(Optional) Additional parameters:
fullOptions: If true, returns verbose information with a limit of the first 10 PEL entries.
If number is specified, returns verbose information limiting the returned PEL entries.
If 0 is specified, returns verbose information with no limit.A ReturnTypeXinfoStream of detailed stream information for the given key. See
the example for a sample response.
https://valkey.io/commands/xinfo-stream/|valkey.io for more details.
const infoResult = await client.xinfoStream("my_stream");
console.log(infoResult);
// Output: {
// length: 2, // The number of entries in the stream.
// "radix-tree-keys": 1, // The number of keys in the underlying radix data structure.
// "radix-tree-nodes": 2, // The number of nodes in the underlying radix data structure.
// "last-generated-id": "1719877599564-1", // The ID of the least-recently entry that was added to the stream.
// "max-deleted-entry-id": "0-0", // The maximal entry ID that was deleted from the stream. Added in Valkey 7.0.0.
// "entries-added": 2, // The count of all entries added to the stream during its lifetime. Added in Valkey 7.0.0.
// "recorded-first-entry-id": "1719877599564-0", // Recorded first entry id. Added in Valkey 7.0.0.
// "first-entry": [ "1719877599564-0", ["some_field", "some_value", ...] ], // The ID and field-value tuples of the first entry in the stream.
// "last-entry": [ "1719877599564-0", ["some_field", "some_value", ...] ], // The ID and field-value tuples of the last entry in the stream.
// "groups": 1, // The number of consumer groups defined for the stream
// }
const infoResult = await client.xinfoStream("my_stream", true); // default limit of 10 entries
const infoResult = await client.xinfoStream("my_stream", 15); // limit of 15 entries
console.log(infoResult);
// Output: {
// "length": 2, // The number of entries in the stream.
// "radix-tree-keys": 1, // The number of keys in the underlying radix data structure.
// "radix-tree-nodes": 2, // The number of nodes in the underlying radix data structure.
// "last-generated-id": "1719877599564-1", // The ID of the least-recently entry that was added to the stream.
// "max-deleted-entry-id": "0-0", // The maximal entry ID that was deleted from the stream. Added in Valkey 7.0.0.
// "entries-added": 2, // The count of all entries added to the stream during its lifetime. Added in Valkey 7.0.0.
// "recorded-first-entry-id": "1719877599564-0", // Recorded first entry id. Added in Valkey 7.0.0.
// "entries": [ [ "1719877599564-0", ["some_field", "some_value", ...] ] ], // Array of the stream entries (ID and field-value tuples) in ascending order.
// "groups': [ { // An array of groups containing information about each consumer group.
// "name': "group", // The consumer group's name.
// "last-delivered-id": "1719877599564-0", // The ID of the last entry delivered to the group's consumers.
// "entries-read": 1, // The logical "read counter" of the last entry delivered to the group's consumers. Added in Valkey 7.0.0.
// "lag": 1, // The number of entries in the stream that are still waiting to be delivered. Added in Valkey 7.0.0.
// "pel-count": 1, // The length of the group's pending entries list (PEL).
// "pending": [ [ "1719877599564-0", "consumer", 1722624726802, 1 ] ], // An array with pending entries.
// "consumers": [ {
// "name": "consumer", // The consumer's name.
// "seen-time": 1722624726802, // The UNIX timestamp of the last attempted interaction.
// "active-time": 1722624726802, // The UNIX timestamp of the last successful interaction. Added in Valkey 7.2.0.
// "pel-count": 1, // The number of entries in the PEL.
// "pending": [ [ "1719877599564-0", "consumer", 1722624726802, 1 ] ], // An array with pending entries information.
// }
// ]
// }
// ]
// }
Returns the number of entries in the stream stored at key.
The key of the stream.
The number of entries in the stream. If key does not exist, returns 0.
https://valkey.io/commands/xlen/|valkey.io for more details.
Returns stream message summary information for pending messages matching a given range of IDs.
The key of the stream.
The consumer group name.
An array that includes the summary of the pending messages. See example for more details.
https://valkey.io/commands/xpending/|valkey.io for more details.
console.log(await client.xpending("my_stream", "my_group"));
// Output:
// [
// 42, // The total number of pending messages
// "1722643465939-0", // The smallest ID among the pending messages
// "1722643484626-0", // The greatest ID among the pending messages
// [ // A 2D-`array` of every consumer in the group
// [ "consumer1", "10" ], // with at least one pending message, and the
// [ "consumer2", "32" ], // number of pending messages it has
// ]
// ]
Returns an extended form of stream message information for pending messages matching a given range of IDs.
The key of the stream.
The consumer group name.
Additional options to filter entries, see StreamPendingOptions.
A 2D-array of 4-tuples containing extended message information. See example for more details.
https://valkey.io/commands/xpending/|valkey.io for more details.
console.log(await client.xpending("my_stream", "my_group"), {
start: { value: "0-1", isInclusive: true },
end: InfBoundary.PositiveInfinity,
count: 2,
consumer: "consumer1"
});
// Output:
// [
// [
// "1722643465939-0", // The ID of the message
// "consumer1", // The name of the consumer that fetched the message and has still to acknowledge it
// 174431, // The number of milliseconds that elapsed since the last time this message was delivered to this consumer
// 1 // The number of times this message was delivered
// ],
// [
// "1722643484626-0",
// "consumer1",
// 202231,
// 1
// ]
// ]
Returns stream entries matching a given range of entry IDs.
The key of the stream.
The starting stream entry ID bound for the range.
- Use value to specify a stream entry ID.
- Use isInclusive: false to specify an exclusive bounded stream entry ID. This is only available starting with Valkey version 6.2.0.
- Use InfBoundary.NegativeInfinity to start with the minimum available ID.
The ending stream entry ID bound for the range.
- Use value to specify a stream entry ID.
- Use isInclusive: false to specify an exclusive bounded stream entry ID. This is only available starting with Valkey version 6.2.0.
- Use InfBoundary.PositiveInfinity to end with the maximum available ID.
Optionaloptions: { count?: number } & DecoderOption(Optional) Additional parameters:
count: the maximum count of stream entries to return.
If count is not provided, all stream entries in the range will be returned.decoder: see DecoderOption.A map of stream entry ids, to an array of entries, or null if count is non-positive.
https://valkey.io/commands/xrange/|valkey.io for more details.
await client.xadd("mystream", [["field1", "value1"]], {id: "0-1"});
await client.xadd("mystream", [["field2", "value2"], ["field2", "value3"]], {id: "0-2"});
console.log(await client.xrange("mystream", InfBoundary.NegativeInfinity, InfBoundary.PositiveInfinity));
// Output:
// {
// "0-1": [["field1", "value1"]],
// "0-2": [["field2", "value2"], ["field2", "value3"]],
// }
// Indicates the stream entry IDs and their associated field-value pairs for all stream entries in `mystream`.
Reads entries from the given streams.
An object of stream keys and entry IDs to read from.
Optionaloptions: StreamReadOptions & DecoderOption(Optional) Parameters detailing how to read the stream - see StreamReadOptions and DecoderOption.
A list of stream keys with a Record of stream IDs mapped to an Array of entries or null if key does not exist.
https://valkey.io/commands/xread/|valkey.io for more details.
const streamResults = await client.xread({"my_stream": "0-0", "writers": "0-0"});
console.log(result);
// Output:
// [
// {
// key: "my_stream", // Stream key
// value: { // Stream Ids mapped to entries array.
// "1526984818136-0": [["duration", "1532"], ["event-id", "5"], ["user-id", "7782813"]], // Each entry is a key/value tuple.
// "1526999352406-0": [["duration", "812"], ["event-id", "9"], ["user-id", "388234"]],
// }
// },
// {
// key: "writers",
// value: {
// "1526985676425-0": [["name", "Virginia"], ["surname", "Woolf"]],
// "1526985685298-0": [["name", "Jane"], ["surname", "Austen"]],
// }
// }
// ]
Reads entries from the given streams owned by a consumer group.
The consumer group name.
The group consumer.
An object of stream keys and entry IDs to read from.
Use the special entry ID of ">" to receive only new messages.
Optionaloptions: StreamReadOptions & { noAck?: boolean } & DecoderOption(Optional) Parameters detailing how to read the stream - see StreamReadGroupOptions and DecoderOption.
OptionalnoAck?: booleanIf set, messages are not added to the Pending Entries List (PEL). This is equivalent to acknowledging the message when it is read.
A list of stream keys with a Record of stream IDs mapped to an Array of entries.
Returns null if there is no stream that can be served.
https://valkey.io/commands/xreadgroup/|valkey.io for details.
const streamResults = await client.xreadgroup("my_group", "my_consumer", {"my_stream": "0-0", "writers_stream": "0-0", "readers_stream", ">"});
console.log(result);
// Output:
// [
// {
// key: "my_stream",
// value: {
// "1526984818136-0": [["duration", "1532"], ["event-id", "5"], ["user-id", "7782813"]],
// "1526999352406-0": [["duration", "812"], ["event-id", "9"], ["user-id", "388234"]],
// }
// },
// {
// key: "writers_stream",
// value: {
// "1526985676425-0": [["name", "Virginia"], ["surname", "Woolf"]],
// "1526985685298-0": null, // entry was deleted
// }
// },
// {
// key: "readers_stream", // stream is empty
// value: {}
// }
// ]
Returns stream entries matching a given range of entry IDs in reverse order. Equivalent to xrange but returns the entries in reverse order.
The key of the stream.
The ending stream entry ID bound for the range.
- Use value to specify a stream entry ID.
- Use isInclusive: false to specify an exclusive bounded stream entry ID. This is only available starting with Valkey version 6.2.0.
- Use InfBoundary.PositiveInfinity to end with the maximum available ID.
The ending stream ID bound for the range.
- Use value to specify a stream entry ID.
- Use isInclusive: false to specify an exclusive bounded stream entry ID. This is only available starting with Valkey version 6.2.0.
- Use InfBoundary.NegativeInfinity to start with the minimum available ID.
Optionaloptions: { count?: number } & DecoderOption(Optional) Additional parameters:
count: the maximum count of stream entries to return.
If count is not provided, all stream entries in the range will be returned.decoder: see DecoderOption.A map of stream entry ids, to an array of entries, or null if count is non-positive.
https://valkey.io/commands/xrevrange/|valkey.io for more details.
await client.xadd("mystream", [["field1", "value1"]], {id: "0-1"});
await client.xadd("mystream", [["field2", "value2"], ["field2", "value3"]], {id: "0-2"});
console.log(await client.xrevrange("mystream", InfBoundary.PositiveInfinity, InfBoundary.NegativeInfinity));
// Output:
// {
// "0-2": [["field2", "value2"], ["field2", "value3"]],
// "0-1": [["field1", "value1"]],
// }
// Indicates the stream entry IDs and their associated field-value pairs for all stream entries in `mystream`.
Trims the stream stored at key by evicting older entries.
the key of the stream
options detailing how to trim the stream.
The number of entries deleted from the stream. If key doesn't exist, 0 is returned.
https://valkey.io/commands/xtrim/|valkey.io for more details.
Adds members with their scores to the sorted set stored at key.
If a member is already a part of the sorted set, its score is updated.
The key of the sorted set.
A list of members and their corresponding scores or a mapping of members to their corresponding scores.
Optionaloptions: ZAddOptions(Optional) The ZADD options - see ZAddOptions.
The number of elements added to the sorted set.
If ZAddOptions.changed is set to true, returns the number of elements updated in the sorted set.
https://valkey.io/commands/zadd/|valkey.io for more details.
// Example usage of the zadd method to add elements to a sorted set
const data = [{ element: "member1", score: 10.5 }, { element: "member2", score: 8.2 }]
const result = await client.zadd("my_sorted_set", data);
console.log(result);
// Output: 2
// Indicates that two elements have been added to the sorted set `my_sorted_set`.
// Example usage of the zadd method to update scores in an existing sorted set
const options = { conditionalChange: ConditionalChange.ONLY_IF_EXISTS, changed: true };
const result = await client.zadd("existing_sorted_set", { "member1": 10.5, "member2": 8.2 }, options);
console.log(result);
// Output: 2
// Updates the scores of two existing members in the sorted set `existing_sorted_set`.
Increments the score of member in the sorted set stored at key by increment.
If member does not exist in the sorted set, it is added with increment as its score (as if its previous score was 0.0).
If key does not exist, a new sorted set with the specified member as its sole member is created.
The key of the sorted set.
A member in the sorted set to increment score to.
The score to increment the member.
Optionaloptions: ZAddOptions(Optional) The ZADD options - see ZAddOptions.
The score of the member.
If there was a conflict with the options, the operation aborts and null is returned.
https://valkey.io/commands/zadd/|valkey.io for more details.
// Example usage of the zaddIncr method to add a member with a score to a sorted set
const result = await client.zaddIncr("my_sorted_set", member, 5.0);
console.log(result);
// Output: 5.0
// Score of the member after being updated.
// Example usage of the zaddIncr method to add or update a member with a score in an existing sorted set
const result = await client.zaddIncr("existing_sorted_set", member, "3.0", { updateOptions: UpdateByScore.LESS_THAN });
console.log(result);
// Output: null
// Indicates that the member in the sorted set haven't been updated.
Returns the cardinality (number of elements) of the sorted set stored at key.
The key of the sorted set.
The number of elements in the sorted set.
If key does not exist, it is treated as an empty sorted set, and this command returns 0.
https://valkey.io/commands/zcard/|valkey.io for more details.
Returns the number of members in the sorted set stored at key with scores between minScore and maxScore.
The key of the sorted set.
The minimum score to count from. Can be positive/negative infinity, or specific score and inclusivity.
The maximum score to count up to. Can be positive/negative infinity, or specific score and inclusivity.
The number of members in the specified score range.
If key does not exist, it is treated as an empty sorted set, and the command returns 0.
If minScore is greater than maxScore, 0 is returned.
https://valkey.io/commands/zcount/|valkey.io for more details.
// Example usage of the zcount method to count members in a sorted set within a score range
const result = await client.zcount("my_sorted_set", { value: 5.0, isInclusive: true }, InfBoundary.PositiveInfinity);
console.log(result);
// Output: 2
// Indicates that there are 2 members with scores between 5.0 (inclusive) and +inf in the sorted set `my_sorted_set`.
// Example usage of the zcount method to count members in a sorted set within a score range
const result = await client.zcount("my_sorted_set", { value: 5.0, isInclusive: true }, { value: 10.0, isInclusive: false });
console.log(result);
// Output: 1
// Indicates that there is one member with score between 5.0 (inclusive) and 10.0 (exclusive) in the sorted set `my_sorted_set`.
Returns the difference between the first sorted set and all the successive sorted sets. To get the elements with their scores, see zdiffWithScores.
The keys of the sorted sets.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
An array of elements representing the difference between the sorted sets.
If the first key does not exist, it is treated as an empty sorted set, and the command returns an empty array.
https://valkey.io/commands/zdiff/|valkey.io for more details.
await client.zadd("zset1", {"member1": 1.0, "member2": 2.0, "member3": 3.0});
await client.zadd("zset2", {"member2": 2.0});
await client.zadd("zset3", {"member3": 3.0});
const result = await client.zdiff(["zset1", "zset2", "zset3"]);
console.log(result);
// Output: ["member1"]
// `member1` is in `zset1` but not `zset2` or `zset3`.
Calculates the difference between the first sorted set and all the successive sorted sets in keys and stores
the difference as a sorted set to destination, overwriting it if it already exists. Non-existent keys are
treated as empty sets.
The key for the resulting sorted set.
The keys of the sorted sets to compare.
The number of members in the resulting sorted set stored at destination.
https://valkey.io/commands/zdiffstore/|valkey.io for more details.
await client.zadd("zset1", {"member1": 1.0, "member2": 2.0});
await client.zadd("zset2", {"member1": 1.0});
const result1 = await client.zdiffstore("zset3", ["zset1", "zset2"]);
console.log(result1);
// Output: 1
// One member exists in `key1` but not `key2`, and this member was stored in `zset3`.
const result2 = await client.zrange("zset3", {start: 0, end: -1});
console.log(result2);
// Output: ["member2"]
// `member2` is now stored in `my_sorted_set`.
Returns the difference between the first sorted set and all the successive sorted sets, with the associated scores.
The keys of the sorted sets.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
A list of elements and their scores representing the difference between the sorted sets.
If the first key does not exist, it is treated as an empty sorted set, and the command returns an empty array.
https://valkey.io/commands/zdiff/|valkey.io for more details.
await client.zadd("zset1", {"member1": 1.0, "member2": 2.0, "member3": 3.0});
await client.zadd("zset2", {"member2": 2.0});
await client.zadd("zset3", {"member3": 3.0});
const result = await client.zdiffWithScores(["zset1", "zset2", "zset3"]);
console.log(result);
// Output: [{ element: "member1", score: 1.0 }]
// `member1` is in `zset1` but not `zset2` or `zset3`
Increments the score of member in the sorted set stored at key by increment.
If member does not exist in the sorted set, it is added with increment as its score.
If key does not exist, a new sorted set is created with the specified member as its sole member.
The key of the sorted set.
The score increment.
A member of the sorted set.
The new score of member.
https://valkey.io/commands/zincrby/|valkey.io for details.
// Example usage of zincrBy method to increment the value of a member's score
await client.zadd("my_sorted_set", {"member": 10.5, "member2": 8.2});
console.log(await client.zincrby("my_sorted_set", 1.2, "member"));
// Output: 11.7
// The member existed in the set before score was altered, the new score is 11.7.
console.log(await client.zincrby("my_sorted_set", -1.7, "member"));
// Output: 10.0
// Negative increment, decrements the score.
console.log(await client.zincrby("my_sorted_set", 5.5, "non_existing_member"));
// Output: 5.5
// A new member is added to the sorted set with the score of 5.5.
Computes the intersection of sorted sets given by the specified keys and returns a list of intersecting elements.
To get the scores as well, see zinterWithScores.
To store the result in a key as a sorted set, see zinterStore.
The keys of the sorted sets.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
The resulting array of intersecting elements.
https://valkey.io/commands/zinter/|valkey.io for details.
Returns the cardinality of the intersection of the sorted sets specified by keys.
The keys of the sorted sets to intersect.
Optionaloptions: { limit?: number }(Optional) Additional parameters:
limit: the limit for the intersection cardinality value. If not specified, or set to 0, no limit is used.The cardinality of the intersection of the given sorted sets.
https://valkey.io/commands/zintercard/|valkey.io for more details.
Computes the intersection of sorted sets given by the specified keys and stores the result in destination.
If destination already exists, it is overwritten. Otherwise, a new sorted set will be created.
To get the result directly, see zinterWithScores.
The key of the destination sorted set.
The keys of the sorted sets with possible formats:
GlideString[] - for keys only.KeyWeight[] - for weighted keys with score multipliers.Optionaloptions: { aggregationType?: AggregationType }(Optional) Additional parameters:
aggregationType: the aggregation strategy to apply when combining the scores of elements. See AggregationType.
If aggregationType is not specified, defaults to AggregationType.SUM.The number of elements in the resulting sorted set stored at destination.
https://valkey.io/commands/zinterstore/|valkey.io for more details.
await client.zadd("key1", {"member1": 10.5, "member2": 8.2})
await client.zadd("key2", {"member1": 9.5})
// use `zinterstore` with default aggregation and weights
console.log(await client.zinterstore("my_sorted_set", ["key1", "key2"]))
// Output: 1
// Indicates that the sorted set `my_sorted_set` contains one element.
console.log(await client.zrangeWithScores("my_sorted_set", {start: 0, end: -1}))
// Output: {'member1': 20}
// `member1` is now stored in `my_sorted_set` with score of 20.
// use `zinterstore` with default weights
console.log(await client.zinterstore("my_sorted_set", ["key1", "key2"] , { aggregationType: AggregationType.MAX }))
// Output: 1
// Indicates that the sorted set `my_sorted_set` contains one element, and it's score is the maximum score between the sets.
console.log(await client.zrangeWithScores("my_sorted_set", {start: 0, end: -1}))
// Output: {'member1': 10.5}
// `member1` is now stored in `my_sorted_set` with score of 10.5.
Computes the intersection of sorted sets given by the specified keys and returns a list of intersecting elements with scores.
To get the elements only, see zinter.
To store the result in a key as a sorted set, see zinterStore.
The keys of the sorted sets with possible formats:
GlideString[] - for keys only.KeyWeight[] - for weighted keys with score multipliers.Optionaloptions: { aggregationType?: AggregationType } & DecoderOption(Optional) Additional parameters:
aggregationType: the aggregation strategy to apply when combining the scores of elements.
If aggregationType is not specified, defaults to AggregationType.SUM. See AggregationType.decoder: see DecoderOption.A list of elements and their scores representing the intersection of the sorted sets. If a key does not exist, it is treated as an empty sorted set, and the command returns an empty result.
https://valkey.io/commands/zinter/|valkey.io for details.
await client.zadd("key1", {"member1": 10.5, "member2": 8.2});
await client.zadd("key2", {"member1": 9.5});
const result1 = await client.zinterWithScores(["key1", "key2"]);
console.log(result1);
// Output: [{ element: 'member1', score: 20 }]
// `member1` with score of 20 is the result
const result2 = await client.zinterWithScores(["key1", "key2"], AggregationType.MAX)
console.log(result2);
// Output: [{ element: 'member1', score: 10.5 }]
// `member1` with score of 10.5 is the result
Returns the number of members in the sorted set stored at 'key' with scores between 'minLex' and 'maxLex'.
The key of the sorted set.
The minimum lex to count from. Can be negative infinity, or a specific lex and inclusivity.
The maximum lex to count up to. Can be positive infinity, or a specific lex and inclusivity.
The number of members in the specified lex range. If 'key' does not exist, it is treated as an empty sorted set, and the command returns '0'. If maxLex is less than minLex, '0' is returned.
https://valkey.io/commands/zlexcount/|valkey.io for more details.
Pops member-score pairs from the first non-empty sorted set, with the given keys
being checked in the order they are provided.
The keys of the sorted sets.
The element pop criteria - either ScoreFilter.MIN or ScoreFilter.MAX to pop the member with the lowest/highest score accordingly.
Optionaloptions: { count?: number } & DecoderOption(Optional) Additional parameters:
count: the maximum number of popped elements. If not specified, pops one member.decoder: see DecoderOption.A two-element array containing the key name of the set from which the element
was popped, and a SortedSetDataType of the popped elements.
If no member could be popped, returns null.
https://valkey.io/commands/zmpop/|valkey.io for more details.
await client.zadd("zSet1", { one: 1.0, two: 2.0, three: 3.0 });
await client.zadd("zSet2", { four: 4.0 });
console.log(await client.zmpop(["zSet1", "zSet2"], ScoreFilter.MAX, 2));
// Output:
// [ "zSet1", [
// { element: 'three', score: 3 },
// { element: 'two', score: 2 }
// ] ]
// `three` with score 3 and `two` with score 2 were popped from `zSet1`.
Returns the scores associated with the specified members in the sorted set stored at key.
The key of the sorted set.
A list of members in the sorted set.
An array of scores corresponding to members.
If a member does not exist in the sorted set, the corresponding value in the list will be null.
https://valkey.io/commands/zmscore/|valkey.io for more details.
Removes and returns the members with the highest scores from the sorted set stored at key.
If count is provided, up to count members with the highest scores are removed and returned.
Otherwise, only one member with the highest score is removed and returned.
The key of the sorted set.
Optionaloptions: { count?: number } & DecoderOption(Optional) Additional parameters:
count: the maximum number of popped elements. If not specified, pops one member.decoder: see DecoderOption.A list of the removed members and their scores, ordered from the one with the highest score to the one with the lowest.
If key doesn't exist, it will be treated as an empty sorted set and the command returns an empty map.
If count is higher than the sorted set's cardinality, returns all members and their scores, ordered from highest to lowest.
https://valkey.io/commands/zpopmax/|valkey.io for more details.
// Example usage of zpopmax method to remove and return the member with the highest score from a sorted set
const result = await client.zpopmax("my_sorted_set");
console.log(result);
// Output: [{ element: 'member1', score: 10.0 }]
// `member1` with a score of 10.0 has been removed from the sorted set
// Example usage of zpopmax method to remove and return multiple members with the highest scores from a sorted set
const result = await client.zpopmax("my_sorted_set", 2);
console.log(result);
// Output:
// [
// { element: 'member3', score: 7.5 },
// { element: 'member2', score: 8.0 }
// ]
// `member3` with a score of 7.5 and `member2` with a score of 8.0 have been removed from the sorted set
Removes and returns the members with the lowest scores from the sorted set stored at key.
If count is provided, up to count members with the lowest scores are removed and returned.
Otherwise, only one member with the lowest score is removed and returned.
The key of the sorted set.
Optionaloptions: { count?: number } & DecoderOption(Optional) Additional parameters:
count: the maximum number of popped elements. If not specified, pops one member.decoder: see DecoderOption.A list of the removed members and their scores, ordered from the one with the lowest score to the one with the highest.
If key doesn't exist, it will be treated as an empty sorted set and the command returns an empty map.
If count is higher than the sorted set's cardinality, returns all members and their scores.
https://valkey.io/commands/zpopmin/|valkey.io for more details.
// Example usage of zpopmin method to remove and return the member with the lowest score from a sorted set
const result = await client.zpopmin("my_sorted_set");
console.log(result);
// Output: [{ element: 'member1', score: 5.0 }]
// `member1` with a score of 5.0 has been removed from the sorted set
// Example usage of zpopmin method to remove and return multiple members with the lowest scores from a sorted set
const result = await client.zpopmin("my_sorted_set", 2);
console.log(result);
// Output:
// [
// { element: 'member3', score: 7.5 },
// { element: 'member2', score: 8.0 }
// ]
// `member3` with a score of 7.5 and `member2` with a score of 8.0 have been removed from the sorted set
Returns a random member from the sorted set stored at key.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
A string representing a random member from the sorted set.
If the sorted set does not exist or is empty, the response will be null.
https://valkey.io/commands/zrandmember/|valkey.io for more details.
Returns random members from the sorted set stored at key.
The number of members to return.
If count is positive, returns unique members.
If negative, allows for duplicates.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
An array of members from the sorted set.
If the sorted set does not exist or is empty, the response will be an empty array.
https://valkey.io/commands/zrandmember/|valkey.io for more details.
Returns random members with scores from the sorted set stored at key.
The number of members to return.
If count is positive, returns unique members.
If negative, allows for duplicates.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
A list of KeyWeight tuples, which store member names and their respective scores.
If the sorted set does not exist or is empty, the response will be an empty array.
https://valkey.io/commands/zrandmember/|valkey.io for more details.
Returns the specified range of elements in the sorted set stored at key.
ZRANGE can perform different types of range queries: by index (rank), by the score, or by lexicographical order.
To get the elements with their scores, see zrangeWithScores.
The key of the sorted set.
The range query object representing the type of range query to perform.
Optionaloptions: { reverse?: boolean } & DecoderOption(Optional) Additional parameters:
reverse: if true, reverses the sorted set, with index 0 as the element with the highest score.decoder: see DecoderOption.A list of elements within the specified range.
If key does not exist, it is treated as an empty sorted set, and the command returns an empty array.
https://valkey.io/commands/zrange/|valkey.io for more details.
// Example usage of zrange method to retrieve all members of a sorted set in ascending order
const result = await client.zrange("my_sorted_set", { start: 0, end: -1 });
console.log(result1);
// Output: ['member1', 'member2', 'member3']
// All members in ascending order
// Example usage of zrange method to retrieve members within a score range in descending order
const result = await client.zrange("my_sorted_set", {
start: { value: 3, isInclusive: false },
end: InfBoundary.NegativeInfinity,
type: "byScore",
}, { reverse: true });
console.log(result);
// Output: ['member2', 'member1']
// Members with scores within the range of negative infinity to 3, in descending order
Stores a specified range of elements from the sorted set at source, into a new
sorted set at destination. If destination doesn't exist, a new sorted
set is created; if it exists, it's overwritten.
The key for the destination sorted set.
The key of the source sorted set.
The range query object representing the type of range query to perform.
If true, reverses the sorted set, with index 0 as the element with the highest score.
The number of elements in the resulting sorted set.
https://valkey.io/commands/zrangestore/|valkey.io for more details.
// Example usage of zrangeStore to retrieve and store all members of a sorted set in ascending order.
const result = await client.zrangeStore("destination_key", "my_sorted_set", { start: 0, end: -1 });
console.log(result);
// Output: 7
// `destination_key` contains a sorted set with the 7 members from `my_sorted_set`.
// Example usage of zrangeStore method to retrieve members within a score range in ascending order and store in `destination_key`
const result = await client.zrangeStore("destination_key", "my_sorted_set", {
start: InfBoundary.NegativeInfinity,
end: { value: 3, isInclusive: false },
type: "byScore",
});
console.log(result);
// Output: 5
// Stores 5 members with scores within the range of negative infinity to 3, in ascending order, in `destination_key`.
Returns the specified range of elements with their scores in the sorted set stored at key.
Similar to ZRange but with a WITHSCORE flag.
The key of the sorted set.
The range query object representing the type of range query to perform.
Optionaloptions: { reverse?: boolean } & DecoderOption(Optional) Additional parameters:
reverse: if true, reverses the sorted set, with index 0 as the element with the highest score.decoder: see DecoderOption.A list of elements and their scores within the specified range.
If key does not exist, it is treated as an empty sorted set, and the command returns an empty list.
https://valkey.io/commands/zrange/|valkey.io for more details.
// Example usage of zrangeWithScores method to retrieve members within a score range with their scores
const result = await client.zrangeWithScores("my_sorted_set", {
start: { value: 10, isInclusive: false },
end: { value: 20, isInclusive: false },
type: "byScore",
});
console.log(result);
// Output: [{ element: 'member1', score: 10.5 }, { element: 'member2', score: 15.2 }]
// Members with scores between 10 and 20 with their scores
// Example usage of zrangeWithScores method to retrieve members within a score range with their scores
const result = await client.zrangeWithScores("my_sorted_set", {
start: { value: 3, isInclusive: false },
end: InfBoundary.NegativeInfinity,
type: "byScore",
}, { reverse: true });
console.log(result);
// Output: [{ element: 'member7', score: 1.5 }, { element: 'member4', score: -2.0 }]
// Members with scores within the range of negative infinity to 3, with their scores
Returns the rank of member in the sorted set stored at key, with scores ordered from low to high.
To get the rank of member with its score, see zrankWithScore.
The key of the sorted set.
The member whose rank is to be retrieved.
The rank of member in the sorted set.
If key doesn't exist, or if member is not present in the set, null will be returned.
https://valkey.io/commands/zrank/|valkey.io for more details.
Returns the rank of member in the sorted set stored at key with its score, where scores are ordered from the lowest to highest.
The key of the sorted set.
The member whose rank is to be retrieved.
A list containing the rank and score of member in the sorted set.
If key doesn't exist, or if member is not present in the set, null will be returned.
https://valkey.io/commands/zrank/|valkey.io for more details.
// Example usage of zrank_withscore method to retrieve the rank and score of a member in a sorted set
const result = await client.zrank_withscore("my_sorted_set", "member2");
console.log(result);
// Output: [1, 6.0]
// Indicates that `member2` with score 6.0 has the second-lowest score in the sorted set `my_sorted_set`.
Removes the specified members from the sorted set stored at key.
Specified members that are not a member of this set are ignored.
The key of the sorted set.
A list of members to remove from the sorted set.
The number of members that were removed from the sorted set, not including non-existing members.
If key does not exist, it is treated as an empty sorted set, and this command returns 0.
https://valkey.io/commands/zrem/|valkey.io for more details.
Removes all elements in the sorted set stored at key with lexicographical order between minLex and maxLex.
The key of the sorted set.
The minimum lex to count from. Can be negative infinity, or a specific lex and inclusivity.
The maximum lex to count up to. Can be positive infinity, or a specific lex and inclusivity.
The number of members removed.
If key does not exist, it is treated as an empty sorted set, and the command returns 0.
If minLex is greater than maxLex, 0 is returned.
https://valkey.io/commands/zremrangebylex/|valkey.io for more details.
// Example usage of zremRangeByLex method to remove members from a sorted set based on lexicographical order range
const result = await client.zremRangeByLex("my_sorted_set", { value: "a", isInclusive: false }, { value: "e" });
console.log(result);
// Output: 4
// Indicates that 4 members, with lexicographical values ranging from `a` (exclusive) to `e` (inclusive), have been removed from `my_sorted_set`.
Removes all elements in the sorted set stored at key with rank between start and end.
Both start and end are zero-based indexes with 0 being the element with the lowest score.
These indexes can be negative numbers, where they indicate offsets starting at the element with the highest score.
The key of the sorted set.
The starting point of the range.
The end of the range.
The number of members removed.
If start exceeds the end of the sorted set, or if start is greater than end, 0 returned.
If end exceeds the actual end of the sorted set, the range will stop at the actual end of the sorted set.
If key does not exist 0 will be returned.
https://valkey.io/commands/zremrangebyrank/|valkey.io for more details.
Removes all elements in the sorted set stored at key with a score between minScore and maxScore.
The key of the sorted set.
The minimum score to remove from. Can be negative infinity, or specific score and inclusivity.
The maximum score to remove to. Can be positive infinity, or specific score and inclusivity.
The number of members removed.
If key does not exist, it is treated as an empty sorted set, and the command returns 0.
If minScore is greater than maxScore, 0 is returned.
https://valkey.io/commands/zremrangebyscore/|valkey.io for more details.
// Example usage of zremRangeByScore method to remove members from a sorted set based on score range
const result = await client.zremRangeByScore("my_sorted_set", { value: 5.0, isInclusive: true }, InfBoundary.PositiveInfinity);
console.log(result);
// Output: 2
// Indicates that 2 members with scores between 5.0 (inclusive) and +inf have been removed from the sorted set `my_sorted_set`.
// Example usage of zremRangeByScore method when the sorted set does not exist
const result = await client.zremRangeByScore("non_existing_sorted_set", { value: 5.0, isInclusive: true }, { value: 10.0, isInclusive: false });
console.log(result);
// Output: 0
// Indicates that no members were removed as the sorted set `non_existing_sorted_set` does not exist.
Returns the rank of member in the sorted set stored at key, where
scores are ordered from the highest to lowest, starting from 0.
To get the rank of member with its score, see zrevrankWithScore.
The key of the sorted set.
The member whose rank is to be retrieved.
The rank of member in the sorted set, where ranks are ordered from high to low based on scores.
If key doesn't exist, or if member is not present in the set, null will be returned.
https://valkey.io/commands/zrevrank/|valkey.io for more details.
Returns the rank of member in the sorted set stored at key with its
score, where scores are ordered from the highest to lowest, starting from 0.
The key of the sorted set.
The member whose rank is to be retrieved.
A list containing the rank and score of member in the sorted set, where ranks
are ordered from high to low based on scores.
If key doesn't exist, or if member is not present in the set, null will be returned.
https://valkey.io/commands/zrevrank/|valkey.io for more details.
Iterates incrementally over a sorted set.
The key of the sorted set.
The cursor that points to the next iteration of results. A value of "0" indicates the start of
the search.
Optionaloptions: BaseScanOptions & { noScores?: boolean } & DecoderOption(Optional) The zscan options - see ZScanOptions and DecoderOption.
Optional ReadonlynoScores?: booleanIf true, the scores are not included in the results. Supported from Valkey 8.0.0 and above.
An Array of the cursor and the subset of the sorted set held by key.
The first element is always the cursor for the next iteration of results. 0 will be the cursor
returned on the last iteration of the sorted set. The second element is always an Array of the subset
of the sorted set held in key. The Array in the second element is a flattened series of
string pairs, where the value is at even indices and the score is at odd indices.
If options.noScores is to true, the second element will only contain the members without scores.
https://valkey.io/commands/zscan/|valkey.io for more details.
// Assume "key1" contains a sorted set with multiple members
let cursor = "0";
do {
const result = await client.zscan(key1, cursor, {
match: "*",
count: 5,
});
cursor = result[0];
console.log("Cursor: ", cursor);
console.log("Members: ", result[1]);
} while (cursor !== "0");
// The output of the code above is something similar to:
// Cursor: 123
// Members: ['value 163', '163', 'value 114', '114', 'value 25', '25', 'value 82', '82', 'value 64', '64']
// Cursor: 47
// Members: ['value 39', '39', 'value 127', '127', 'value 43', '43', 'value 139', '139', 'value 211', '211']
// Cursor: 0
// Members: ['value 55', '55', 'value 24', '24', 'value 90', '90', 'value 113', '113']
// Zscan with no scores
let newCursor = "0";
let result = [];
do {
result = await client.zscan(key1, newCursor, {
match: "*",
count: 5,
noScores: true,
});
newCursor = result[0];
console.log("Cursor: ", newCursor);
console.log("Members: ", result[1]);
} while (newCursor !== "0");
// The output of the code above is something similar to:
// Cursor: 123
// Members: ['value 163', 'value 114', 'value 25', 'value 82', 'value 64']
// Cursor: 47
// Members: ['value 39', 'value 127', 'value 43', 'value 139', 'value 211']
// Cursor: 0
// Members: ['value 55', 'value 24' 'value 90', 'value 113']
Returns the score of member in the sorted set stored at key.
The key of the sorted set.
The member whose score is to be retrieved.
The score of the member.
If member does not exist in the sorted set, null is returned.
If key does not exist, null is returned.
https://valkey.io/commands/zscore/|valkey.io for more details.
// Example usage of the zscore method∂∂ to get the score of a member in a sorted set
const result = await client.zscore("my_sorted_set", "member");
console.log(result);
// Output: 10.5
// Indicates that the score of `member` in the sorted set `my_sorted_set` is 10.5.
Computes the union of sorted sets given by the specified keys and returns a list of union elements.
To get the scores as well, see zunionWithScores. To store the result in a key as a sorted set, see zunionStore.
The keys of the sorted sets.
Optionaloptions: DecoderOption(Optional) See DecoderOption.
The resulting array of union elements.
https://valkey.io/commands/zunion/|valkey.io for details.
Computes the union of sorted sets given by the specified keys and stores the result in destination.
If destination already exists, it is overwritten. Otherwise, a new sorted set will be created.
To get the result directly, see zunionWithScores.
The key of the destination sorted set.
The keys of the sorted sets with possible formats:
GlideString[] - for keys only.KeyWeight[] - for weighted keys with their score multipliers.Optionaloptions: { aggregationType?: AggregationType }(Optional) Additional parameters:
aggregationType: the aggregation strategy to apply when combining the scores of elements. See AggregationType.
If aggregationType is not specified, defaults to AggregationType.SUM.The number of elements in the resulting sorted set stored at destination.
https://valkey.io/commands/zunionstore/|valkey.io for details.
await client.zadd("key1", {"member1": 10.5, "member2": 8.2})
await client.zadd("key2", {"member1": 9.5})
// use `zunionstore` with default aggregation and weights
console.log(await client.zunionstore("my_sorted_set", ["key1", "key2"]))
// Output: 2
// Indicates that the sorted set `my_sorted_set` contains two elements.
console.log(await client.zrangeWithScores("my_sorted_set", {start: 0, stop: -1}))
// Output: {'member1': 20, 'member2': 8.2}
// `member1` is now stored in `my_sorted_set` with score of 20 and `member2` with score of 8.2.
// use `zunionstore` with default weights
console.log(await client.zunionstore("my_sorted_set", ["key1", "key2"], { aggregationType: AggregationType.MAX }))
// Output: 2
// Indicates that the sorted set `my_sorted_set` contains two elements, and each score is the maximum score between the sets.
console.log(await client.zrangeWithScores("my_sorted_set", {start: 0, stop: -1}))
// Output: {'member1': 10.5, 'member2': 8.2}
// `member1` is now stored in `my_sorted_set` with score of 10.5 and `member2` with score of 8.2.
// use `zunionstore` with default aggregation
console.log(await client.zunionstore("my_sorted_set", [["key1", 2], ["key2", 1]]))
// Output: 2
// Indicates that the sorted set `my_sorted_set` contains two elements
console.log(await client.zrangeWithScores("my_sorted_set", {start: 0, stop: -1}))
// Output: { member2: 16.4, member1: 30.5 }
Computes the intersection of sorted sets given by the specified keys and returns a list of union elements with scores.
To get the elements only, see zunion.
The keys of the sorted sets with possible formats:
Optionaloptions: { aggregationType?: AggregationType } & DecoderOption(Optional) Additional parameters:
aggregationType: the aggregation strategy to apply when combining the scores of elements.
If aggregationType is not specified, defaults to AggregationType.SUM. See AggregationType.decoder: see DecoderOption.A list of elements and their scores representing the intersection of the sorted sets.
https://valkey.io/commands/zunion/|valkey.io for details.
await client.zadd("key1", {"member1": 10.5, "member2": 8.2});
await client.zadd("key2", {"member1": 9.5});
const result1 = await client.zunionWithScores(["key1", "key2"]);
console.log(result1);
// Output: [{ element: 'member1', score: 20 }, { element: 'member2', score: 8.2 }]
// A list of union elements with scores.
const result2 = await client.zunionWithScores(["key1", "key2"], "MAX");
console.log(result2);
// Output: [{ element: 'member1', score: 10.5}, { element: 'member2', score: 8.2 }]
// A list of union elements with score. The score of the common element in both sets (`member1`), is the maximum of scores(10.5) for that member from both sets.
Static__InternalProtected Static__InternalStaticcreateCreates a new GlideClient instance and establishes a connection to a standalone Valkey server.
The configuration options for the client, including server addresses, authentication credentials, TLS settings, database selection, reconnection strategy, and Pub/Sub subscriptions.
A promise that resolves to a connected GlideClient instance.
Use this static method to create and connect a GlideClient to a standalone Valkey server.
The client will automatically handle connection establishment, including any authentication and TLS configurations.
// Connecting to a Standalone Server
import { GlideClient, GlideClientConfiguration } from '@valkey/valkey-glide';
const client = await GlideClient.createClient({
addresses: [
{ host: 'primary.example.com', port: 6379 },
{ host: 'replica1.example.com', port: 6379 },
],
databaseId: 1,
credentials: {
username: 'user1',
password: 'passwordA',
},
useTLS: true,
connectionBackoff: {
numberOfRetries: 5,
factor: 1000,
exponentBase: 2,
jitter: 20,
},
pubsubSubscriptions: {
channelsAndPatterns: {
[GlideClientConfiguration.PubSubChannelModes.Exact]: new Set(['updates']),
},
callback: (msg) => {
console.log(`Received message: ${msg.payload}`);
},
},
});
Protected StaticcreateInternalProtected StaticGetInternal
Client used for connection to standalone servers. Use createClient to request a client.
See
For full documentation refer to Valkey Glide Wiki.