@valkey/valkey-glide
    Preparing search index...

    Class GlideClient

    Client used for connection to standalone servers. Use createClient to request a client.

    For full documentation refer to Valkey Glide Wiki.

    Hierarchy (View Summary)

    Index

    Constructors

    Properties

    Methods

    append bitcount bitfield bitfieldReadOnly bitop bitpos blmove blmpop blpop brpop bzmpop bzpopmax bzpopmin cancelPubSubFuturesWithExceptionSafe clientGetName clientId close completePubSubFuturesSafe configGet configResetStat configRewrite configSet configureAdvancedConfigurationBase configurePubsub connectToServer copy createClientRequest createRefreshIamTokenPromise createScriptInvocationPromise createUpdateConnectionPasswordPromise createWritePromise customCommand dbsize decr decrBy del dump echo ensureClientIsOpen exec exists expire expireAt expiretime fcall fcallReadonly flushall flushdb functionDelete functionDump functionFlush functionKill functionList functionLoad functionRestore functionStats geoadd geodist geohash geopos geosearch geosearchstore get getbit getCallbackIndex getdel getex getPubsubCallbackAndContext getPubSubMessage getrange getStatistics hdel hexists hexpire hexpireat hexpiretime hget hgetall hgetex hincrBy hincrByFloat hkeys hlen hmget hpersist hpexpire hpexpireat hpexpiretime hpttl hrandfield hrandfieldCount hrandfieldWithValues hscan hset hsetex hsetnx hstrlen httl hvals incr incrBy incrByFloat info invokeScript isPubsubConfigured lastsave lcs lcsIdx lcsLen lindex linsert llen lmove lmpop lolwut lpop lpopCount lpos lpush lpushx lrange lrem lset ltrim mget move mset msetnx notificationToPubSubMessageSafe objectEncoding objectFreq objectIdletime objectRefcount persist pexpire pexpireAt pexpiretime pfadd pfcount pfmerge ping processPush processResponse processResultWithSetCommands pttl publish pubsubChannels pubsubNumPat pubsubNumSub randomKey refreshIamToken rename renamenx restore rpop rpopCount rpush rpushx sadd scan scard scriptExists scriptFlush scriptKill scriptShow sdiff sdiffstore select set setbit setrange sinter sintercard sinterstore sismember smembers smismember smove sort sortReadOnly sortStore spop spopCount srandmember srandmemberCount srem sscan strlen sunion sunionstore time toProtobufRoute touch tryGetPubSubMessage ttl type unlink unwatch updateConnectionPassword wait watch writeOrBufferCommandRequest writeOrBufferRequest xack xadd xautoclaim xautoclaimJustId xclaim xclaimJustId xdel xgroupCreate xgroupCreateConsumer xgroupDelConsumer xgroupDestroy xgroupSetId xinfoConsumers xinfoGroups xinfoStream xlen xpending xpendingWithOptions xrange xread xreadgroup xrevrange xtrim zadd zaddIncr zcard zcount zdiff zdiffstore zdiffWithScores zincrby zinter zintercard zinterstore zinterWithScores zlexcount zmpop zmscore zpopmax zpopmin zrandmember zrandmemberWithCount zrandmemberWithCountWithScores zrange zrangeStore zrangeWithScores zrank zrankWithScore zrem zremRangeByLex zremRangeByRank zremRangeByScore zrevrank zrevrankWithScore zscan zscore zunion zunionstore zunionWithScores __createClient __createClientInternal createClient createClientInternal GetSocket

    Constructors

    Properties

    defaultDecoder: Decoder = Decoder.String
    isClosed: boolean = false
    promiseCallbackFunctions:
        | [PromiseFunction, ErrorFunction, Decoder | undefined][]
        | [PromiseFunction, ErrorFunction][] = []

    Methods

    • Appends 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.

      Parameters

      Returns Promise<number>

      The length of the string after appending the value.

      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.

      Parameters

      Returns Promise<number>

      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.

      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 the array of bits representing the string that is held at key based on the specified subcommands.

      Parameters

      Returns Promise<number[]>

      An array of results from the BitFieldGet subcommands.

      Since Valkey version 6.0.0.

      await client.set("key", "A");  // "A" has binary value 01000001
      const result = await client.bitfieldReadOnly("key", [new BitFieldGet(new UnsignedEncoding(2), new BitOffset(1))]);
      console.log(result);
      // Output: [2]
      // The value at offset 1 with an unsigned encoding of 2 is 2.
    • Perform a bitwise operation between multiple keys (containing string values) and store the result in the destination.

      Parameters

      • operation: BitwiseOperation

        The bitwise operation to perform.

      • destination: GlideString

        The key that will store the resulting string.

      • keys: GlideString[]

        The list of keys to perform the bitwise operation on.

      Returns Promise<number>

      The size of the string stored in destination.

      When in cluster mode, destination and all keys must map to the same hash slot.

      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.

      Parameters

      Returns Promise<number>

      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.

      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.

      Parameters

      Returns Promise<GlideString | null>

      The popped element, or null if source does not exist or if the operation timed-out.

      When in cluster mode, both source and destination must map to the same hash slot.

      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.

      Parameters

      • keys: GlideString[]

        An array of keys.

      • direction: ListDirection

        The direction based on which elements are popped from - see ListDirection.

      • timeout: number

        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:

        • (Optional) count: the maximum number of popped elements. If not specified, pops one member.
        • (Optional) decoder: see DecoderOption.

      Returns Promise<{ elements: GlideString[]; key: GlideString } | null>

      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.

      When in cluster mode, all keys must map to the same hash slot.

      await client.lpush("testKey", ["one", "two", "three"]);
      await client.lpush("testKey2", ["five", "six", "seven"]);
      const result = await client.blmpop(["testKey", "testKey2"], ListDirection.LEFT, 0.1, 1);
      console.log(result"testKey");
      // Output: { key: "testKey", elements: ["three"] }
    • 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.

      Parameters

      Returns Promise<[GlideString, GlideString] | null>

      • An 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.

      When in cluster mode, all keys must map to the same hash slot.

      const result = await client.blpop(["list1", "list2"], 5);
      console.log(result);
      // Output: ['list1', 'element']
      // An element `element` popped from the list stored at key `list1`.
    • 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.

      Parameters

      Returns Promise<[GlideString, GlideString] | null>

      • An 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.

      When in cluster mode, all keys must map to the same hash slot.

      // Example usage of brpop method to block and wait for elements from multiple lists
      const result = await client.brpop(["list1", "list2"], 5);
      console.log(result);
      // Output: ["list1", "element"]
      // Indicates an element `element` was popped from `list1`.
    • 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.

      Parameters

      • keys: GlideString[]

        The keys of the sorted sets.

      • modifier: ScoreFilter

        The element pop criteria - either ScoreFilter.MIN or ScoreFilter.MAX to pop the member with the lowest/highest score accordingly.

      • timeout: number

        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:

        • (Optional) count: the maximum number of popped elements. If not specified, pops one member.
        • (Optional) decoder: see DecoderOption.

      Returns Promise<[GlideString, SortedSetDataType] | null>

      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.

      When in cluster mode, all keys must map to the same hash slot.

      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.

      Parameters

      • keys: GlideString[]

        The keys of the sorted sets.

      • timeout: number

        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.

      Returns Promise<[GlideString, GlideString, number] | null>

      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.

      When in cluster mode, keys must map to the same hash slot.

      const data = await client.bzpopmax(["zset1", "zset2"], 0.5);
      console.log(data);
      // Output: ["zset1", "c", 2];
    • 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.

      Parameters

      • keys: GlideString[]

        The keys of the sorted sets.

      • timeout: number

        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.

      Returns Promise<[GlideString, GlideString, number] | null>

      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.

      When in cluster mode, keys must map to the same hash slot.

      const data = await client.bzpopmin(["zset1", "zset2"], 0.5);
      console.log(data);
      // Output: ["zset1", "a", 2];
      // Pops the member `a` with score 2 stored at key `zset1`.
    • Returns the current connection ID.

      Returns Promise<number>

      The ID of the connection.

      const result = await client.clientId();
      console.log("Connection id: " + result);
    • Terminate the client by closing all associated resources, including the socket and any active promises. All open promises will be closed with an exception.

      Parameters

      • OptionalerrorMessage: string

        If defined, this error message will be passed along with the exceptions when closing all open promises.

      Returns void

    • Reads the configuration parameters of the running server. Starting from server version 7, command supports multiple parameters.

      Parameters

      • parameters: string[]

        A list of configuration parameter names to retrieve values for.

      • Optionaloptions: DecoderOption

        (Optional) See DecoderOption.

      Returns Promise<Record<string, GlideString>>

      A map of values corresponding to the configuration parameters.

      // Example usage of configGet method with multiple configuration parameters
      const result = await client.configGet(["timeout", "maxmemory"]);
      console.log(result); // Output: {'timeout': '1000', 'maxmemory': '1GB'}
    • Resets the statistics reported by the server using the INFO and LATENCY HISTOGRAM commands.

      Returns Promise<"OK">

      always "OK".

      // Example usage of configResetStat command
      const result = await client.configResetStat();
      console.log(result); // Output: 'OK'
    • Rewrites the configuration file with the current configuration.

      Returns Promise<"OK">

      "OK" when the configuration was rewritten properly. Otherwise, an error is thrown.

      // Example usage of configRewrite command
      const result = await client.configRewrite();
      console.log(result); // Output: 'OK'
    • Sets configuration parameters to the specified values. Starting from server version 7, command supports multiple parameters.

      Parameters

      • parameters: Record<string, GlideString>

        A map consisting of configuration parameters and their respective values to set.

      Returns Promise<"OK">

      "OK" when the configuration was set properly. Otherwise an error is thrown.

      // Example usage of configSet method to set multiple configuration parameters
      const result = await client.configSet({ timeout: "1000", maxmemory, "1GB" });
      console.log(result); // Output: 'OK'
    • Copies 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.

      Parameters

      • source: GlideString

        The key to the source value.

      • destination: GlideString

        The key where the value should be copied to.

      • Optionaloptions: { destinationDB?: number; replace?: boolean }

        (Optional) Additional parameters:

        • (Optional) destinationDB: the alternative logical database index for the destination key. If not provided, the current database will be used.
        • (Optional) 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.

      Returns Promise<boolean>

      true if source was copied, false if the source was not copied.

      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".
    • Internal

      Creates a promise that resolves or rejects based on the result of a command request.

      Type Parameters

      • T

        The type of the result expected from the promise.

      Parameters

      • command: Command | Command[]

        A single command or an array of commands to be executed, array of commands represents a batch and not a single command.

      • options: WritePromiseOptions = {}

        Optional settings for the write operation, including route, batch options and decoder.

      • isAtomic: boolean = false

        Indicates whether the operation should be executed atomically (AKA as a Transaction, in the case of a batch). Defaults to false.

      • raiseOnError: boolean = 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.

      Returns Promise<T>

      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.

      Parameters

      Returns Promise<GlideReturnType>

      The executed custom command return value.

      Glide Wiki for details on the restrictions and limitations of the custom command API.

      // Example usage of customCommand method to retrieve pub/sub clients
      const result = await client.customCommand(["CLIENT", "LIST", "TYPE", "PUBSUB"]);
      console.log(result); // Output: Returns a list of all pub/sub clients
    • Returns the number of keys in the currently selected database.

      Returns Promise<number>

      The number of keys in the currently selected database.

      const numKeys = await client.dbsize();
      console.log("Number of keys in the current database: ", numKeys);
    • Decrements the number stored at key by one. If key does not exist, it is set to 0 before performing the operation.

      Parameters

      Returns Promise<number>

      the value of key after the decrement.

      // Example usage of decr method to decrement the value of a key by 1
      await client.set("my_counter", "10");
      const result = await client.decr("my_counter");
      console.log(result); // Output: 9
    • Decrements the number stored at key by amount. If key does not exist, it is set to 0 before performing the operation.

      Parameters

      • key: GlideString

        The key to decrement its value.

      • amount: number

        The amount to decrement.

      Returns Promise<number>

      the value of key after the decrement.

      // Example usage of decrby method to decrement the value of a key by a specified amount
      await client.set("my_counter", "10");
      const result = await client.decrby("my_counter", 5);
      console.log(result); // Output: 5
    • Removes the specified keys. A key is ignored if it does not exist.

      Parameters

      Returns Promise<number>

      The number of keys that were removed.

      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.

      // Example usage of del method to delete an existing key
      await client.set("my_key", "my_value");
      const result = await client.del(["my_key"]);
      console.log(result); // Output: 1
      // Example usage of del method for a non-existing key
      const result = await client.del(["non_existing_key"]);
      console.log(result); // Output: 0
    • Serialize the value stored at key in a Valkey-specific format and return it to the user.

      Parameters

      Returns Promise<Buffer | null>

      The serialized value of the data stored at key. If key does not exist, null will be returned.

      let result = await client.dump("myKey");
      console.log(result);
      // Result contains the serialized value of `myKey`
      result = await client.dump("nonExistingKey");
      console.log(result);
      // Output: null
    • Execute a batch by processing the queued commands.

      Notes:

      • Atomic Batches - Transactions: If the transaction fails due to a WATCH command, EXEC will return null.

      Parameters

      • batch: Batch

        A Batch object containing a list of commands to be executed.

      • raiseOnError: boolean

        Determines how errors are handled within the batch response.

        • If 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.
        • If 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.

      Returns Promise<GlideReturnType[] | null>

      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.

      Parameters

      Returns Promise<number>

      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.

      // Example usage of the exists method
      const result = await client.exists(["key1", "key2", "key3"]);
      console.log(result);
      // Output: 3
      // Indicates that all three keys exist in the database.
    • 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.

      Parameters

      • key: GlideString

        The key to set timeout on it.

      • seconds: number

        The timeout in seconds.

      • Optionaloptions: { expireOption?: ExpireOptions }

        (Optional) Additional parameters:

        • (Optional) expireOption: the expire option - see ExpireOptions.

      Returns Promise<boolean>

      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.

      // Example usage of the expire method
      const result = await client.expire("my_key", 60);
      console.log(result);
      // Output: true
      // Indicates that a timeout of 60 seconds has been set for `my_key`.
      // Example usage of the expire method with exisiting expiry
      const result = await client.expire("my_key", 60, { expireOption: ExpireOptions.HasNoExpiry });
      console.log(result);
      // Output: false
      // Indicates that `my_key` has an existing expiry.
    • 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.

      Parameters

      • key: GlideString

        The key to set timeout on it.

      • unixSeconds: number

        The timeout in an absolute Unix timestamp.

      • Optionaloptions: { expireOption?: ExpireOptions }

        (Optional) Additional parameters:

        • (Optional) expireOption: the expire option - see ExpireOptions.

      Returns Promise<boolean>

      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.

      // Example usage of the expireAt method on a key with no previous expiry
      const result = await client.expireAt("my_key", 1672531200, { expireOption: ExpireOptions.HasNoExpiry });
      console.log(result);
      // Output: true
      // Indicates that the expiration time for `my_key` was successfully set.
    • 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.

      Parameters

      • key: GlideString

        The key to determine the expiration value of.

      Returns Promise<number>

      The expiration Unix timestamp in seconds, -2 if key does not exist or -1 if key exists but has no associated expire.

      Since Valkey version 7.0.0.

      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 read-only function.

      Parameters

      • func: GlideString

        The function name.

      • keys: GlideString[]

        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.

      • args: GlideString[]

        A list of function arguments and it should not represent names of keys.

      • Optionaloptions: DecoderOption

        (Optional) See DecoderOption.

      Returns Promise<GlideReturnType>

      The invoked function's return value.

      When in cluster mode, all keys must map to the same hash slot.

      const response = await client.fcallReadOnly("Deep_Thought", ["key1"], ["Answer", "to", "the",
      "Ultimate", "Question", "of", "Life,", "the", "Universe,", "and", "Everything"]);
      console.log(response);
      // Output: 42
      // The return value on the function that was executed.
    • Deletes a library and all its functions.

      Parameters

      Returns Promise<"OK">

      A simple "OK" response.

      Since Valkey version 7.0.0.

      const result = await client.functionDelete("libName");
      console.log(result); // Output: 'OK'
    • Returns the serialized payload of all loaded libraries.

      Returns Promise<Buffer<ArrayBufferLike>>

      The serialized payload of all loaded libraries.

      Since Valkey version 7.0.0.

      const data = await client.functionDump();
      // data can be used to restore loaded functions on any Valkey instance
    • 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.

      Returns Promise<"OK">

      "OK" if function is terminated. Otherwise, throws an error.

      Since Valkey version 7.0.0.

      await client.functionKill();
      
    • Returns information about the functions and libraries.

      Parameters

      Returns Promise<FunctionListResponse>

      Info about all or selected libraries and their functions in FunctionListResponse format.

      Since Valkey version 7.0.0.

      // 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.

      Parameters

      • libraryCode: GlideString

        The source code that implements the library.

      • Optionaloptions: { replace?: boolean } & DecoderOption

        (Optional) Additional parameters:

        • (Optional) replace: Whether the given library should overwrite a library with the same name if it already exists.
        • (Optional) decoder: see DecoderOption.

      Returns Promise<GlideString>

      The library name that was loaded.

      Since Valkey version 7.0.0.

      const code = "#!lua name=mylib \n redis.register_function('myfunc', function(keys, args) return args[1] end)";
      const result = await client.functionLoad(code, { replace: true });
      console.log(result); // Output: 'mylib'
    • 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.

      Parameters

      Returns Promise<FunctionStatsFullResponse>

      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.

      Since Valkey version 7.0.0.

      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.

      Parameters

      Returns Promise<number>

      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.

      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.

      Parameters

      • key: GlideString

        The key of the sorted set.

      • member1: GlideString

        The name of the first member.

      • member2: GlideString

        The name of the second member.

      • Optionaloptions: { unit?: GeoUnit }

        (Optional) Additional parameters:

        • (Optional) unit: the unit of distance measurement - see GeoUnit. If not specified, the GeoUnit.METERS is used as a default unit.

      Returns Promise<number | null>

      The distance between member1 and member2. Returns null, if one or both members do not exist, or if the key does not exist.

      const result = await client.geodist("mySortedSet", "Place1", "Place2", { unit: GeoUnit.KILOMETERS });
      console.log(num);
      // Output: the distance between Place1 and Place2.
    • Returns the GeoHash strings representing the positions of all the specified members in the sorted set stored at key.

      Parameters

      • key: GlideString

        The key of the sorted set.

      • members: GlideString[]

        The array of members whose GeoHash strings are to be retrieved.

      Returns Promise<(string | null)[]>

      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.

      const result = await client.geohash("mySortedSet", ["Palermo", "Catania", "NonExisting"]);
      console.log(result);
      // Output: ["sqc8b49rny0", "sqdtr74hyu0", null]
      // An array of GeoHash string.
    • Returns the positions (longitude, latitude) of all the specified members of the geospatial index represented by the sorted set at key.

      Parameters

      Returns Promise<([number, number] | null)[]>

      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.

      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.

      Parameters

      • key: GlideString

        The key of the sorted set.

      • searchFrom: SearchOrigin

        The query's center point options, could be one of:

        • MemberOrigin to use the position of the given existing member in the sorted set.
        • CoordOrigin to use the given longitude and latitude coordinates.
      • searchBy: GeoSearchShape

        The query's shape options, could be one of:

        • GeoCircleShape to search inside circular area according to given radius.
        • GeoBoxShape to search inside an axis-aligned rectangle, determined by height and width.
      • Optionaloptions: GeoSearchCommonResultOptions & {
            withCoord?: boolean;
            withDist?: boolean;
            withHash?: boolean;
        } & DecoderOption

        (Optional) Parameters to request additional information and configure sorting/limiting the results, see GeoSearchResultOptions and DecoderOption.

        • OptionalwithCoord?: boolean

          Include the coordinate of the returned items.

        • OptionalwithDist?: boolean

          Include 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?: boolean

          Include the geohash of the returned items.

      Returns Promise<[GlideString, [number?, number?, [number, number]?]?][]>

      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:

      • The member (location) name.
      • The distance from the center as a floating point number, in the same unit specified for searchBy, if withDist is set to true.
      • The geohash of the location as a integer number, if withHash is set to true.
      • The coordinates as a two item array of floating point numbers, if withCoord is set to true.

      Since Valkey version 6.2.0.

      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.

      Parameters

      Returns Promise<number>

      The number of elements in the resulting sorted set stored at destination.

      When in cluster mode, destination and source must map to the same hash slot.

      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.

      Parameters

      Returns Promise<GlideString | null>

      If key exists, returns the value of key. Otherwise, return null.

      // 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.

      Parameters

      • key: GlideString

        The key of the string.

      • offset: number

        The index of the bit to return.

      Returns Promise<number>

      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.

      const result = await client.getbit("key", 1);
      console.log(result);
      // Output: 1
      // The second bit of the string stored at `key` is set to 1.
    • Get the value of key and optionally set its expiration. GETEX is similar to get.

      Parameters

      • key: GlideString

        The key to retrieve from the database.

      • Optionaloptions: { expiry: "persist" | { duration: number; type: TimeUnit } } & DecoderOption

        (Optional) Additional Parameters:

        • (Optional) 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.
        • (Optional) decoder: see DecoderOption.

      Returns Promise<GlideString | null>

      If key exists, returns the value of key as a string. Otherwise, return null.

      Since Valkey version 6.2.0.

      const result = await client.getex("key", {expiry: { type: TimeUnit.Seconds, count: 5 }});
      console.log(result);
      // Output: 'value'
    • 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.

      Parameters

      Returns Promise<GlideString | null>

      A substring extracted from the value stored at key.

      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

      Returns object

      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.

      Parameters

      Returns Promise<number>

      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.

      // Example usage of the hdel method
      const result = await client.hdel("my_hash", ["field1", "field2"]);
      console.log(result);
      // Output: 2
      // Indicates that two fields were successfully removed from the hash.
    • Returns if field is an existing field in the hash stored at key.

      Parameters

      Returns Promise<boolean>

      true the hash contains field. If the hash does not contain field, or if key does not exist, it returns false.

      // Example usage of the hexists method with existing field
      const result = await client.hexists("my_hash", "field1");
      console.log(result);
      // Output: true
      // Returns true because `my_hash` hash contains `field1` field.
      // Example usage of the hexists method with non-existing field
      const result = await client.hexists("my_hash", "nonexistent_field");
      console.log(result);
      // Output: false
      // Returns false because `my_hash` hash does not contain `nonexistent_field` field.
    • Sets expiration time for hash fields in seconds. Creates the hash if it doesn't exist.

      Parameters

      • key: GlideString

        The key of the hash.

      • seconds: number

        The expiration time in seconds.

      • fields: GlideString[]

        The fields to set expiration for.

      • Optionaloptions: HExpireOptions

        Optional parameters for the command.

      Returns Promise<number[]>

      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)

      // 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
      // Set expiration only if fields don't have expiration
      const result = await client.hexpire("my_hash", 120, ["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 result = await client.hexpire("my_hash", 300, ["field1"], {
      condition: HashExpirationCondition.ONLY_IF_GREATER_THAN_CURRENT
      });
      console.log(result); // [1] - expiration set because 300 > current TTL
    • Sets expiration time for hash fields using an absolute Unix timestamp in seconds. Creates the hash if it doesn't exist.

      Parameters

      • key: GlideString

        The key of the hash.

      • unixTimestampSeconds: number

        The expiration time as a Unix timestamp in seconds.

      • fields: GlideString[]

        The fields to set expiration for.

      • Optionaloptions: HExpireOptions

        Optional arguments for the HEXPIREAT command. See HExpireOptions.

      Returns Promise<number[]>

      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)

      // 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.

      Parameters

      • key: GlideString

        The key of the hash.

      • fields: GlideString[]

        The list of fields to get the expiration timestamp for.

      Returns Promise<number[]>

      An array of expiration timestamps in seconds for the specified fields:

      • For fields with a timeout, returns the absolute Unix timestamp in seconds.
      • For fields without a timeout, returns -1.
      • For fields that do not exist, returns -2.
      // Get expiration timestamps for hash fields
      const result = await client.hexpiretime("my_hash", ["field1", "field2", "field3"]);
      console.log(result); // [1672531200, -1, -2] - field1 expires at timestamp 1672531200, field2 has no expiration, field3 doesn't exist
      // Get expiration timestamp for a single field
      const result = await client.hexpiretime("my_hash", ["field1"]);
      console.log(result); // [1672531200] - field1 expires at timestamp 1672531200
    • Retrieve the value associated with field in the hash stored at key.

      Parameters

      Returns Promise<GlideString | null>

      the value associated with field, or null when field is not present in the hash or key does not exist.

      // Example usage of the hget method on an-existing field
      await client.hset("my_hash", {"field": "value"});
      const result = await client.hget("my_hash", "field");
      console.log(result);
      // Output: "value"
      // The value associated with `field` in the key `my_hash`.
      // Example usage of the hget method on a non-existing field
      const result = await client.hget("my_hash", "nonexistent_field");
      console.log(result);
      // Output: null
      // Indicates non existent key.
    • Gets hash fields and optionally sets their expiration.

      Parameters

      Returns Promise<(GlideString | null)[]>

      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

      Valkey 9.0.0

    • 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.

      Parameters

      • key: GlideString

        The key of the hash.

      • field: GlideString

        The field in the hash stored at key to increment its value.

      • amount: number

        The amount to increment.

      Returns Promise<number>

      the value of field in the hash stored at key after the increment.

      // Example usage of the hincrby method to increment the value in a hash by a specified amount
      const result = await client.hincrby("my_hash", "field1", 5);
      console.log(result);
      // Output: 5
      // Increments the value stored at hash field `field1` by 5
    • 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.

      Parameters

      • key: GlideString

        The key of the hash.

      • field: GlideString

        The field in the hash stored at key to increment its value.

      • amount: number

        The amount to increment.

      Returns Promise<number>

      the value of field in the hash stored at key after the increment.

      // Example usage of the hincrbyfloat method to increment the value of a floating point in a hash by a specified amount
      const result = await client.hincrbyfloat("my_hash", "field1", 2.5);
      console.log(result);
      // Output: 2.5
      // Increments the value stored at hash field `field1` by 2.5
    • Returns all field names in the hash stored at key.

      Parameters

      Returns Promise<GlideString[]>

      A list of field names for the hash, or an empty list when the key does not exist.

      // 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.

      Parameters

      Returns Promise<number>

      The number of fields in the hash, or 0 when the key does not exist.

      // Example usage of the hlen method with an existing key
      const result = await client.hlen("my_hash");
      console.log(result);
      // Output: 3
      // Returns the number of fields for the hash stored at key `my_hash`.
      // Example usage of the hlen method with a non-existing key
      const result = await client.hlen("non_existing_key");
      console.log(result);
      // Output: 0
      // Returns 0 for non-existent key.
    • Returns the values associated with the specified fields in the hash stored at key.

      Parameters

      Returns Promise<(GlideString | null)[]>

      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.

      // Example usage of the hmget method
      const result = await client.hmget("my_hash", ["field1", "field2"]);
      console.log(result);
      // Output: ["value1", "value2"]
      // A list of values associated with the specified fields.
    • Removes the expiration time associated with each specified field, causing them to persist.

      Parameters

      Returns Promise<number[]>

      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.

      // Remove expiration from hash fields
      const result = await client.hpersist("my_hash", ["field1", "field2"]);
      console.log(result); // [1, -1] - expiration removed from field1, field2 had no expiration
      // Remove expiration from a single field
      const result = await client.hpersist("my_hash", ["field1"]);
      console.log(result); // [1] - expiration removed from field1
    • Sets expiration time for hash fields in milliseconds. Creates the hash if it doesn't exist.

      Parameters

      • key: GlideString

        The key of the hash.

      • milliseconds: number

        The expiration time in milliseconds.

      • fields: GlideString[]

        The fields to set expiration for.

      • Optionaloptions: HExpireOptions

        Optional arguments for the HPEXPIRE command. See HPExpireOptions.

      Returns Promise<number[]>

      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)

      // 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
      // Set expiration only if fields don't have expiration
      const result = await client.hpexpire("my_hash", 120000, ["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 result = await client.hpexpire("my_hash", 300000, ["field1"], {
      condition: HashExpirationCondition.ONLY_IF_GREATER_THAN_CURRENT
      });
      console.log(result); // [1] - expiration set because 300000 ms > current TTL
    • Sets expiration time for hash fields using an absolute Unix timestamp in milliseconds. Creates the hash if it doesn't exist.

      Parameters

      • key: GlideString

        The key of the hash.

      • unixTimestampMilliseconds: number

        The expiration time as a Unix timestamp in milliseconds.

      • fields: GlideString[]

        The fields to set expiration for.

      • Optionaloptions: HExpireOptions

        Optional arguments for the HPEXPIREAT command. See HExpireOptions.

      Returns Promise<number[]>

      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)

      // 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.

      Parameters

      • key: GlideString

        The key of the hash.

      • fields: GlideString[]

        The list of fields to get the expiration timestamp for.

      Returns Promise<number[]>

      An array of expiration timestamps in milliseconds for the specified fields:

      • For fields with a timeout, returns the absolute Unix timestamp in milliseconds.
      • For fields without a timeout, returns -1.
      • For fields that do not exist, returns -2.
      // Get expiration timestamps for hash fields in milliseconds
      const result = await client.hpexpiretime("my_hash", ["field1", "field2", "field3"]);
      console.log(result); // [1672531200000, -1, -2] - field1 expires at timestamp 1672531200000, field2 has no expiration, field3 doesn't exist
      // Get expiration timestamp for a single field in milliseconds
      const result = await client.hpexpiretime("my_hash", ["field1"]);
      console.log(result); // [1672531200000] - field1 expires at timestamp 1672531200000
    • Returns the remaining time to live of hash fields that have a timeout, in milliseconds.

      Parameters

      Returns Promise<number[]>

      An array of TTL values in milliseconds for the specified fields:

      • For fields with a timeout, returns the remaining TTL in milliseconds.
      • For fields without a timeout, returns -1.
      • For fields that do not exist, returns -2.
      // Get TTL for hash fields in milliseconds
      const result = await client.hpttl("my_hash", ["field1", "field2", "field3"]);
      console.log(result); // [120000, -1, -2] - field1 expires in 120000 ms, field2 has no expiration, field3 doesn't exist
      // Get TTL for a single field in milliseconds
      const result = await client.hpttl("my_hash", ["field1"]);
      console.log(result); // [60000] - field1 expires in 60000 ms
    • Retrieves up to count random field names from the hash value stored at key.

      Parameters

      • key: GlideString

        The key of the hash.

      • count: number

        The number of field names to return. If count is positive, returns unique elements. If negative, allows for duplicates.

      • Optionaloptions: DecoderOption

        (Optional) See DecoderOption.

      Returns Promise<GlideString[]>

      An array of random field names from the hash stored at key, or an empty array when the key does not exist.

      Since Valkey version 6.2.0.

      result = await client.hrandfieldCount("my_hash", 2)
      console.log(result);
      // Output: ['field1', 'field2']
      // Returns 2 random fields from the hash stored at key `my_hash`.
    • Retrieves up to count random field names along with their values from the hash value stored at key.

      Parameters

      • key: GlideString

        The key of the hash.

      • count: number

        The number of field names to return. If count is positive, returns unique elements. If negative, allows for duplicates.

      • Optionaloptions: DecoderOption

        (Optional) See DecoderOption.

      Returns Promise<[GlideString, GlideString][]>

      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.

      Since Valkey version 6.2.0.

      const result = await client.hrandfieldCountWithValues("myHash", 2);
      console.log(result);
      // Output: [['field1', 'value1'], ['field2', 'value2']]
      // Returns 2 random field-value pairs from the hash stored at key `my_hash`.
    • Iterates incrementally over a hash.

      Parameters

      • key: GlideString

        The key of the set.

      • cursor: string

        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?: boolean

          If true, the values of the fields are not included in the results. Supported from Valkey 8.0.0 and above.

      Returns Promise<[string, GlideString[]]>

      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.

      // 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.

      Parameters

      Returns Promise<number>

      The number of fields that were added.

      // 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.

      Parameters

      Returns Promise<number>

      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

      Valkey 9.0.0

    • 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.

      Parameters

      Returns Promise<boolean>

      true if the field was set, false if the field already existed and was not set.

      // Example usage of the hsetnx method
      const result = await client.hsetnx("my_hash", "field", "value");
      console.log(result);
      // Output: true
      // Indicates that the field "field" was set successfully in the hash `my_hash`.
      // Example usage of the hsetnx method on a field that already exists
      const result = await client.hsetnx("my_hash", "field", "new_value");
      console.log(result);
      // Output: false
      // Indicates that the field `field` already existed in the hash `my_hash` and was not set again.
    • Returns the string length of the value associated with field in the hash stored at key.

      Parameters

      Returns Promise<number>

      The string length or 0 if field or key does not exist.

      await client.hset("my_hash", {"field": "value"});
      const result = await client.hstrlen("my_hash", "field");
      console.log(result);
      // Output: 5
      // Returns the string length of `value` which is the value associated with the field `field` stored at key `my_hash`.
    • Returns the remaining time to live of hash fields that have a timeout, in seconds.

      Parameters

      • key: GlideString

        The key of the hash.

      • fields: GlideString[]

        The fields in the hash stored at key to retrieve the TTL for.

      Returns Promise<number[]>

      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.

      // Get TTL for hash fields
      const result = await client.httl("my_hash", ["field1", "field2", "field3"]);
      console.log(result); // [120, -1, -2] - field1 expires in 120 seconds, field2 has no expiration, field3 doesn't exist
      // Get TTL for a single field
      const result = await client.httl("my_hash", ["field1"]);
      console.log(result); // [60] - field1 expires in 60 seconds
    • Increments the number stored at key by one. If key does not exist, it is set to 0 before performing the operation.

      Parameters

      Returns Promise<number>

      the value of key after the increment.

      // Example usage of incr method to increment the value of a key
      await client.set("my_counter", "10");
      const result = await client.incr("my_counter");
      console.log(result); // Output: 11
    • Increments the number stored at key by amount. If key does not exist, it is set to 0 before performing the operation.

      Parameters

      • key: GlideString

        The key to increment its value.

      • amount: number

        The amount to increment.

      Returns Promise<number>

      the value of key after the increment.

      // Example usage of incrBy method to increment the value of a key by a specified amount
      await client.set("my_counter", "10");
      const result = await client.incrBy("my_counter", 5);
      console.log(result); // Output: 15
    • 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.

      Parameters

      • key: GlideString

        The key to increment its value.

      • amount: number

        The amount to increment.

      Returns Promise<number>

      the value of key after the increment.

      // Example usage of incrByFloat method to increment the value of a floating point key by a specified amount
      await client.set("my_float_counter", "10.5");
      const result = await client.incrByFloat("my_float_counter", 2.5);
      console.log(result); // Output: 13.0
    • Gets information and statistics about the server.

      Starting from server version 7, command supports multiple section arguments.

      Parameters

      • Optionalsections: InfoOptions[]

        (Optional) A list of InfoOptions values specifying which sections of information to retrieve. When no parameter is provided, Default is assumed.

      Returns Promise<string>

      A string containing the information for the sections requested.

      // Example usage of the info method with retrieving total_net_input_bytes from the result
      const result = await client.info(new Section[] { Section.STATS });
      console.log(someParsingFunction(result, "total_net_input_bytes")); // Output: 1
    • 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.

      Parameters

      • script: Script

        The Lua script to execute.

      • Optionaloptions: { args?: GlideString[]; keys?: GlideString[] } & DecoderOption

        (Optional) Additional parameters:

        • (Optional) keys : the keys that are used in the script.
        • (Optional) args: the arguments for the script.
        • (Optional) decoder: see DecoderOption.

      Returns Promise<GlideReturnType>

      A value that depends on the script that was executed.

      When in cluster mode, all keys must map to the same hash slot.

      const luaScript = new Script("return { KEYS[1], ARGV[1] }");
      const scriptOptions = {
      keys: ["foo"],
      args: ["bar"],
      };
      const result = await invokeScript(luaScript, scriptOptions);
      console.log(result);
      // Output: ['foo', 'bar']
      // The result for the script.
    • Returns UNIX TIME of the last DB save timestamp or startup timestamp if no save was made since then.

      Returns Promise<number>

      UNIX TIME of the last DB save executed with success.

      const timestamp = await client.lastsave();
      console.log("Last DB save was done at " + timestamp);
    • Returns all the longest common subsequences combined between strings stored at key1 and key2.

      Parameters

      Returns Promise<string>

      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.

      When in cluster mode, key1 and key2 must map to the same hash slot.

      await client.mset({"testKey1": "abcd", "testKey2": "axcd"});
      const result = await client.lcs("testKey1", "testKey2");
      console.log(result);
      // Output: 'acd'
      // Returned the longest common subsequence of strings stored at `testKey1` and `testKey2`.
    • Returns the indices and lengths of the longest common subsequences between strings stored at key1 and key2.

      Parameters

      • key1: GlideString

        The key that stores the first string.

      • key2: GlideString

        The key that stores the second string.

      • Optionaloptions: { minMatchLen?: number; withMatchLen?: boolean }

        (Optional) Additional parameters:

        • (Optional) withMatchLen: if true, include the length of the substring matched for the each match.
        • (Optional) minMatchLen: the minimum length of matches to include in the result.

      Returns Promise<Record<string, number | (number | [number, number])[][]>>

      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.
      

      When in cluster mode, key1 and key2 must map to the same hash slot.

      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.

      Parameters

      Returns Promise<number>

      The total length of all the longest common subsequences between the 2 strings.

      When in cluster mode, key1 and key2 must map to the same hash slot.

      await client.mset({"testKey1": "abcd", "testKey2": "axcd"});
      const result = await client.lcsLen("testKey1", "testKey2");
      console.log(result);
      // Output: 3
      // The total length of all the longest common subsequences between the strings stored at `testKey1` and `testKey2`.
    • 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.

      Parameters

      Returns Promise<GlideString | null>

      • The element at index in the list stored at key. If index is out of range or if key does not exist, null is returned.
      // Example usage of lindex method to retrieve elements from a list by index
      const result = await client.lindex("my_list", 0);
      console.log(result);
      // Output: 'value1'
      // Returns the first element in the list stored at `my_list`.
      // Example usage of lindex method to retrieve elements from a list by negative index
      const result = await client.lindex("my_list", -1);
      console.log(result);
      // Output: 'value3'
      // Returns the last element in the list stored at `my_list`.
    • Inserts element in the list at key either before or after the pivot.

      Parameters

      • key: GlideString

        The key of the list.

      • position: InsertPosition

        The relative position to insert into - either InsertPosition.Before or InsertPosition.After the pivot.

      • pivot: GlideString

        An element of the list.

      • element: GlideString

        The new element to insert.

      Returns Promise<number>

      The list length after a successful insert operation. If the key doesn't exist returns -1. If the pivot wasn't found, returns 0.

      const length = await client.linsert("my_list", InsertPosition.Before, "World", "There");
      console.log(length);
      // Output: 2
      // The list has a length of 2 after performing the insert.
    • Returns the length of the list stored at key.

      Parameters

      Returns Promise<number>

      the length of the list at key. If key does not exist, it is interpreted as an empty list and 0 is returned.

      // Example usage of the llen method
      const result = await client.llen("my_list");
      console.log(result);
      // Output: 3
      // Indicates that there are 3 elements in the list.
    • 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.

      Parameters

      Returns Promise<GlideString | null>

      The popped element, or null if source does not exist.

      Since Valkey version 6.2.0.

      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.

      Parameters

      • keys: GlideString[]

        An array of keys.

      • direction: ListDirection

        The direction based on which elements are popped from - see ListDirection.

      • Optionaloptions: { count?: number } & DecoderOption

        (Optional) Additional parameters:

        • (Optional) count: the maximum number of popped elements. If not specified, pops one member.
        • (Optional) decoder: see DecoderOption.

      Returns Promise<{ elements: GlideString[]; key: GlideString } | null>

      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.

      When in cluster mode, all keys must map to the same hash slot.

      await client.lpush("testKey", ["one", "two", "three"]);
      await client.lpush("testKey2", ["five", "six", "seven"]);
      const result = await client.lmpop(["testKey", "testKey2"], ListDirection.LEFT, 1L);
      console.log(result);
      // Output: { key: "testKey", elements: ["three"] }
    • Displays a piece of generative computer art and the server version.

      Parameters

      Returns Promise<string>

      A piece of generative computer art along with the current server version.

      const response = await client.lolwut({ version: 6, parameters: [40, 20] });
      console.log(response); // Output: "Valkey ver. 7.2.3" - Indicates the current server version.
    • Removes and returns the first elements of the list stored at key. The command pops a single element from the beginning of the list.

      Parameters

      Returns Promise<GlideString | null>

      The value of the first element. If key does not exist null will be returned.

      // Example usage of the lpop method with an existing list
      const result = await client.lpop("my_list");
      console.log(result);
      // Output: 'value1'
      // Returns and removes the first element of the list `value1`.
      // Example usage of the lpop method with a non-existing list
      const result = await client.lpop("non_exiting_key");
      console.log(result);
      // Output: null
      // Returns null for non-existent key.
    • Removes and returns up to count elements of the list stored at key, depending on the list's length.

      Parameters

      Returns Promise<GlideString[] | null>

      A list of the popped elements will be returned depending on the list's length. If key does not exist null will be returned.

      // Example usage of the lpopCount method with an existing list
      const result = await client.lpopCount("my_list", 2);
      console.log(result);
      // Output: ["value1", "value2"]
      // Returns and removes 2 elements from the list.
      // Example usage of the lpopCount method with a non-existing list
      const result = await client.lpopCount("non_exiting_key", 3);
      console.log(result);
      // Output: null
      // Returns null in case of non-existent key.
    • 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.

      Parameters

      Returns Promise<number | number[] | null>

      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.

      Since Valkey version 6.0.6.

      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.

      Parameters

      • key: GlideString

        The key of the list.

      • elements: GlideString[]

        The elements to insert at the head of the list stored at key.

      Returns Promise<number>

      the length of the list after the push operations.

      // Example usage of the lpush method with an existing list
      const result = await client.lpush("my_list", ["value2", "value3"]);
      console.log(result);
      // Output: 3
      // Indicates that the new length of the list is 3 after the push operation.
      // Example usage of the lpush method with a non-existing list
      const result = await client.lpush("nonexistent_list", ["new_value"]);
      console.log(result);
      // Output: 1
      // Indicates that a new list was created with one element
    • Inserts specified values at the head of the list, only if key already exists and holds a list.

      Parameters

      • key: GlideString

        The key of the list.

      • elements: GlideString[]

        The elements to insert at the head of the list stored at key.

      Returns Promise<number>

      The length of the list after the push operation.

      const result = await client.lpushx("my_list", ["value1", "value2"]);
      console.log(result);
      // Output: 2
      // Indicates that the list has two elements after the push operation.
    • 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.

      Parameters

      Returns Promise<GlideString[]>

      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.

      // 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.
      // Example usage of the lrange method with an existing list and negative indices
      const result = await client.lrange("my_list", -2, -1);
      console.log(result);
      // Output: ["value2", "value3"]
      // Returns the last 2 elements of the list.
      // Example usage of the lrange method with a non-existing list
      const result = await client.lrange("non_exiting_key", 0, 2);
      console.log(result);
      // Output: []
      // Returns an empty list for non-existent key.
    • Removes the first count occurrences of elements equal to element from the list stored at key.

      Parameters

      • key: GlideString

        The key of the list.

      • count: number

        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.

      • element: GlideString

        The element to remove from the list.

      Returns Promise<number>

      the number of the removed elements. If key does not exist, 0 is returned.

      // Example usage of the lrem method
      const result = await client.lrem("my_list", 2, "value");
      console.log(result);
      // Output: 2
      // Removes the first 2 occurrences of "value" in the list.
    • 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.

      Parameters

      • key: GlideString

        The key of the list.

      • index: number

        The index of the element in the list to be set.

      • element: GlideString

        The new element to set at the specified index.

      Returns Promise<"OK">

      Always "OK".

      // Example usage of the lset method
      const result = await client.lset("test_key", 1, "two");
      console.log(result);
      // Output: 'OK'
      // Indicates that the second index of the list has been set to "two".
    • 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.

      Parameters

      • key: GlideString

        The key of the list.

      • start: number

        The starting point of the range.

      • end: number

        The end of the range.

      Returns Promise<"OK">

      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.

      // Example usage of the ltrim method
      const result = await client.ltrim("my_list", 0, 1);
      console.log(result);
      // Output: 'OK'
      // Indicates that the list has been trimmed to contain elements from 0 to 1.
    • Retrieve the values of multiple keys.

      Parameters

      Returns Promise<(GlideString | null)[]>

      A list of values corresponding to the provided keys. If a key is not found, its corresponding value in the list will be null.

      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.

      // Example usage of mget method to retrieve values of multiple keys
      await client.set("key1", "value1");
      await client.set("key2", "value2");
      const result = await client.mget(["key1", "key2"]);
      console.log(result);
      // Output: ['value1', 'value2']
    • Move key from the currently selected database to the database specified by dbIndex.

      Parameters

      • key: GlideString

        The key to move.

      • dbIndex: number

        The index of the database to move key to.

      Returns Promise<boolean>

      true if key was moved, or false if the key already exists in the destination database or does not exist in the source database.

      Move is available for cluster mode since Valkey 9.0.0 and above.

      const result = await client.move("key", 1);
      console.log(result); // Output: true
    • Set multiple keys to multiple values in a single operation.

      Parameters

      Returns Promise<"OK">

      A simple "OK" response.

      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.

      // Example usage of mset method to set values for multiple keys
      const result = await client.mset({"key1": "value1", "key2": "value2"});
      console.log(result); // Output: 'OK'
      // Example usage of mset method to set values for multiple keys (GlideRecords allow binary data in the key)
      const result = await client.mset([{key: "key1", value: "value1"}, {key: "key2", value: "value2"}]);
      console.log(result); // Output: 'OK'
    • 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.

      Parameters

      Returns Promise<boolean>

      true if all keys were set. false if no key was set.

      When in cluster mode, all keys in keyValueMap must map to the same hash slot.

      const result1 = await client.msetnx({"key1": "value1", "key2": "value2"});
      console.log(result1); // Output: `true`

      const result2 = await client.msetnx({"key2": "value4", "key3": "value5"});
      console.log(result2); // Output: `false`
    • Returns the internal encoding for the Valkey object stored at key.

      Parameters

      • key: GlideString

        The key of the object to get the internal encoding of.

      Returns Promise<string | null>

      • If key exists, returns the internal encoding of the object stored at key as a string. Otherwise, returns null.
      const result = await client.objectEncoding("my_hash");
      console.log(result);
      // Output: "listpack"
    • Returns the logarithmic access frequency counter of a Valkey object stored at key.

      Parameters

      • key: GlideString

        The key of the object to get the logarithmic access frequency counter of.

      Returns Promise<number | null>

      • If key exists, returns the logarithmic access frequency counter of the object stored at key as a number. Otherwise, returns null.
      const result = await client.objectFreq("my_hash");
      console.log(result);
      // Output: 2
      // The logarithmic access frequency counter of `my_hash`.
    • Returns the time in seconds since the last access to the value stored at key.

      Parameters

      • key: GlideString

        The key of the object to get the idle time of.

      Returns Promise<number | null>

      If key exists, returns the idle time in seconds. Otherwise, returns null.

      const result = await client.objectIdletime("my_hash");
      console.log(result);
      // Output: 13
      // `my_hash` was last accessed 13 seconds ago.
    • Returns the reference count of the object stored at key.

      Parameters

      • key: GlideString

        The key of the object to get the reference count of.

      Returns Promise<number | null>

      If key exists, returns the reference count of the object stored at key as a number. Otherwise, returns null.

      const result = await client.objectRefcount("my_hash");
      console.log(result);
      // Output: 2
      // `my_hash` has a reference count of 2.
    • 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).

      Parameters

      • key: GlideString

        The key to remove the existing timeout on.

      Returns Promise<boolean>

      false if key does not exist or does not have an associated timeout, true if the timeout has been removed.

      // Example usage of persist method to remove the timeout associated with a key
      const result = await client.persist("my_key");
      console.log(result);
      // Output: true
      // Indicates that the timeout associated with the key `my_key` was successfully removed.
    • 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.

      Parameters

      • key: GlideString

        The key to set timeout on it.

      • milliseconds: number

        The timeout in milliseconds.

      • Optionaloptions: { expireOption?: ExpireOptions }

        (Optional) Additional parameters:

        • (Optional) expireOption: the expire option - see ExpireOptions.

      Returns Promise<boolean>

      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.

      // Example usage of the pexpire method on a key with no previous expiry
      const result = await client.pexpire("my_key", 60000, { expireOption: ExpireOptions.HasNoExpiry });
      console.log(result);
      // Output: true
      // Indicates that a timeout of 60,000 milliseconds has been set for `my_key`.
    • 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.

      Parameters

      • key: GlideString

        The key to set timeout on it.

      • unixMilliseconds: number

        The timeout in an absolute Unix timestamp.

      • Optionaloptions: { expireOption?: ExpireOptions }

        (Optional) Additional parameters:

        • (Optional) expireOption: the expire option - see ExpireOptions.

      Returns Promise<number>

      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.

      // Example usage of the pexpireAt method on a key with no previous expiry
      const result = await client.pexpireAt("my_key", 1672531200000, { expireOption: ExpireOptions.HasNoExpiry });
      console.log(result);
      // Output: true
      // Indicates that the expiration time for `my_key` was successfully set.
    • Returns the absolute Unix timestamp (since January 1, 1970) at which the given key will expire, in milliseconds.

      Parameters

      • key: GlideString

        The key to determine the expiration value of.

      Returns Promise<number>

      The expiration Unix timestamp in seconds, -2 if key does not exist or -1 if key exists but has no associated expire.

      Since Valkey version 7.0.0.

      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.

      Parameters

      • key: GlideString

        The key of the HyperLogLog data structure to add elements into.

      • elements: GlideString[]

        An array of members to add to the HyperLogLog stored at key.

      Returns Promise<boolean>

      • If the HyperLogLog is newly created, or if the HyperLogLog approximated cardinality is altered, then returns true. Otherwise, returns false.
      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.

      Parameters

      • keys: GlideString[]

        The keys of the HyperLogLog data structures to be analyzed.

      Returns Promise<number>

      • The approximated cardinality of given HyperLogLog data structures. The cardinality of a key that does not exist is 0.

      When in cluster mode, all keys must map to the same hash slot.

      const result = await client.pfcount(["hll_1", "hll_2"]);
      console.log(result);
      // Output: 4
      // The approximate cardinality of the union of `hll_1` and `hll_2`
    • 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.

      Parameters

      • destination: GlideString

        The key of the destination HyperLogLog where the merged data sets will be stored.

      • sourceKeys: GlideString[]

        The keys of the HyperLogLog structures to be merged.

      Returns Promise<"OK">

      A simple "OK" response.

      When in Cluster mode, all keys in sourceKeys and destination must map to the same hash slot.

      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.

      Parameters

      • Optionaloptions: { message?: GlideString } & DecoderOption

        (Optional) Additional parameters:

        • (Optional) message : a message to include in the PING command.
          • If not provided, the server will respond with "PONG".
          • If provided, the server will respond with a copy of the message.
        • (Optional) decoder: see DecoderOption.

      Returns Promise<GlideString>

      "PONG" if message is not provided, otherwise return a copy of message.

      // Example usage of ping method without any message
      const result = await client.ping();
      console.log(result); // Output: 'PONG'
      // Example usage of ping method with a message
      const result = await client.ping("Hello");
      console.log(result); // Output: 'Hello'
    • Parameters

      • response: Response

      Returns void

    • Returns the remaining time to live of key that has a timeout, in milliseconds.

      Parameters

      Returns Promise<number>

      TTL in milliseconds, -2 if key does not exist, -1 if key exists but has no associated expire.

      // 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.
      // Example usage of pttl method with a non-existing key
      const result = await client.pttl("non_existing_key");
      console.log(result);
      // Output: -2
      // Indicates that the key `non_existing_key` does not exist.
      // Example usage of pttl method with an exisiting key that has no associated expire.
      const result = await client.pttl("key");
      console.log(result);
      // Output: -1
      // Indicates that the key `key` has no associated expire.
    • Publish a message on pubsub channel.

      Parameters

      Returns Promise<number>

      • Number of subscriptions in primary node that received the message. Note that this value does not include subscriptions that configured on replicas.
      // Example usage of publish command
      const result = await client.publish("Hi all!", "global-channel");
      console.log(result); // Output: 1 - This message was posted to 1 subscription which is configured on primary node
    • Lists the currently active channels. The command is routed to all nodes, and aggregates the response to a single array.

      Parameters

      • Optionaloptions: { pattern?: GlideString } & DecoderOption

        (Optional) Additional parameters:

        • (Optional) pattern: A glob-style pattern to match active channels. If not provided, all active channels are returned.
        • (Optional) decoder: see DecoderOption.

      Returns Promise<GlideString[]>

      A list of currently active channels matching the given pattern. If no pattern is specified, all active channels are returned.

      const channels = await client.pubsubChannels();
      console.log(channels);
      // Output: ["channel1", "channel2"]

      const newsChannels = await client.pubsubChannels("news.*");
      console.log(newsChannels);
      // Output: ["news.sports", "news.weather"]
    • 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.

      Returns Promise<number>

      The number of unique patterns.

      const patternCount = await client.pubsubNumpat();
      console.log(patternCount);
      // Output: 3
    • Returns the number of subscribers (exclusive of clients subscribed to patterns) for the specified channels.

      Parameters

      Returns Promise<{ channel: GlideString; numSub: number }[]>

      A list of the channel names and their numbers of subscribers.

      When in cluster mode, the command is routed to all nodes, and aggregates the response into a single list.

      const result1 = await client.pubsubNumsub(["channel1", "channel2"]);
      console.log(result1);
      // Output: [{ channel: "channel1", numSub: 3}, { channel: "channel2", numSub: 5 }]

      const result2 = await client.pubsubNumsub([]);
      console.log(result2);
      // Output: []
    • Returns a random existing key name from the currently selected database.

      Parameters

      Returns Promise<GlideString | null>

      A random existing key name from the currently selected database.

      const result = await client.randomKey();
      console.log(result); // Output: "key12" - "key12" is a random existing key name from the currently selected database.
    • 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.

      Returns Promise<GlideString>

      ConfigurationError if the client is not using IAM authentication.

      await client.refreshToken();
      
    • Renames key to newkey. If newkey already exists it is overwritten.

      Parameters

      Returns Promise<"OK">

      • If the key was successfully renamed, return "OK". If key does not exist, an error is thrown.

      When in cluster mode, key and newKey must map to the same hash slot.

      // Example usage of rename method to rename a key
      await client.set("old_key", "value");
      const result = await client.rename("old_key", "new_key");
      console.log(result);
      // Output: OK
      // Indicates successful renaming of the key `old_key` to `new_key`.
    • Renames key to newkey if newkey does not yet exist.

      Parameters

      Returns Promise<boolean>

      • If the key was successfully renamed, returns true. Otherwise, returns false. If key does not exist, an error is thrown.

      When in cluster mode, key and newKey must map to the same hash slot.

      // Example usage of renamenx method to rename a key
      await client.set("old_key", "value");
      const result = await client.renamenx("old_key", "new_key");
      console.log(result);
      // Output: true
      // Indicates successful renaming of the key `old_key` to `new_key`.
    • Create a key associated with a value that is obtained by deserializing the provided serialized value (obtained via dump).

      Parameters

      • key: GlideString

        The key to create.

      • ttl: number

        The expiry time (in milliseconds). If 0, the key will persist.

      • value: Buffer

        The serialized value to deserialize and assign to key.

      • Optionaloptions: RestoreOptions

        (Optional) Restore options RestoreOptions.

      Returns Promise<"OK">

      Return "OK" if the key was successfully restored with a value.

      options.idletime and options.frequency modifiers cannot be set at the same time.

      const result = await client.restore("myKey", 0, value);
      console.log(result); // Output: "OK"
      const result = await client.restore("myKey", 1000, value, {replace: true, absttl: true});
      console.log(result); // Output: "OK"
      const result = await client.restore("myKey", 0, value, {replace: true, idletime: 10});
      console.log(result); // Output: "OK"
      const result = await client.restore("myKey", 0, value, {replace: true, frequency: 10});
      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.

      Parameters

      Returns Promise<GlideString | null>

      The value of the last element. If key does not exist null will be returned.

      // Example usage of the rpop method with an existing list
      const result = await client.rpop("my_list");
      console.log(result);
      // Output: 'value1'
      // Returns and removes the last element of the list stored at `my_list`.
      // Example usage of the rpop method with a non-existing list
      const result = await client.rpop("non_exiting_key");
      console.log(result);
      // Output: null
      // Returns null for non-existent key.
    • Removes and returns up to count elements from the list stored at key, depending on the list's length.

      Parameters

      Returns Promise<GlideString[] | null>

      A list of popped elements will be returned depending on the list's length. If key does not exist null will be returned.

      // Example usage of the rpopCount method with an existing list
      const result = await client.rpopCount("my_list", 2);
      console.log(result);
      // Output: ["value1", "value2"]
      // Returns and removes the last 2 elements from the list stored at `my_list`.
      // Example usage of the rpopCount method with a non-existing list
      const result = await client.rpopCount("non_exiting_key", 7);
      console.log(result);
      // Output: null
      // Returns null for a non-existing key.
    • 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.

      Parameters

      • key: GlideString

        The key of the list.

      • elements: GlideString[]

        The elements to insert at the tail of the list stored at key.

      Returns Promise<number>

      the length of the list after the push operations.

      // Example usage of the rpush method with an existing list
      const result = await client.rpush("my_list", ["value2", "value3"]);
      console.log(result);
      // Output: 3
      // Indicates that the new length of the list is 3 after the push operation.
      // Example usage of the rpush method with a non-existing list
      const result = await client.rpush("nonexistent_list", ["new_value"]);
      console.log(result);
      // Output: 1
    • Inserts specified values at the tail of the list, only if key already exists and holds a list.

      Parameters

      • key: GlideString

        The key of the list.

      • elements: GlideString[]

        The elements to insert at the tail of the list stored at key.

      Returns Promise<number>

      The length of the list after the push operation.

      const result = await client.rpushx("my_list", ["value1", "value2"]);
      console.log(result);
      // Output: 2
      // Indicates that the list has two elements.
    • 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.

      Parameters

      • key: GlideString

        The key to store the members to its set.

      • members: GlideString[]

        A list of members to add to the set stored at key.

      Returns Promise<number>

      The number of members that were added to the set, not including all the members already present in the set.

      // Example usage of the sadd method with an existing set
      const result = await client.sadd("my_set", ["member1", "member2"]);
      console.log(result);
      // Output: 2
      // Adds 2 members to the set at key `my_set`
    • 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.

      Parameters

      • cursor: GlideString

        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.

      Returns Promise<[GlideString, GlideString[]]>

      A List containing the next cursor value and a list of keys, formatted as [cursor, [key1, key2, ...]]

      // 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.

      Parameters

      • key: GlideString

        The key to return the number of its members.

      Returns Promise<number>

      The cardinality (number of elements) of the set, or 0 if key does not exist.

      // Example usage of the scard method
      const result = await client.scard("my_set");
      console.log(result);
      // Output: 3
    • Checks existence of scripts in the script cache by their SHA1 digest.

      Parameters

      • sha1s: GlideString[]

        List of SHA1 digests of the scripts to check.

      Returns Promise<boolean[]>

      A list of boolean values indicating the existence of each script.

      console result = await client.scriptExists(["sha1_digest1", "sha1_digest2"]);
      console.log(result); // Output: [true, false]
    • Kills the currently executing Lua script, assuming no write operation was yet performed by the script.

      Returns Promise<"OK">

      A simple "OK" response.

      console result = await client.scriptKill();
      console.log(result); // Output: "OK"
    • Returns the original source code of a script in the script cache.

      Parameters

      Returns Promise<GlideString>

      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.

      Since Valkey version 8.0.0.

      const scriptHash = script.getHash();
      const scriptSource = await client.scriptShow(scriptHash);
      console.log(scriptSource);
      // Output: "return { KEYS[1], ARGV[1] }"
      // The source for the script
    • Computes the difference between the first set and all the successive sets in keys.

      Parameters

      Returns Promise<Set<GlideString>>

      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.

      When in cluster mode, all keys must map to the same hash slot.

      await client.sadd("set1", ["member1", "member2"]);
      await client.sadd("set2", ["member1"]);
      const result = await client.sdiff(["set1", "set2"]);
      console.log(result);
      // Output: Set(1) {"member1"}
      // `member2` is in `set1` but not `set2`
    • Stores the difference between the first set and all the successive sets in keys into a new set at destination.

      Parameters

      Returns Promise<number>

      The number of elements in the resulting set.

      When in cluster mode, destination and all keys must map to the same hash slot.

      await client.sadd("set1", ["member1", "member2"]);
      await client.sadd("set2", ["member1"]);
      const result = await client.sdiffstore("set3", ["set1", "set2"]);
      console.log(result);
      // Output: 1
      // One member was stored in `set3`, and that member is the diff between `set1` and `set2`.
    • Changes the currently selected database.

      Parameters

      • index: number

        The index of the database to select.

      Returns Promise<"OK">

      A simple "OK" response.

      // Example usage of select method (NOT RECOMMENDED)
      const result = await client.select(2);
      console.log(result); // Output: 'OK'
      // Note: Database selection will be lost on reconnection!
    • Set the given key with the given value. Return value is dependent on the passed options.

      Parameters

      Returns Promise<GlideString | null>

      • If the value is successfully set, return OK. If 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.
      // 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.

      Parameters

      • key: GlideString

        The key of the string.

      • offset: number

        The index of the bit to be set.

      • value: number

        The bit value to set at offset. The value must be 0 or 1.

      Returns Promise<number>

      The bit value that was previously stored at offset.

      const result = await client.setbit("key", 1, 1);
      console.log(result);
      // Output: 0
      // The second bit value was 0 before setting to 1.
    • 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.

      Parameters

      • key: GlideString

        The key of the string to update.

      • offset: number

        The byte position in the string where value should be written.

      • value: GlideString

        The string written with offset.

      Returns Promise<number>

      The length of the string stored at key after it was modified.

      const len = await client.setrange("key", 6, "GLIDE");
      console.log(len);
      // Output: 11
      // New key was created with length of 11 symbols

      const value = await client.get("key");
      console.log(result);
      // Output: "\0\0\0\0\0\0GLIDE"
      // The string was padded with zero bytes
    • Gets the intersection of all the given sets.

      Parameters

      Returns Promise<Set<GlideString>>

      • A set of members which are present in all given sets. If one or more sets do not exist, an empty set will be returned.

      When in cluster mode, all keys must map to the same hash slot.

      // Example usage of sinter method when member exists
      const result = await client.sinter(["my_set1", "my_set2"]);
      console.log(result);
      // Output: Set(1) {'member2'}
      // Indicates that sets have one common member
      // Example usage of sinter method with non-existing key
      const result = await client.sinter(["my_set", "non_existing_key"]);
      console.log(result);
      // Output: Set(0) {}
      // An empty set is returned since the key does not exist.
    • Gets the cardinality of the intersection of all the given sets.

      Parameters

      • keys: GlideString[]

        The keys of the sets.

      • Optionaloptions: { limit?: number }

        (Optional) Additional parameters:

        • (Optional) limit: the limit for the intersection cardinality value. If not specified, or set to 0, no limit is used.

      Returns Promise<number>

      The cardinality of the intersection result. If one or more sets do not exist, 0 is returned.

      When in cluster mode, all keys must map to the same hash slot.

      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.

      Parameters

      • destination: GlideString

        The key of the destination set.

      • keys: GlideString[]

        The keys from which to retrieve the set members.

      Returns Promise<number>

      The number of elements in the resulting set.

      When in cluster mode, destination and all keys must map to the same hash slot.

      const result = await client.sinterstore("my_set", ["set1", "set2"]);
      console.log(result);
      // Output: 2
      // Two elements were stored at `my_set`, and those elements are the intersection of `set1` and `set2`.
    • Returns if member is a member of the set stored at key.

      Parameters

      Returns Promise<boolean>

      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.

      // Example usage of the sismember method when member exists
      const result = await client.sismember("my_set", "member1");
      console.log(result);
      // Output: true
      // Indicates that `member1` exists in the set `my_set`.
      // Example usage of the sismember method when member does not exist
      const result = await client.sismember("my_set", "non_existing_member");
      console.log(result);
      // Output: false
      // Indicates that `non_existing_member` does not exist in the set `my_set`.
    • Checks whether each member is contained in the members of the set stored at key.

      Parameters

      • key: GlideString

        The key of the set to check.

      • members: GlideString[]

        A list of members to check for existence in the set.

      Returns Promise<boolean[]>

      An array of boolean values, each indicating if the respective member exists in the set.

      Since Valkey version 6.2.0.

      await client.sadd("set1", ["a", "b", "c"]);
      const result = await client.smismember("set1", ["b", "c", "d"]);
      console.log(result);
      // Output: [true, true, false]
      // `b` and `c` are members of `set1`, but `d` is not.
    • 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.

      Parameters

      • source: GlideString

        The key of the set to remove the element from.

      • destination: GlideString

        The key of the set to add the element to.

      • member: GlideString

        The set element to move.

      Returns Promise<boolean>

      true on success, or false if the source set does not exist or the element is not a member of the source set.

      When in cluster mode, source and destination must map to the same hash slot.

      const result = await client.smove("set1", "set2", "member1");
      console.log(result);
      // Output: true
      // `member1` was moved from `set1` to `set2`.
    • 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.

      Parameters

      Returns Promise<(GlideString | null)[]>

      An Array of sorted elements.

      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.

      Parameters

      Returns Promise<(GlideString | null)[]>

      An Array of sorted elements

      Since Valkey version 7.0.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.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.

      Parameters

      Returns Promise<number>

      The number of elements in the sorted key stored at destination.

      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.

      Parameters

      Returns Promise<GlideString | null>

      the value of the popped member. If key does not exist, null will be returned.

      // Example usage of spop method to remove and return a random member from a set
      const result = await client.spop("my_set");
      console.log(result);
      // Output: 'member1'
      // Removes and returns a random member from the set `my_set`.
      // Example usage of spop method with non-existing key
      const result = await client.spop("non_existing_key");
      console.log(result);
      // Output: null
    • Removes and returns up to count random members from the set value store at key, depending on the set's length.

      Parameters

      Returns Promise<Set<GlideString>>

      A Set containing the popped elements, depending on the set's length. If key does not exist, an empty Set will be returned.

      // Example usage of spopCount method to remove and return multiple random members from a set
      const result = await client.spopCount("my_set", 2);
      console.log(result);
      // Output: Set(2) {'member2', 'member3'}
      // Removes and returns 2 random members from the set `my_set`.
      // Example usage of spopCount method with non-existing key
      const result = await client.spopCount("non_existing_key");
      console.log(result);
      // Output: Set(0) {}
      // An empty set is returned since the key does not exist.
    • Returns a random element from the set value stored at key.

      Parameters

      Returns Promise<GlideString | null>

      A random element from the set, or null if key does not exist.

      // Example usage of srandmember method to return a random member from a set
      const result = await client.srandmember("my_set");
      console.log(result);
      // Output: 'member1'
      // A random member of `my_set`.
      // Example usage of srandmember method with non-existing key
      const result = await client.srandmember("non_existing_set");
      console.log(result);
      // Output: null
    • Returns one or more random elements from the set value stored at key.

      Parameters

      • key: GlideString

        The key of the sorted set.

      • count: number

        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.

      Returns Promise<GlideString[]>

      a list of members from the set. If the set does not exist or is empty, an empty list will be returned.

      // Example usage of srandmemberCount method to return multiple random members from a set
      const result = await client.srandmemberCount("my_set", -3);
      console.log(result);
      // Output: ['member1', 'member1', 'member2']
      // Random members of `my_set`.
      // Example usage of srandmemberCount method with non-existing key
      const result = await client.srandmemberCount("non_existing_set", 3);
      console.log(result);
      // Output: []
      // An empty list since the key does not exist.
    • Removes the specified members from the set stored at key. Specified members that are not a member of this set are ignored.

      Parameters

      • key: GlideString

        The key to remove the members from its set.

      • members: GlideString[]

        A list of members to remove from the set stored at key.

      Returns Promise<number>

      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.

      // Example usage of the srem method
      const result = await client.srem("my_set", ["member1", "member2"]);
      console.log(result);
      // Output: 2
      // Removes `member1` and `member2` from the set at key `my_set`.
    • Iterates incrementally over a set.

      Parameters

      Returns Promise<[GlideString, GlideString[]]>

      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.

      // 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.

      Parameters

      Returns Promise<number>

      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.

      // Example usage of strlen method with an existing key
      await client.set("key", "GLIDE");
      const length1 = await client.strlen("key");
      console.log(length1);
      // Output: 5
      // Example usage of strlen method with a non-existing key
      const length2 = await client.strlen("non_existing_key");
      console.log(length2);
      // Output: 0
    • Gets the union of all the given sets.

      Parameters

      Returns Promise<Set<GlideString>>

      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.

      When in cluster mode, all keys must map to the same hash slot.

      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.

      Parameters

      • destination: GlideString

        The key of the destination set.

      • keys: GlideString[]

        The keys from which to retrieve the set members.

      Returns Promise<number>

      The number of elements in the resulting set.

      When in cluster mode, destination and all keys must map to the same hash slot.

      const length = await client.sunionstore("mySet", ["set1", "set2"]);
      console.log(length);
      // Output: 2
      // Two elements were stored in `mySet`, and those two members are the union of `set1` and `set2`.
    • Returns the server time.

      Returns Promise<[string, string]>

      The current server time as an array with two items:

      • A Unix timestamp,
      • The amount of microseconds already elapsed in the current second.
      console.log(await client.time()); // Output: ['1710925775', '913580']
      
    • Updates the last access time of the specified keys.

      Parameters

      • keys: GlideString[]

        The keys to update the last access time of.

      Returns Promise<number>

      The number of keys that were updated. A key is ignored if it doesn't exist.

      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.

      await client.set("key1", "value1");
      await client.set("key2", "value2");
      const result = await client.touch(["key1", "key2", "nonExistingKey"]);
      console.log(result);
      // Output: 2
      // The last access time of 2 keys has been updated.
    • Returns the remaining time to live of key that has a timeout.

      Parameters

      Returns Promise<number>

      TTL in seconds, -2 if key does not exist or -1 if key exists but has no associated expire.

      // 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.
      // Example usage of the ttl method with existing key that has no associated expire.
      const result = await client.ttl("key");
      console.log(result);
      // Output: -1
      // Indicates that the key has no associated expire.
      // Example usage of the ttl method with a non-existing key
      const result = await client.ttl("nonexistent_key");
      console.log(result);
      // Output: -2
      // Indicates that the key doesn't exist.
    • Returns the string representation of the type of the value stored at key.

      Parameters

      Returns Promise<string>

      If the key exists, the type of the stored value is returned. Otherwise, a "none" string is returned.

      // Example usage of type method with a string value
      await client.set("key", "value");
      const type = await client.type("key");
      console.log(type);
      // Output: 'string'
      // Example usage of type method with a list
      await client.lpush("key", ["value"]);
      const type = await client.type("key");
      console.log(type);
      // Output: 'list'
    • 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.

      Parameters

      Returns Promise<number>

      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.

      // Example usage of the unlink method
      const result = await client.unlink(["key1", "key2", "key3"]);
      console.log(result);
      // Output: 3
      // Indicates that all three keys were unlinked from the database.
    • Flushes all the previously watched keys for a transaction. Executing a transaction will automatically flush all previously watched keys.

      Returns Promise<"OK">

      A simple "OK" response.

      let response = await client.unwatch();
      console.log(response); // Output: "OK"
    • 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.

      Parameters

      • password: string | null

        String | null. The new password to update the current password, or null to remove the current password.

      • immediateAuth: boolean = false

      Returns Promise<GlideString>

      await client.updateConnectionPassword("newPassword", true)
      // Output: "OK"
    • 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.

      Parameters

      • numreplicas: number

        The number of replicas to reach.

      • timeout: number

        The timeout value specified in milliseconds. A value of 0 will block indefinitely.

      Returns Promise<number>

      The number of replicas reached by all the writes performed in the context of the current connection.

      await client.set(key, value);
      let response = await client.wait(1, 1000);
      console.log(response);
      // Output: return 1 when a replica is reached or 0 if 1000ms is reached.
    • 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.

      Parameters

      Returns Promise<"OK">

      A simple "OK" response.

      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.
    • Internal

      Parameters

      • callbackIdx: number

        The requests callback index.

      • command: Command | Command[]

        A single command or an array of commands to be executed, array of commands represents a batch and not a single command.

      • Optionalroute: Routes

        Optional routing information for the command.

      • OptionalcommandSpanPtr: number | Long | null
      • isAtomic: boolean = false

        Indicates whether the operation should be executed atomically (AKA as a Transaction, in the case of a batch). Defaults to false.

      • raiseOnError: boolean = 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.

      • options: BaseBatchOptions | ClusterBatchOptions = {}

        Optional settings for batch requests.

      Returns void

    • Returns 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.

      Parameters

      • key: GlideString

        The key of the stream.

      • group: GlideString

        The consumer group name.

      • ids: string[]

        An array of entry ids.

      Returns Promise<number>

      The number of messages that were successfully acknowledged.

      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
    • Transfers ownership of pending stream entries that match the specified criteria.

      Parameters

      • key: GlideString

        The key of the stream.

      • group: GlideString

        The consumer group name.

      • consumer: GlideString

        The group consumer.

      • minIdleTime: number

        The minimum idle time for the message to be claimed.

      • start: string

        Filters the claimed entries to those that have an ID equal or greater than the specified value.

      • Optionaloptions: { count?: number } & DecoderOption

        (Optional) Additional parameters:

        • (Optional) count: the number of claimed entries. Default value is 100.
        • (Optional) decoder: see DecoderOption.

      Returns Promise<[GlideString, StreamEntryDataType, GlideString[]?]>

      A tuple containing the following elements:

      • A stream ID to be used as the start argument for the next call to 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.
      • A Record of the claimed entries.
      • If you are using Valkey 7.0.0 or above, the response list will also include a list containing the message IDs that were in the Pending Entries List but no longer exist in the stream. These IDs are deleted from the Pending Entries List.

      Since Valkey version 6.2.0.

      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.

      Parameters

      • key: GlideString

        The key of the stream.

      • group: GlideString

        The consumer group name.

      • consumer: GlideString

        The group consumer.

      • minIdleTime: number

        The minimum idle time for the message to be claimed.

      • start: string

        Filters the claimed entries to those that have an ID equal or greater than the specified value.

      • Optionaloptions: { count?: number }

        (Optional) Additional parameters:

        • (Optional) count: limits the number of claimed entries to the specified value. Default value is 100.

      Returns Promise<[string, string[], string[]?]>

      An array containing the following elements:

      • A stream ID to be used as the start argument for the next call to 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.
      • A list of the IDs for the claimed entries.
      • If you are using Valkey 7.0.0 or above, the response list will also include a list containing the message IDs that were in the Pending Entries List but no longer exist in the stream. These IDs are deleted from the Pending Entries List.

      Since Valkey version 6.2.0.

      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. This function returns an array with only the message/entry IDs, and is equivalent to using JUSTID in the Valkey API.

      Parameters

      Returns Promise<string[]>

      An array of message ids claimed by the consumer.

      const result = await client.xclaimJustId("my_stream", "my_group", "my_consumer", 42,
      ["1-0", "2-0", "3-0"], { idle: 500, retryCount: 3, isForce: true });
      console.log(result);
      // Output: [ "2-0", "3-0" ]
      // A list of entry ids.
    • Removes the specified entries by id from a stream, and returns the number of entries deleted.

      Parameters

      • key: GlideString

        The key of the stream.

      • ids: string[]

        An array of entry ids.

      Returns Promise<number>

      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.

      console.log(await client.xdel("key", ["1538561698944-0", "1538561698944-1"]));
      // Output: 2
      // the stream marked 2 entries as deleted.
    • Creates a new consumer group uniquely identified by groupname for the stream stored at key.

      Parameters

      • key: GlideString

        The key of the stream.

      • groupName: GlideString

        The newly created consumer group name.

      • id: string

        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

      Returns Promise<"OK">

      "OK".

      // Create the consumer group "mygroup", using zero as the starting ID:
      console.log(await client.xgroupCreate("mystream", "mygroup", "0-0"));
      // Output: "OK"
    • Creates a consumer named consumerName in the consumer group groupName for the stream stored at key.

      Parameters

      Returns Promise<boolean>

      true if the consumer is created. Otherwise, returns false.

      // The consumer "myconsumer" was created in consumer group "mygroup" for the stream "mystream".
      console.log(await client.xgroupCreateConsumer("mystream", "mygroup", "myconsumer"));
      // Output: true
    • Deletes a consumer named consumerName in the consumer group groupName for the stream stored at key.

      Parameters

      Returns Promise<number>

      The number of pending messages the consumer had before it was deleted.

      // Consumer "myconsumer" was deleted, and had 5 pending messages unclaimed.
      console.log(await client.xgroupDelConsumer("mystream", "mygroup", "myconsumer"));
      // Output: 5
    • Sets the last delivered ID for a consumer group.

      Parameters

      • key: GlideString

        The key of the stream.

      • groupName: GlideString

        The consumer group name.

      • id: string

        The stream entry ID that should be set as the last delivered ID for the consumer group.

      • Optionaloptions: { entriesRead?: number }

        (Optional) Additional parameters:

        • (Optional) 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.

      Returns Promise<"OK">

      "OK".

      console.log(await client.xgroupSetId("mystream", "mygroup", "0", { entriesRead: 1 }));
      // Output: "OK"
    • Returns the list of all consumers and their attributes for the given consumer group of the stream stored at key.

      Parameters

      Returns Promise<Record<string, number | GlideString>[]>

      An Array of Records, where each mapping contains the attributes of a consumer for the given consumer group of the stream at key.

      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.

      Parameters

      Returns Promise<Record<string, number | GlideString | null>[]>

      An array of maps, where each mapping represents the attributes of a consumer group for the stream at key.

      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.

      Parameters

      • key: GlideString

        The key of the stream.

      • Optionaloptions: { fullOptions?: number | boolean } & DecoderOption

        (Optional) Additional parameters:

        • (Optional) 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.

      Returns Promise<ReturnTypeXinfoStream>

      A ReturnTypeXinfoStream of detailed stream information for the given key. See the example for a sample response.

      fullOptions - Available since Valkey version 6.0.0

      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.

      Parameters

      Returns Promise<number>

      The number of entries in the stream. If key does not exist, returns 0.

      const numEntries = await client.xlen("my_stream");
      console.log(numEntries);
      // Output: 2
      // `my_stream` contains 2 entries.
    • Returns stream message summary information for pending messages matching a given range of IDs.

      Parameters

      Returns Promise<[number, GlideString, GlideString, [GlideString, number][]]>

      An array that includes the summary of the pending messages. See example 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.

      Parameters

      Returns Promise<[GlideString, GlideString, number, number][]>

      A 2D-array of 4-tuples containing extended message information. See example 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.

      Parameters

      • key: GlideString

        The key of the stream.

      • start: Boundary<string>

        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.

      • end: Boundary<string>

        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:

        • (Optional) count: the maximum count of stream entries to return. If count is not provided, all stream entries in the range will be returned.
        • (Optional) decoder: see DecoderOption.

      Returns Promise<StreamEntryDataType | null>

      A map of stream entry ids, to an array of entries, or null if count is non-positive.

      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.

      Parameters

      Returns Promise<GlideRecord<StreamEntryDataType> | null>

      A list of stream keys with a Record of stream IDs mapped to an Array of entries or null if key does not exist.

      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.

      Parameters

      • group: GlideString

        The consumer group name.

      • consumer: GlideString

        The group consumer.

      • keys_and_ids: Record<string, string> | GlideRecord<string>

        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?: boolean

          If set, messages are not added to the Pending Entries List (PEL). This is equivalent to acknowledging the message when it is read.

      Returns Promise<GlideRecord<Record<string, [GlideString, GlideString][] | null>> | null>

      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.

      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.

      Parameters

      • key: GlideString

        The key of the stream.

      • end: Boundary<string>

        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.

      • start: Boundary<string>

        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:

        • (Optional) count: the maximum count of stream entries to return. If count is not provided, all stream entries in the range will be returned.
        • (Optional) decoder: see DecoderOption.

      Returns Promise<StreamEntryDataType | null>

      A map of stream entry ids, to an array of entries, or null if count is non-positive.

      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`.
    • 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.

      Parameters

      • key: GlideString

        The key of the sorted set.

      • membersAndScores: Record<string, Score> | ElementAndScore[]

        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.

      Returns Promise<number>

      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.

      // 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.

      Parameters

      • key: GlideString

        The key of the sorted set.

      • member: GlideString

        A member in the sorted set to increment score to.

      • increment: number

        The score to increment the member.

      • Optionaloptions: ZAddOptions

        (Optional) The ZADD options - see ZAddOptions.

      Returns Promise<number | null>

      The score of the member. If there was a conflict with the options, the operation aborts and null is returned.

      // 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.

      Parameters

      Returns Promise<number>

      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.

      // Example usage of the zcard method to get the cardinality of a sorted set
      const result = await client.zcard("my_sorted_set");
      console.log(result);
      // Output: 3
      // Indicates that there are 3 elements in the sorted set `my_sorted_set`.
      // Example usage of the zcard method with a non-existing key
      const result = await client.zcard("non_existing_key");
      console.log(result);
      // Output: 0
    • Returns the number of members in the sorted set stored at key with scores between minScore and maxScore.

      Parameters

      • key: GlideString

        The key of the sorted set.

      • minScore: Boundary<number>

        The minimum score to count from. Can be positive/negative infinity, or specific score and inclusivity.

      • maxScore: Boundary<number>

        The maximum score to count up to. Can be positive/negative infinity, or specific score and inclusivity.

      Returns Promise<number>

      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.

      // 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.

      Parameters

      Returns Promise<GlideString[]>

      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.

      When in cluster mode, all keys must map to the same hash slot.

      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.

      Parameters

      • destination: GlideString

        The key for the resulting sorted set.

      • keys: GlideString[]

        The keys of the sorted sets to compare.

      Returns Promise<number>

      The number of members in the resulting sorted set stored at destination.

      When in cluster mode, all keys in keys and destination must map to the same hash slot.

      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.

      Parameters

      Returns Promise<SortedSetDataType>

      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.

      When in cluster mode, all keys must map to the same hash slot.

      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.

      Parameters

      • key: GlideString

        The key of the sorted set.

      • increment: number

        The score increment.

      • member: GlideString

        A member of the sorted set.

      Returns Promise<number>

      The new score of member.

      // 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.

      Parameters

      Returns Promise<GlideString[]>

      The resulting array of intersecting elements.

      When in cluster mode, all keys in keys must map to the same hash slot.

      await client.zadd("key1", {"member1": 10.5, "member2": 8.2});
      await client.zadd("key2", {"member1": 9.5});
      const result = await client.zinter(["key1", "key2"]);
      console.log(result);
      // Output: ['member1']
      // The intersecting element for the sorted sets at `key1` and `key2`.
    • Returns the cardinality of the intersection of the sorted sets specified by keys.

      Parameters

      • keys: GlideString[]

        The keys of the sorted sets to intersect.

      • Optionaloptions: { limit?: number }

        (Optional) Additional parameters:

        • (Optional) limit: the limit for the intersection cardinality value. If not specified, or set to 0, no limit is used.

      Returns Promise<number>

      The cardinality of the intersection of the given sorted sets.

      When in cluster mode, all keys must map to the same hash slot.

      const cardinality = await client.zintercard(["key1", "key2"], { limit: 10 });
      console.log(cardinality);
      // Output: 3
      // The intersection of the sorted sets at `key1` and `key2` has a cardinality of 3.
    • 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.

      Parameters

      • destination: GlideString

        The key of the destination sorted set.

      • keys: GlideString[] | KeyWeight[]

        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:

        • (Optional) aggregationType: the aggregation strategy to apply when combining the scores of elements. See AggregationType. If aggregationType is not specified, defaults to AggregationType.SUM.

      Returns Promise<number>

      The number of elements in the resulting sorted set stored at destination.

      When in cluster mode, destination and all keys in keys must map to the same hash slot.

      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.

      Parameters

      • keys: GlideString[] | KeyWeight[]

        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:

        • (Optional) aggregationType: the aggregation strategy to apply when combining the scores of elements. If aggregationType is not specified, defaults to AggregationType.SUM. See AggregationType.
        • (Optional) decoder: see DecoderOption.

      Returns Promise<SortedSetDataType>

      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.

      When in cluster mode, all keys in keys must map to the same hash slot.

      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'.

      Parameters

      • key: GlideString

        The key of the sorted set.

      • minLex: Boundary<GlideString>

        The minimum lex to count from. Can be negative infinity, or a specific lex and inclusivity.

      • maxLex: Boundary<GlideString>

        The maximum lex to count up to. Can be positive infinity, or a specific lex and inclusivity.

      Returns Promise<number>

      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.

      const result = await client.zlexcount("my_sorted_set", {value: "c"}, InfBoundary.PositiveInfinity);
      console.log(result);
      // Output: 2
      // Indicates that there are 2 members with lex scores between `c` (inclusive) and positive infinity in the sorted set `my_sorted_set`.
      const result = await client.zlexcount("my_sorted_set", {value: "c"}, {value: "k", isInclusive: false});
      console.log(result);
      // Output: 1
      // Indicates that there is one member with a lex score between `c` (inclusive) and `k` (exclusive) in the sorted set `my_sorted_set`.
    • Pops member-score pairs from the first non-empty sorted set, with the given keys being checked in the order they are provided.

      Parameters

      • keys: GlideString[]

        The keys of the sorted sets.

      • modifier: ScoreFilter

        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:

        • (Optional) count: the maximum number of popped elements. If not specified, pops one member.
        • (Optional) decoder: see DecoderOption.

      Returns Promise<[GlideString, SortedSetDataType] | null>

      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.

      When in cluster mode, all keys must map to the same hash slot.

      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.

      Parameters

      Returns Promise<(number | null)[]>

      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.

      Since Valkey version 6.2.0.

      const result = await client.zmscore("zset1", ["member1", "non_existent_member", "member2"]);
      console.log(result); // Output: [1.0, null, 2.0]
      // `member1` has a score of 1.0, `non_existent_member` does not exist in the sorted set, and `member2` has a score of 2.0.
    • 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.

      Parameters

      • key: GlideString

        The key of the sorted set.

      • Optionaloptions: { count?: number } & DecoderOption

        (Optional) Additional parameters:

        • (Optional) count: the maximum number of popped elements. If not specified, pops one member.
        • (Optional) decoder: see DecoderOption.

      Returns Promise<SortedSetDataType>

      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.

      // 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.

      Parameters

      • key: GlideString

        The key of the sorted set.

      • Optionaloptions: { count?: number } & DecoderOption

        (Optional) Additional parameters:

        • (Optional) count: the maximum number of popped elements. If not specified, pops one member.
        • (Optional) decoder: see DecoderOption.

      Returns Promise<SortedSetDataType>

      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.

      // 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.

      Parameters

      Returns Promise<GlideString | null>

      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.

      const payload1 = await client.zrandmember("mySortedSet");
      console.log(payload1);
      // Output: "Glide"
      // A random member from the set
      const payload2 = await client.zrandmember("nonExistingSortedSet");
      console.log(payload2);
      // Output: null
      // Since the sorted set does not exist.
    • Returns random members from the sorted set stored at key.

      Parameters

      • key: GlideString
      • count: number

        The number of members to return. If count is positive, returns unique members. If negative, allows for duplicates.

      • Optionaloptions: DecoderOption

        (Optional) See DecoderOption.

      Returns Promise<GlideString[]>

      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.

      const payload1 = await client.zrandmemberWithCount("mySortedSet", -3);
      console.log(payload1);
      // Output: ["Glide", "GLIDE", "node"]
      // Returns 3 random members from the sorted set, with duplicates allowed.
      const payload2 = await client.zrandmemberWithCount("nonExistingKey", 3);
      console.log(payload1);
      // Output: []
      // Since the sorted set does not exist.
    • Returns random members with scores from the sorted set stored at key.

      Parameters

      • key: GlideString
      • count: number

        The number of members to return. If count is positive, returns unique members. If negative, allows for duplicates.

      • Optionaloptions: DecoderOption

        (Optional) See DecoderOption.

      Returns Promise<KeyWeight[]>

      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.

      const payload1 = await client.zrandmemberWithCountWithScore("mySortedSet", -3);
      console.log(payload1);
      // Output: [["Glide", 1.0], ["GLIDE", 1.0], ["node", 2.0]]
      // Returns 3 random members with scores, with duplicates allowed.
      const payload2 = await client.zrandmemberWithCountWithScore("nonExistingKey", 3);
      console.log(payload1);
      // Output: []
      // Since the sorted set does not exist.
    • 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.

      Parameters

      • key: GlideString

        The key of the sorted set.

      • rangeQuery: RangeByScore | RangeByLex | RangeByIndex

        The range query object representing the type of range query to perform.

      • Optionaloptions: { reverse?: boolean } & DecoderOption

        (Optional) Additional parameters:

        • (Optional) reverse: if true, reverses the sorted set, with index 0 as the element with the highest score.
        • (Optional) decoder: see DecoderOption.

      Returns Promise<GlideString[]>

      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.

      // 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.

      Parameters

      • destination: GlideString

        The key for the destination sorted set.

      • source: GlideString

        The key of the source sorted set.

      • rangeQuery: RangeByScore | RangeByLex | RangeByIndex

        The range query object representing the type of range query to perform.

      • reverse: boolean = false

        If true, reverses the sorted set, with index 0 as the element with the highest score.

      Returns Promise<number>

      The number of elements in the resulting sorted set.

      When in cluster mode, destination and source must map to the same hash slot.

      // 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.

      Parameters

      • key: GlideString

        The key of the sorted set.

      • rangeQuery: RangeByScore | RangeByIndex

        The range query object representing the type of range query to perform.

      • Optionaloptions: { reverse?: boolean } & DecoderOption

        (Optional) Additional parameters:

        • (Optional) reverse: if true, reverses the sorted set, with index 0 as the element with the highest score.
        • (Optional) decoder: see DecoderOption.

      Returns Promise<SortedSetDataType>

      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.

      // 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.

      Parameters

      Returns Promise<number | null>

      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.

      // Example usage of zrank method to retrieve the rank of a member in a sorted set
      const result = await client.zrank("my_sorted_set", "member2");
      console.log(result);
      // Output: 1
      // Indicates that `member2` has the second-lowest score in the sorted set `my_sorted_set`.
      // Example usage of zrank method with a non-existing member
      const result = await client.zrank("my_sorted_set", "non_existing_member");
      console.log(result);
      // Output: null
      // Indicates that `non_existing_member` is not present in the sorted set `my_sorted_set`.
    • Returns the rank of member in the sorted set stored at key with its score, where scores are ordered from the lowest to highest.

      Parameters

      Returns Promise<[number, number] | null>

      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.

      Since Valkey version 7.2.0.

      // 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`.
      // Example usage of zrank_withscore method with a non-existing member
      const result = await client.zrank_withscore("my_sorted_set", "non_existing_member");
      console.log(result);
      // Output: null
      // Indicates that `non_existing_member` is not present 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.

      Parameters

      • key: GlideString

        The key of the sorted set.

      • members: GlideString[]

        A list of members to remove from the sorted set.

      Returns Promise<number>

      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.

      // Example usage of the zrem function to remove members from a sorted set
      const result = await client.zrem("my_sorted_set", ["member1", "member2"]);
      console.log(result);
      // Output: 2
      // Indicates that two members have been removed from the sorted set `my_sorted_set`.
      // Example usage of the zrem function when the sorted set does not exist
      const result = await client.zrem("non_existing_sorted_set", ["member1", "member2"]);
      console.log(result);
      // Output: 0
      // Indicates that no members were removed as the sorted set `non_existing_sorted_set` does not exist.
    • Removes all elements in the sorted set stored at key with lexicographical order between minLex and maxLex.

      Parameters

      • key: GlideString

        The key of the sorted set.

      • minLex: Boundary<GlideString>

        The minimum lex to count from. Can be negative infinity, or a specific lex and inclusivity.

      • maxLex: Boundary<GlideString>

        The maximum lex to count up to. Can be positive infinity, or a specific lex and inclusivity.

      Returns Promise<number>

      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.

      // 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`.
      // Example usage of zremRangeByLex method when the sorted set does not exist
      const result = await client.zremRangeByLex("non_existing_sorted_set", InfBoundary.NegativeInfinity, { value: "e" });
      console.log(result);
      // Output: 0
      // Indicates that no elements were removed.
    • 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.

      Parameters

      • key: GlideString

        The key of the sorted set.

      • start: number

        The starting point of the range.

      • end: number

        The end of the range.

      Returns Promise<number>

      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.

      // Example usage of zremRangeByRank method
      const result = await client.zremRangeByRank("my_sorted_set", 0, 2);
      console.log(result);
      // Output: 3
      // Indicates that three elements have been removed from the sorted set `my_sorted_set` between ranks 0 and 2.
    • Removes all elements in the sorted set stored at key with a score between minScore and maxScore.

      Parameters

      • key: GlideString

        The key of the sorted set.

      • minScore: Boundary<number>

        The minimum score to remove from. Can be negative infinity, or specific score and inclusivity.

      • maxScore: Boundary<number>

        The maximum score to remove to. Can be positive infinity, or specific score and inclusivity.

      Returns Promise<number>

      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.

      // 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.

      Parameters

      Returns Promise<number | null>

      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.

      const result = await client.zrevrank("my_sorted_set", "member2");
      console.log(result);
      // Output: 1
      // Indicates that `member2` has the second-highest score in the sorted set `my_sorted_set`.
    • 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.

      Parameters

      Returns Promise<[number, number] | null>

      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.

      Since Valkey version 7.2.0.

      const result = await client.zrevankWithScore("my_sorted_set", "member2");
      console.log(result);
      // Output: [1, 6.0]
      // Indicates that `member2` with score 6.0 has the second-highest score in the sorted set `my_sorted_set`.
    • Iterates incrementally over a sorted set.

      Parameters

      • key: GlideString

        The key of the sorted set.

      • cursor: string

        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?: boolean

          If true, the scores are not included in the results. Supported from Valkey 8.0.0 and above.

      Returns Promise<[string, GlideString[]]>

      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.

      // 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.

      Parameters

      Returns Promise<number | null>

      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.

      // 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.
      // Example usage of the zscore method when the member does not exist in the sorted set
      const result = await client.zscore("my_sorted_set", "non_existing_member");
      console.log(result);
      // Output: null
      // Example usage of the zscore method with non existimng key
      const result = await client.zscore("non_existing_set", "member");
      console.log(result);
      // Output: null
    • 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.

      Parameters

      Returns Promise<GlideString[]>

      The resulting array of union elements.

      When in cluster mode, all keys in keys must map to the same hash slot.

      await client.zadd("key1", {"member1": 10.5, "member2": 8.2});
      await client.zadd("key2", {"member1": 9.5});
      const result = await client.zunion(["key1", "key2"]);
      console.log(result);
      // Output: ['member1', 'member2']
      // Union elements from sets stored at keys `key1` and `key2`.
    • 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.

      Parameters

      • destination: GlideString

        The key of the destination sorted set.

      • keys: GlideString[] | KeyWeight[]

        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:

        • (Optional) aggregationType: the aggregation strategy to apply when combining the scores of elements. See AggregationType. If aggregationType is not specified, defaults to AggregationType.SUM.

      Returns Promise<number>

      The number of elements in the resulting sorted set stored at destination.

      When in cluster mode, destination and all keys in keys both must map to the same hash slot.

      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.

      Parameters

      • keys: GlideString[] | KeyWeight[]

        The keys of the sorted sets with possible formats:

        • string[] - for keys only.
        • KeyWeight[] - for weighted keys with score multipliers.
      • Optionaloptions: { aggregationType?: AggregationType } & DecoderOption

        (Optional) Additional parameters:

        • (Optional) aggregationType: the aggregation strategy to apply when combining the scores of elements. If aggregationType is not specified, defaults to AggregationType.SUM. See AggregationType.
        • (Optional) decoder: see DecoderOption.

      Returns Promise<SortedSetDataType>

      A list of elements and their scores representing the intersection of the sorted sets.

      When in cluster mode, all keys in keys must map to the same hash slot.

      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.
    • Creates a new GlideClient instance and establishes a connection to a standalone Valkey server.

      Parameters

      • options: GlideClientConfiguration

        The configuration options for the client, including server addresses, authentication credentials, TLS settings, database selection, reconnection strategy, and Pub/Sub subscriptions.

      Returns Promise<GlideClient>

      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}`);
      },
      },
      });
    • Internal

      Parameters

      • path: string

      Returns Promise<Socket>