Documentation
¶
Index ¶
- Constants
- Variables
- func DefaultSpanFromContext(ctx context.Context) uint64
- func ErrorsToString(errors []error) string
- func GoError(cErrorType uint32, errorMessage string) error
- func IsError(val any) error
- func WithSpan(ctx context.Context, spanPtr uint64) context.Context
- type BatchError
- type Client
- func (client *Client) AclCat(ctx context.Context) ([]string, error)
- func (client *Client) AclCatWithCategory(ctx context.Context, category string) ([]string, error)
- func (client *Client) AclDelUser(ctx context.Context, usernames []string) (int64, error)
- func (client *Client) AclDryRun(ctx context.Context, username string, command string, args []string) (string, error)
- func (client *Client) AclGenPass(ctx context.Context) (string, error)
- func (client *Client) AclGenPassWithBits(ctx context.Context, bits int64) (string, error)
- func (client *Client) AclGetUser(ctx context.Context, username string) (any, error)
- func (client *Client) AclList(ctx context.Context) ([]string, error)
- func (client *Client) AclLoad(ctx context.Context) (string, error)
- func (client *Client) AclLog(ctx context.Context) ([]any, error)
- func (client *Client) AclLogReset(ctx context.Context) (string, error)
- func (client *Client) AclLogWithCount(ctx context.Context, count int64) ([]any, error)
- func (client *Client) AclSave(ctx context.Context) (string, error)
- func (client *Client) AclSetUser(ctx context.Context, username string, rules []string) (string, error)
- func (client *Client) AclUsers(ctx context.Context) ([]string, error)
- func (client *Client) AclWhoAmI(ctx context.Context) (string, error)
- func (client *Client) Append(ctx context.Context, key string, value string) (int64, error)
- func (client *Client) BLMPop(ctx context.Context, keys []string, listDirection constants.ListDirection, ...) ([]models.KeyValues, error)
- func (client *Client) BLMPopCount(ctx context.Context, keys []string, listDirection constants.ListDirection, ...) ([]models.KeyValues, error)
- func (client *Client) BLMove(ctx context.Context, source string, destination string, ...) (models.Result[string], error)
- func (client *Client) BLPop(ctx context.Context, keys []string, timeout time.Duration) ([]string, error)
- func (client *Client) BRPop(ctx context.Context, keys []string, timeout time.Duration) ([]string, error)
- func (client *Client) BZMPop(ctx context.Context, keys []string, scoreFilter constants.ScoreFilter, ...) (models.Result[models.KeyWithArrayOfMembersAndScores], error)
- func (client *Client) BZMPopWithOptions(ctx context.Context, keys []string, scoreFilter constants.ScoreFilter, ...) (models.Result[models.KeyWithArrayOfMembersAndScores], error)
- func (client *Client) BZPopMax(ctx context.Context, keys []string, timeout time.Duration) (models.Result[models.KeyWithMemberAndScore], error)
- func (client *Client) BZPopMin(ctx context.Context, keys []string, timeout time.Duration) (models.Result[models.KeyWithMemberAndScore], error)
- func (client *Client) BitCount(ctx context.Context, key string) (int64, error)
- func (client *Client) BitCountWithOptions(ctx context.Context, key string, opts options.BitCountOptions) (int64, error)
- func (client *Client) BitField(ctx context.Context, key string, subCommands []options.BitFieldSubCommands) ([]models.Result[int64], error)
- func (client *Client) BitFieldRO(ctx context.Context, key string, commands []options.BitFieldROCommands) ([]models.Result[int64], error)
- func (client *Client) BitOp(ctx context.Context, bitwiseOperation options.BitOpType, destination string, ...) (int64, error)
- func (client *Client) BitPos(ctx context.Context, key string, bit int64) (int64, error)
- func (client *Client) BitPosWithOptions(ctx context.Context, key string, bit int64, ...) (int64, error)
- func (client *Client) ClientGetName(ctx context.Context) (models.Result[string], error)
- func (client *Client) ClientId(ctx context.Context) (int64, error)
- func (client *Client) ClientSetName(ctx context.Context, connectionName string) (string, error)
- func (client *Client) Close()
- func (client *Client) ConfigGet(ctx context.Context, args []string) (map[string]string, error)
- func (client *Client) ConfigResetStat(ctx context.Context) (string, error)
- func (client *Client) ConfigRewrite(ctx context.Context) (string, error)
- func (client *Client) ConfigSet(ctx context.Context, parameters map[string]string) (string, error)
- func (client *Client) Copy(ctx context.Context, source string, destination string) (bool, error)
- func (client *Client) CopyWithOptions(ctx context.Context, source string, destination string, ...) (bool, error)
- func (client *Client) CustomCommand(ctx context.Context, args []string) (any, error)
- func (client *Client) DBSize(ctx context.Context) (int64, error)
- func (client *Client) Decr(ctx context.Context, key string) (int64, error)
- func (client *Client) DecrBy(ctx context.Context, key string, amount int64) (int64, error)
- func (client *Client) Del(ctx context.Context, keys []string) (int64, error)
- func (client *Client) Dump(ctx context.Context, key string) (models.Result[string], error)
- func (client *Client) Echo(ctx context.Context, message string) (models.Result[string], error)
- func (client *Client) Exec(ctx context.Context, batch pipeline.StandaloneBatch, raiseOnError bool) ([]any, error)
- func (client *Client) ExecWithOptions(ctx context.Context, batch pipeline.StandaloneBatch, raiseOnError bool, ...) ([]any, error)
- func (client *Client) Exists(ctx context.Context, keys []string) (int64, error)
- func (client *Client) Expire(ctx context.Context, key string, expireTime time.Duration) (bool, error)
- func (client *Client) ExpireAt(ctx context.Context, key string, expireTime time.Time) (bool, error)
- func (client *Client) ExpireAtWithOptions(ctx context.Context, key string, expireTime time.Time, ...) (bool, error)
- func (client *Client) ExpireTime(ctx context.Context, key string) (int64, error)
- func (client *Client) ExpireWithOptions(ctx context.Context, key string, expireTime time.Duration, ...) (bool, error)
- func (client *Client) FCall(ctx context.Context, function string) (any, error)
- func (client *Client) FCallReadOnly(ctx context.Context, function string) (any, error)
- func (client *Client) FCallReadOnlyWithKeysAndArgs(ctx context.Context, function string, keys []string, args []string) (any, error)
- func (client *Client) FCallWithKeysAndArgs(ctx context.Context, function string, keys []string, args []string) (any, error)
- func (client *Client) FlushAll(ctx context.Context) (string, error)
- func (client *Client) FlushAllWithOptions(ctx context.Context, mode options.FlushMode) (string, error)
- func (client *Client) FlushDB(ctx context.Context) (string, error)
- func (client *Client) FlushDBWithOptions(ctx context.Context, mode options.FlushMode) (string, error)
- func (client *Client) FunctionDelete(ctx context.Context, libName string) (string, error)
- func (client *Client) FunctionDump(ctx context.Context) (string, error)
- func (client *Client) FunctionFlush(ctx context.Context) (string, error)
- func (client *Client) FunctionFlushAsync(ctx context.Context) (string, error)
- func (client *Client) FunctionFlushSync(ctx context.Context) (string, error)
- func (client *Client) FunctionKill(ctx context.Context) (string, error)
- func (client *Client) FunctionList(ctx context.Context, query models.FunctionListQuery) ([]models.LibraryInfo, error)
- func (client *Client) FunctionLoad(ctx context.Context, libraryCode string, replace bool) (string, error)
- func (client *Client) FunctionRestore(ctx context.Context, payload string) (string, error)
- func (client *Client) FunctionRestoreWithPolicy(ctx context.Context, payload string, policy constants.FunctionRestorePolicy) (string, error)
- func (client *Client) FunctionStats(ctx context.Context) (map[string]models.FunctionStatsResult, error)
- func (client *Client) GeoAdd(ctx context.Context, key string, ...) (int64, error)
- func (client *Client) GeoAddWithOptions(ctx context.Context, key string, ...) (int64, error)
- func (client *Client) GeoDist(ctx context.Context, key string, member1 string, member2 string) (models.Result[float64], error)
- func (client *Client) GeoDistWithUnit(ctx context.Context, key string, member1 string, member2 string, ...) (models.Result[float64], error)
- func (client *Client) GeoHash(ctx context.Context, key string, members []string) ([]models.Result[string], error)
- func (client *Client) GeoPos(ctx context.Context, key string, members []string) ([][]float64, error)
- func (client *Client) GeoSearch(ctx context.Context, key string, searchFrom options.GeoSearchOrigin, ...) ([]string, error)
- func (client *Client) GeoSearchStore(ctx context.Context, destinationKey string, sourceKey string, ...) (int64, error)
- func (client *Client) GeoSearchStoreWithFullOptions(ctx context.Context, destinationKey string, sourceKey string, ...) (int64, error)
- func (client *Client) GeoSearchStoreWithInfoOptions(ctx context.Context, destinationKey string, sourceKey string, ...) (int64, error)
- func (client *Client) GeoSearchStoreWithResultOptions(ctx context.Context, destinationKey string, sourceKey string, ...) (int64, error)
- func (client *Client) GeoSearchWithFullOptions(ctx context.Context, key string, searchFrom options.GeoSearchOrigin, ...) ([]options.Location, error)
- func (client *Client) GeoSearchWithInfoOptions(ctx context.Context, key string, searchFrom options.GeoSearchOrigin, ...) ([]options.Location, error)
- func (client *Client) GeoSearchWithResultOptions(ctx context.Context, key string, searchFrom options.GeoSearchOrigin, ...) ([]string, error)
- func (client *Client) Get(ctx context.Context, key string) (models.Result[string], error)
- func (client *Client) GetBit(ctx context.Context, key string, offset int64) (int64, error)
- func (client *Client) GetDel(ctx context.Context, key string) (models.Result[string], error)
- func (client *Client) GetEx(ctx context.Context, key string) (models.Result[string], error)
- func (client *Client) GetExWithOptions(ctx context.Context, key string, options options.GetExOptions) (models.Result[string], error)
- func (client *Client) GetQueue() (*PubSubMessageQueue, error)
- func (client *Client) GetRange(ctx context.Context, key string, start int, end int) (string, error)
- func (client *Client) GetStatistics() map[string]uint64
- func (client *Client) GetSubscriptions(ctx context.Context) (*models.PubSubState, error)
- func (client *Client) HDel(ctx context.Context, key string, fields []string) (int64, error)
- func (client *Client) HExists(ctx context.Context, key string, field string) (bool, error)
- func (client *Client) HExpire(ctx context.Context, key string, expireTime time.Duration, fields []string, ...) ([]int64, error)
- func (client *Client) HExpireAt(ctx context.Context, key string, expireTime time.Time, fields []string, ...) ([]int64, error)
- func (client *Client) HExpireTime(ctx context.Context, key string, fields []string) ([]int64, error)
- func (client *Client) HGet(ctx context.Context, key string, field string) (models.Result[string], error)
- func (client *Client) HGetAll(ctx context.Context, key string) (map[string]string, error)
- func (client *Client) HGetEx(ctx context.Context, key string, fields []string, opts options.HGetExOptions) ([]models.Result[string], error)
- func (client *Client) HIncrBy(ctx context.Context, key string, field string, increment int64) (int64, error)
- func (client *Client) HIncrByFloat(ctx context.Context, key string, field string, increment float64) (float64, error)
- func (client *Client) HKeys(ctx context.Context, key string) ([]string, error)
- func (client *Client) HLen(ctx context.Context, key string) (int64, error)
- func (client *Client) HMGet(ctx context.Context, key string, fields []string) ([]models.Result[string], error)
- func (client *Client) HPExpire(ctx context.Context, key string, expireTime time.Duration, fields []string, ...) ([]int64, error)
- func (client *Client) HPExpireAt(ctx context.Context, key string, expireTime time.Time, fields []string, ...) ([]int64, error)
- func (client *Client) HPExpireTime(ctx context.Context, key string, fields []string) ([]int64, error)
- func (client *Client) HPTtl(ctx context.Context, key string, fields []string) ([]int64, error)
- func (client *Client) HPersist(ctx context.Context, key string, fields []string) ([]int64, error)
- func (client *Client) HRandField(ctx context.Context, key string) (models.Result[string], error)
- func (client *Client) HRandFieldWithCount(ctx context.Context, key string, count int64) ([]string, error)
- func (client *Client) HRandFieldWithCountWithValues(ctx context.Context, key string, count int64) ([][]string, error)
- func (client *Client) HScan(ctx context.Context, key string, cursor models.Cursor) (models.ScanResult, error)
- func (client *Client) HScanWithOptions(ctx context.Context, key string, cursor models.Cursor, ...) (models.ScanResult, error)
- func (client *Client) HSet(ctx context.Context, key string, values map[string]string) (int64, error)
- func (client *Client) HSetEx(ctx context.Context, key string, fieldsAndValues map[string]string, ...) (int64, error)
- func (client *Client) HSetNX(ctx context.Context, key string, field string, value string) (bool, error)
- func (client *Client) HStrLen(ctx context.Context, key string, field string) (int64, error)
- func (client *Client) HTtl(ctx context.Context, key string, fields []string) ([]int64, error)
- func (client *Client) HVals(ctx context.Context, key string) ([]string, error)
- func (client *Client) Incr(ctx context.Context, key string) (int64, error)
- func (client *Client) IncrBy(ctx context.Context, key string, amount int64) (int64, error)
- func (client *Client) IncrByFloat(ctx context.Context, key string, amount float64) (float64, error)
- func (client *Client) Info(ctx context.Context) (string, error)
- func (client *Client) InfoWithOptions(ctx context.Context, options options.InfoOptions) (string, error)
- func (client *Client) InvokeScript(ctx context.Context, script options.Script) (any, error)
- func (client *Client) InvokeScriptWithOptions(ctx context.Context, script options.Script, ...) (any, error)
- func (client *Client) LCS(ctx context.Context, key1 string, key2 string) (*models.LCSMatch, error)
- func (client *Client) LCSLen(ctx context.Context, key1, key2 string) (*models.LCSMatch, error)
- func (client *Client) LCSWithOptions(ctx context.Context, key1, key2 string, opts options.LCSIdxOptions) (*models.LCSMatch, error)
- func (client *Client) LIndex(ctx context.Context, key string, index int64) (models.Result[string], error)
- func (client *Client) LInsert(ctx context.Context, key string, insertPosition constants.InsertPosition, ...) (int64, error)
- func (client *Client) LLen(ctx context.Context, key string) (int64, error)
- func (client *Client) LMPop(ctx context.Context, keys []string, listDirection constants.ListDirection) ([]models.KeyValues, error)
- func (client *Client) LMPopCount(ctx context.Context, keys []string, listDirection constants.ListDirection, ...) ([]models.KeyValues, error)
- func (client *Client) LMove(ctx context.Context, source string, destination string, ...) (models.Result[string], error)
- func (client *Client) LPop(ctx context.Context, key string) (models.Result[string], error)
- func (client *Client) LPopCount(ctx context.Context, key string, count int64) ([]string, error)
- func (client *Client) LPos(ctx context.Context, key string, element string) (models.Result[int64], error)
- func (client *Client) LPosCount(ctx context.Context, key string, element string, count int64) ([]int64, error)
- func (client *Client) LPosCountWithOptions(ctx context.Context, key string, element string, count int64, ...) ([]int64, error)
- func (client *Client) LPosWithOptions(ctx context.Context, key string, element string, options options.LPosOptions) (models.Result[int64], error)
- func (client *Client) LPush(ctx context.Context, key string, elements []string) (int64, error)
- func (client *Client) LPushX(ctx context.Context, key string, elements []string) (int64, error)
- func (client *Client) LRange(ctx context.Context, key string, start int64, end int64) ([]string, error)
- func (client *Client) LRem(ctx context.Context, key string, count int64, element string) (int64, error)
- func (client *Client) LSet(ctx context.Context, key string, index int64, element string) (string, error)
- func (client *Client) LTrim(ctx context.Context, key string, start int64, end int64) (string, error)
- func (client *Client) LastSave(ctx context.Context) (int64, error)
- func (client *Client) Lolwut(ctx context.Context) (string, error)
- func (client *Client) LolwutWithOptions(ctx context.Context, opts options.LolwutOptions) (string, error)
- func (client *Client) MGet(ctx context.Context, keys []string) ([]models.Result[string], error)
- func (client *Client) MSet(ctx context.Context, keyValueMap map[string]string) (string, error)
- func (client *Client) MSetNX(ctx context.Context, keyValueMap map[string]string) (bool, error)
- func (client *Client) Move(ctx context.Context, key string, dbIndex int64) (bool, error)
- func (client *Client) ObjectEncoding(ctx context.Context, key string) (models.Result[string], error)
- func (client *Client) ObjectFreq(ctx context.Context, key string) (models.Result[int64], error)
- func (client *Client) ObjectIdleTime(ctx context.Context, key string) (models.Result[int64], error)
- func (client *Client) ObjectRefCount(ctx context.Context, key string) (models.Result[int64], error)
- func (client *Client) PExpire(ctx context.Context, key string, expireTime time.Duration) (bool, error)
- func (client *Client) PExpireAt(ctx context.Context, key string, expireTime time.Time) (bool, error)
- func (client *Client) PExpireAtWithOptions(ctx context.Context, key string, expireTime time.Time, ...) (bool, error)
- func (client *Client) PExpireTime(ctx context.Context, key string) (int64, error)
- func (client *Client) PExpireWithOptions(ctx context.Context, key string, expireTime time.Duration, ...) (bool, error)
- func (client *Client) PSubscribe(ctx context.Context, patterns []string, timeoutMs int) error
- func (client *Client) PSubscribeBlocking(ctx context.Context, patterns []string, timeoutMs int) error
- func (client *Client) PSubscribeLazy(ctx context.Context, patterns []string) error
- func (client *Client) PTTL(ctx context.Context, key string) (int64, error)
- func (client *Client) PUnsubscribe(ctx context.Context, patterns []string, timeoutMs int) error
- func (client *Client) PUnsubscribeLazy(ctx context.Context, patterns []string) error
- func (client *Client) Persist(ctx context.Context, key string) (bool, error)
- func (client *Client) PfAdd(ctx context.Context, key string, elements []string) (bool, error)
- func (client *Client) PfCount(ctx context.Context, keys []string) (int64, error)
- func (client *Client) PfMerge(ctx context.Context, destination string, sourceKeys []string) (string, error)
- func (client *Client) Ping(ctx context.Context) (string, error)
- func (client *Client) PingWithOptions(ctx context.Context, pingOptions options.PingOptions) (string, error)
- func (client *Client) PubSubChannels(ctx context.Context) ([]string, error)
- func (client *Client) PubSubChannelsWithPattern(ctx context.Context, pattern string) ([]string, error)
- func (client *Client) PubSubNumPat(ctx context.Context) (int64, error)
- func (client *Client) PubSubNumSub(ctx context.Context, channels ...string) (map[string]int64, error)
- func (client *Client) Publish(ctx context.Context, channel string, message string) (int64, error)
- func (client *Client) RPop(ctx context.Context, key string) (models.Result[string], error)
- func (client *Client) RPopCount(ctx context.Context, key string, count int64) ([]string, error)
- func (client *Client) RPush(ctx context.Context, key string, elements []string) (int64, error)
- func (client *Client) RPushX(ctx context.Context, key string, elements []string) (int64, error)
- func (client *Client) RandomKey(ctx context.Context) (models.Result[string], error)
- func (client *Client) RefreshIamToken(ctx context.Context) (string, error)
- func (client *Client) Rename(ctx context.Context, key string, newKey string) (string, error)
- func (client *Client) RenameNX(ctx context.Context, key string, newKey string) (bool, error)
- func (client *Client) ResetConnectionPassword(ctx context.Context) (string, error)
- func (client *Client) Restore(ctx context.Context, key string, ttl time.Duration, value string) (string, error)
- func (client *Client) RestoreWithOptions(ctx context.Context, key string, ttl time.Duration, value string, ...) (string, error)
- func (client *Client) SAdd(ctx context.Context, key string, members []string) (int64, error)
- func (client *Client) SCard(ctx context.Context, key string) (int64, error)
- func (client *Client) SDiff(ctx context.Context, keys []string) (map[string]struct{}, error)
- func (client *Client) SDiffStore(ctx context.Context, destination string, keys []string) (int64, error)
- func (client *Client) SInter(ctx context.Context, keys []string) (map[string]struct{}, error)
- func (client *Client) SInterCard(ctx context.Context, keys []string) (int64, error)
- func (client *Client) SInterCardLimit(ctx context.Context, keys []string, limit int64) (int64, error)
- func (client *Client) SInterStore(ctx context.Context, destination string, keys []string) (int64, error)
- func (client *Client) SIsMember(ctx context.Context, key string, member string) (bool, error)
- func (client *Client) SMIsMember(ctx context.Context, key string, members []string) ([]bool, error)
- func (client *Client) SMembers(ctx context.Context, key string) (map[string]struct{}, error)
- func (client *Client) SMove(ctx context.Context, source string, destination string, member string) (bool, error)
- func (client *Client) SPop(ctx context.Context, key string) (models.Result[string], error)
- func (client *Client) SPopCount(ctx context.Context, key string, count int64) (map[string]struct{}, error)
- func (client *Client) SRandMember(ctx context.Context, key string) (models.Result[string], error)
- func (client *Client) SRandMemberCount(ctx context.Context, key string, count int64) ([]string, error)
- func (client *Client) SRem(ctx context.Context, key string, members []string) (int64, error)
- func (client *Client) SScan(ctx context.Context, key string, cursor models.Cursor) (models.ScanResult, error)
- func (client *Client) SScanWithOptions(ctx context.Context, key string, cursor models.Cursor, ...) (models.ScanResult, error)
- func (client *Client) SUnion(ctx context.Context, keys []string) (map[string]struct{}, error)
- func (client *Client) SUnionStore(ctx context.Context, destination string, keys []string) (int64, error)
- func (client *Client) Scan(ctx context.Context, cursor models.Cursor) (models.ScanResult, error)
- func (client *Client) ScanWithOptions(ctx context.Context, cursor models.Cursor, scanOptions options.ScanOptions) (models.ScanResult, error)
- func (client *Client) ScriptExists(ctx context.Context, sha1s []string) ([]bool, error)
- func (client *Client) ScriptFlush(ctx context.Context) (string, error)
- func (client *Client) ScriptFlushWithMode(ctx context.Context, mode options.FlushMode) (string, error)
- func (client *Client) ScriptKill(ctx context.Context) (string, error)
- func (client *Client) ScriptShow(ctx context.Context, sha1 string) (string, error)
- func (client *Client) Select(ctx context.Context, index int64) (string, error)
- func (client *Client) Set(ctx context.Context, key string, value string) (string, error)
- func (client *Client) SetBit(ctx context.Context, key string, offset int64, value int64) (int64, error)
- func (client *Client) SetRange(ctx context.Context, key string, offset int, value string) (int64, error)
- func (client *Client) SetWithOptions(ctx context.Context, key string, value string, options options.SetOptions) (models.Result[string], error)
- func (client *Client) Sort(ctx context.Context, key string) ([]models.Result[string], error)
- func (client *Client) SortReadOnly(ctx context.Context, key string) ([]models.Result[string], error)
- func (client *Client) SortReadOnlyWithOptions(ctx context.Context, key string, options options.SortOptions) ([]models.Result[string], error)
- func (client *Client) SortStore(ctx context.Context, key string, destination string) (int64, error)
- func (client *Client) SortStoreWithOptions(ctx context.Context, key string, destination string, opts options.SortOptions) (int64, error)
- func (client *Client) SortWithOptions(ctx context.Context, key string, options options.SortOptions) ([]models.Result[string], error)
- func (client *Client) Strlen(ctx context.Context, key string) (int64, error)
- func (client *Client) Subscribe(ctx context.Context, channels []string, timeoutMs int) error
- func (client *Client) SubscribeLazy(ctx context.Context, channels []string) error
- func (client *Client) TTL(ctx context.Context, key string) (int64, error)
- func (client *Client) Time(ctx context.Context) ([]string, error)
- func (client *Client) Touch(ctx context.Context, keys []string) (int64, error)
- func (client *Client) Type(ctx context.Context, key string) (string, error)
- func (client *Client) Unlink(ctx context.Context, keys []string) (int64, error)
- func (client *Client) Unsubscribe(ctx context.Context, channels []string, timeoutMs int) error
- func (client *Client) UnsubscribeLazy(ctx context.Context, channels []string) error
- func (client *Client) Unwatch(ctx context.Context) (string, error)
- func (client *Client) UpdateConnectionPassword(ctx context.Context, password string, immediateAuth bool) (string, error)
- func (client *Client) Wait(ctx context.Context, numberOfReplicas int64, timeout time.Duration) (int64, error)
- func (client *Client) Watch(ctx context.Context, keys []string) (string, error)
- func (client *Client) XAck(ctx context.Context, key string, group string, ids []string) (int64, error)
- func (client *Client) XAdd(ctx context.Context, key string, values []models.FieldValue) (string, error)
- func (client *Client) XAddWithOptions(ctx context.Context, key string, values []models.FieldValue, ...) (models.Result[string], error)
- func (client *Client) XAutoClaim(ctx context.Context, key string, group string, consumer string, ...) (models.XAutoClaimResponse, error)
- func (client *Client) XAutoClaimJustId(ctx context.Context, key string, group string, consumer string, ...) (models.XAutoClaimJustIdResponse, error)
- func (client *Client) XAutoClaimJustIdWithOptions(ctx context.Context, key string, group string, consumer string, ...) (models.XAutoClaimJustIdResponse, error)
- func (client *Client) XAutoClaimWithOptions(ctx context.Context, key string, group string, consumer string, ...) (models.XAutoClaimResponse, error)
- func (client *Client) XClaim(ctx context.Context, key string, group string, consumer string, ...) (map[string]models.XClaimResponse, error)
- func (client *Client) XClaimJustId(ctx context.Context, key string, group string, consumer string, ...) ([]string, error)
- func (client *Client) XClaimJustIdWithOptions(ctx context.Context, key string, group string, consumer string, ...) ([]string, error)
- func (client *Client) XClaimWithOptions(ctx context.Context, key string, group string, consumer string, ...) (map[string]models.XClaimResponse, error)
- func (client *Client) XDel(ctx context.Context, key string, ids []string) (int64, error)
- func (client *Client) XGroupCreate(ctx context.Context, key string, group string, id string) (string, error)
- func (client *Client) XGroupCreateConsumer(ctx context.Context, key string, group string, consumer string) (bool, error)
- func (client *Client) XGroupCreateWithOptions(ctx context.Context, key string, group string, id string, ...) (string, error)
- func (client *Client) XGroupDelConsumer(ctx context.Context, key string, group string, consumer string) (int64, error)
- func (client *Client) XGroupDestroy(ctx context.Context, key string, group string) (bool, error)
- func (client *Client) XGroupSetId(ctx context.Context, key string, group string, id string) (string, error)
- func (client *Client) XGroupSetIdWithOptions(ctx context.Context, key string, group string, id string, ...) (string, error)
- func (client *Client) XInfoConsumers(ctx context.Context, key string, group string) ([]models.XInfoConsumerInfo, error)
- func (client *Client) XInfoGroups(ctx context.Context, key string) ([]models.XInfoGroupInfo, error)
- func (client *Client) XInfoStream(ctx context.Context, key string) (models.XInfoStreamResponse, error)
- func (client *Client) XInfoStreamFullWithOptions(ctx context.Context, key string, opts options.XInfoStreamOptions) (models.XInfoStreamFullOptionsResponse, error)
- func (client *Client) XLen(ctx context.Context, key string) (int64, error)
- func (client *Client) XPending(ctx context.Context, key string, group string) (models.XPendingSummary, error)
- func (client *Client) XPendingWithOptions(ctx context.Context, key string, group string, opts options.XPendingOptions) ([]models.XPendingDetail, error)
- func (client *Client) XRange(ctx context.Context, key string, start options.StreamBoundary, ...) ([]models.StreamEntry, error)
- func (client *Client) XRangeWithOptions(ctx context.Context, key string, start options.StreamBoundary, ...) ([]models.StreamEntry, error)
- func (client *Client) XRead(ctx context.Context, keysAndIds map[string]string) (map[string]models.StreamResponse, error)
- func (client *Client) XReadGroup(ctx context.Context, group string, consumer string, ...) (map[string]models.StreamResponse, error)
- func (client *Client) XReadGroupWithOptions(ctx context.Context, group string, consumer string, ...) (map[string]models.StreamResponse, error)
- func (client *Client) XReadWithOptions(ctx context.Context, keysAndIds map[string]string, opts options.XReadOptions) (map[string]models.StreamResponse, error)
- func (client *Client) XRevRange(ctx context.Context, key string, start options.StreamBoundary, ...) ([]models.StreamEntry, error)
- func (client *Client) XRevRangeWithOptions(ctx context.Context, key string, start options.StreamBoundary, ...) ([]models.StreamEntry, error)
- func (client *Client) XTrim(ctx context.Context, key string, options options.XTrimOptions) (int64, error)
- func (client *Client) ZAdd(ctx context.Context, key string, membersScoreMap map[string]float64) (int64, error)
- func (client *Client) ZAddIncr(ctx context.Context, key string, member string, increment float64) (float64, error)
- func (client *Client) ZAddIncrWithOptions(ctx context.Context, key string, member string, increment float64, ...) (models.Result[float64], error)
- func (client *Client) ZAddWithOptions(ctx context.Context, key string, membersScoreMap map[string]float64, ...) (int64, error)
- func (client *Client) ZCard(ctx context.Context, key string) (int64, error)
- func (client *Client) ZCount(ctx context.Context, key string, rangeOptions options.ZCountRange) (int64, error)
- func (client *Client) ZDiff(ctx context.Context, keys []string) ([]string, error)
- func (client *Client) ZDiffStore(ctx context.Context, destination string, keys []string) (int64, error)
- func (client *Client) ZDiffWithScores(ctx context.Context, keys []string) ([]models.MemberAndScore, error)
- func (client *Client) ZIncrBy(ctx context.Context, key string, increment float64, member string) (float64, error)
- func (client *Client) ZInter(ctx context.Context, keys options.KeyArray) ([]string, error)
- func (client *Client) ZInterCard(ctx context.Context, keys []string) (int64, error)
- func (client *Client) ZInterCardWithOptions(ctx context.Context, keys []string, options options.ZInterCardOptions) (int64, error)
- func (client *Client) ZInterStore(ctx context.Context, destination string, ...) (int64, error)
- func (client *Client) ZInterStoreWithOptions(ctx context.Context, destination string, ...) (int64, error)
- func (client *Client) ZInterWithScores(ctx context.Context, keysOrWeightedKeys options.KeysOrWeightedKeys, ...) ([]models.MemberAndScore, error)
- func (client *Client) ZLexCount(ctx context.Context, key string, rangeQuery options.RangeByLex) (int64, error)
- func (client *Client) ZMPop(ctx context.Context, keys []string, scoreFilter constants.ScoreFilter) (models.Result[models.KeyWithArrayOfMembersAndScores], error)
- func (client *Client) ZMPopWithOptions(ctx context.Context, keys []string, scoreFilter constants.ScoreFilter, ...) (models.Result[models.KeyWithArrayOfMembersAndScores], error)
- func (client *Client) ZMScore(ctx context.Context, key string, members []string) ([]models.Result[float64], error)
- func (client *Client) ZPopMax(ctx context.Context, key string) (map[string]float64, error)
- func (client *Client) ZPopMaxWithOptions(ctx context.Context, key string, options options.ZPopOptions) (map[string]float64, error)
- func (client *Client) ZPopMin(ctx context.Context, key string) (map[string]float64, error)
- func (client *Client) ZPopMinWithOptions(ctx context.Context, key string, options options.ZPopOptions) (map[string]float64, error)
- func (client *Client) ZRandMember(ctx context.Context, key string) (models.Result[string], error)
- func (client *Client) ZRandMemberWithCount(ctx context.Context, key string, count int64) ([]string, error)
- func (client *Client) ZRandMemberWithCountWithScores(ctx context.Context, key string, count int64) ([]models.MemberAndScore, error)
- func (client *Client) ZRange(ctx context.Context, key string, rangeQuery options.ZRangeQuery) ([]string, error)
- func (client *Client) ZRangeStore(ctx context.Context, destination string, key string, ...) (int64, error)
- func (client *Client) ZRangeWithScores(ctx context.Context, key string, rangeQuery options.ZRangeQueryWithScores) ([]models.MemberAndScore, error)
- func (client *Client) ZRank(ctx context.Context, key string, member string) (models.Result[int64], error)
- func (client *Client) ZRankWithScore(ctx context.Context, key string, member string) (models.Result[models.RankAndScore], error)
- func (client *Client) ZRem(ctx context.Context, key string, members []string) (int64, error)
- func (client *Client) ZRemRangeByLex(ctx context.Context, key string, rangeQuery options.RangeByLex) (int64, error)
- func (client *Client) ZRemRangeByRank(ctx context.Context, key string, start int64, stop int64) (int64, error)
- func (client *Client) ZRemRangeByScore(ctx context.Context, key string, rangeQuery options.RangeByScore) (int64, error)
- func (client *Client) ZRevRank(ctx context.Context, key string, member string) (models.Result[int64], error)
- func (client *Client) ZRevRankWithScore(ctx context.Context, key string, member string) (models.Result[models.RankAndScore], error)
- func (client *Client) ZScan(ctx context.Context, key string, cursor models.Cursor) (models.ScanResult, error)
- func (client *Client) ZScanWithOptions(ctx context.Context, key string, cursor models.Cursor, ...) (models.ScanResult, error)
- func (client *Client) ZScore(ctx context.Context, key string, member string) (models.Result[float64], error)
- func (client *Client) ZUnion(ctx context.Context, keys options.KeyArray) ([]string, error)
- func (client *Client) ZUnionStore(ctx context.Context, destination string, ...) (int64, error)
- func (client *Client) ZUnionStoreWithOptions(ctx context.Context, destination string, ...) (int64, error)
- func (client *Client) ZUnionWithScores(ctx context.Context, keysOrWeightedKeys options.KeysOrWeightedKeys, ...) ([]models.MemberAndScore, error)
- type ClosingError
- type ClusterClient
- func (client *ClusterClient) AclCat(ctx context.Context) ([]string, error)
- func (client *ClusterClient) AclCatWithCategory(ctx context.Context, category string) ([]string, error)
- func (client *ClusterClient) AclDelUser(ctx context.Context, usernames []string) (int64, error)
- func (client *ClusterClient) AclDryRun(ctx context.Context, username string, command string, args []string) (string, error)
- func (client *ClusterClient) AclGenPass(ctx context.Context) (string, error)
- func (client *ClusterClient) AclGenPassWithBits(ctx context.Context, bits int64) (string, error)
- func (client *ClusterClient) AclGetUser(ctx context.Context, username string) (any, error)
- func (client *ClusterClient) AclList(ctx context.Context) ([]string, error)
- func (client *ClusterClient) AclLoad(ctx context.Context) (string, error)
- func (client *ClusterClient) AclLog(ctx context.Context) ([]any, error)
- func (client *ClusterClient) AclLogReset(ctx context.Context) (string, error)
- func (client *ClusterClient) AclLogWithCount(ctx context.Context, count int64) ([]any, error)
- func (client *ClusterClient) AclSave(ctx context.Context) (string, error)
- func (client *ClusterClient) AclSetUser(ctx context.Context, username string, rules []string) (string, error)
- func (client *ClusterClient) AclUsers(ctx context.Context) ([]string, error)
- func (client *ClusterClient) AclWhoAmI(ctx context.Context) (string, error)
- func (client *ClusterClient) Append(ctx context.Context, key string, value string) (int64, error)
- func (client *ClusterClient) BLMPop(ctx context.Context, keys []string, listDirection constants.ListDirection, ...) ([]models.KeyValues, error)
- func (client *ClusterClient) BLMPopCount(ctx context.Context, keys []string, listDirection constants.ListDirection, ...) ([]models.KeyValues, error)
- func (client *ClusterClient) BLMove(ctx context.Context, source string, destination string, ...) (models.Result[string], error)
- func (client *ClusterClient) BLPop(ctx context.Context, keys []string, timeout time.Duration) ([]string, error)
- func (client *ClusterClient) BRPop(ctx context.Context, keys []string, timeout time.Duration) ([]string, error)
- func (client *ClusterClient) BZMPop(ctx context.Context, keys []string, scoreFilter constants.ScoreFilter, ...) (models.Result[models.KeyWithArrayOfMembersAndScores], error)
- func (client *ClusterClient) BZMPopWithOptions(ctx context.Context, keys []string, scoreFilter constants.ScoreFilter, ...) (models.Result[models.KeyWithArrayOfMembersAndScores], error)
- func (client *ClusterClient) BZPopMax(ctx context.Context, keys []string, timeout time.Duration) (models.Result[models.KeyWithMemberAndScore], error)
- func (client *ClusterClient) BZPopMin(ctx context.Context, keys []string, timeout time.Duration) (models.Result[models.KeyWithMemberAndScore], error)
- func (client *ClusterClient) BitCount(ctx context.Context, key string) (int64, error)
- func (client *ClusterClient) BitCountWithOptions(ctx context.Context, key string, opts options.BitCountOptions) (int64, error)
- func (client *ClusterClient) BitField(ctx context.Context, key string, subCommands []options.BitFieldSubCommands) ([]models.Result[int64], error)
- func (client *ClusterClient) BitFieldRO(ctx context.Context, key string, commands []options.BitFieldROCommands) ([]models.Result[int64], error)
- func (client *ClusterClient) BitOp(ctx context.Context, bitwiseOperation options.BitOpType, destination string, ...) (int64, error)
- func (client *ClusterClient) BitPos(ctx context.Context, key string, bit int64) (int64, error)
- func (client *ClusterClient) BitPosWithOptions(ctx context.Context, key string, bit int64, ...) (int64, error)
- func (client *ClusterClient) ClientGetName(ctx context.Context) (models.Result[string], error)
- func (client *ClusterClient) ClientGetNameWithOptions(ctx context.Context, opts options.RouteOption) (models.ClusterValue[models.Result[string]], error)
- func (client *ClusterClient) ClientId(ctx context.Context) (models.ClusterValue[int64], error)
- func (client *ClusterClient) ClientIdWithOptions(ctx context.Context, opts options.RouteOption) (models.ClusterValue[int64], error)
- func (client *ClusterClient) ClientSetName(ctx context.Context, connectionName string) (string, error)
- func (client *ClusterClient) ClientSetNameWithOptions(ctx context.Context, connectionName string, opts options.RouteOption) (string, error)
- func (client *ClusterClient) Close()
- func (client *ClusterClient) ClusterCountKeysInSlot(ctx context.Context, slot int64) (int64, error)
- func (client *ClusterClient) ClusterGetKeysInSlot(ctx context.Context, slot int64, count int64) ([]string, error)
- func (client *ClusterClient) ClusterInfo(ctx context.Context) (string, error)
- func (client *ClusterClient) ClusterInfoWithRoute(ctx context.Context, route options.RouteOption) (models.ClusterValue[string], error)
- func (client *ClusterClient) ClusterKeySlot(ctx context.Context, key string) (int64, error)
- func (client *ClusterClient) ClusterLinks(ctx context.Context) ([]map[string]any, error)
- func (client *ClusterClient) ClusterLinksWithRoute(ctx context.Context, route options.RouteOption) (models.ClusterValue[[]map[string]any], error)
- func (client *ClusterClient) ClusterMyId(ctx context.Context) (string, error)
- func (client *ClusterClient) ClusterMyIdWithRoute(ctx context.Context, route options.RouteOption) (models.ClusterValue[string], error)
- func (client *ClusterClient) ClusterMyShardId(ctx context.Context) (string, error)
- func (client *ClusterClient) ClusterMyShardIdWithRoute(ctx context.Context, route options.RouteOption) (models.ClusterValue[string], error)
- func (client *ClusterClient) ClusterNodes(ctx context.Context) (string, error)
- func (client *ClusterClient) ClusterNodesWithRoute(ctx context.Context, route options.RouteOption) (models.ClusterValue[string], error)
- func (client *ClusterClient) ClusterShards(ctx context.Context) ([]map[string]any, error)
- func (client *ClusterClient) ClusterShardsWithRoute(ctx context.Context, route options.RouteOption) (models.ClusterValue[[]map[string]any], error)
- func (client *ClusterClient) ConfigGet(ctx context.Context, parameters []string) (map[string]string, error)
- func (client *ClusterClient) ConfigGetWithOptions(ctx context.Context, parameters []string, opts options.RouteOption) (models.ClusterValue[map[string]string], error)
- func (client *ClusterClient) ConfigResetStat(ctx context.Context) (string, error)
- func (client *ClusterClient) ConfigResetStatWithOptions(ctx context.Context, opts options.RouteOption) (string, error)
- func (client *ClusterClient) ConfigRewrite(ctx context.Context) (string, error)
- func (client *ClusterClient) ConfigRewriteWithOptions(ctx context.Context, opts options.RouteOption) (string, error)
- func (client *ClusterClient) ConfigSet(ctx context.Context, parameters map[string]string) (string, error)
- func (client *ClusterClient) ConfigSetWithOptions(ctx context.Context, parameters map[string]string, opts options.RouteOption) (string, error)
- func (client *ClusterClient) Copy(ctx context.Context, source string, destination string) (bool, error)
- func (client *ClusterClient) CopyWithOptions(ctx context.Context, source string, destination string, ...) (bool, error)
- func (client *ClusterClient) CustomCommand(ctx context.Context, args []string) (models.ClusterValue[any], error)
- func (client *ClusterClient) CustomCommandWithRoute(ctx context.Context, args []string, route config.Route) (models.ClusterValue[any], error)
- func (client *ClusterClient) DBSizeWithOptions(ctx context.Context, opts options.RouteOption) (int64, error)
- func (client *ClusterClient) Decr(ctx context.Context, key string) (int64, error)
- func (client *ClusterClient) DecrBy(ctx context.Context, key string, amount int64) (int64, error)
- func (client *ClusterClient) Del(ctx context.Context, keys []string) (int64, error)
- func (client *ClusterClient) Dump(ctx context.Context, key string) (models.Result[string], error)
- func (client *ClusterClient) Echo(ctx context.Context, message string) (models.Result[string], error)
- func (client *ClusterClient) EchoWithOptions(ctx context.Context, message string, opts options.RouteOption) (models.ClusterValue[string], error)
- func (client *ClusterClient) Exec(ctx context.Context, batch pipeline.ClusterBatch, raiseOnError bool) ([]any, error)
- func (client *ClusterClient) ExecWithOptions(ctx context.Context, batch pipeline.ClusterBatch, raiseOnError bool, ...) ([]any, error)
- func (client *ClusterClient) Exists(ctx context.Context, keys []string) (int64, error)
- func (client *ClusterClient) Expire(ctx context.Context, key string, expireTime time.Duration) (bool, error)
- func (client *ClusterClient) ExpireAt(ctx context.Context, key string, expireTime time.Time) (bool, error)
- func (client *ClusterClient) ExpireAtWithOptions(ctx context.Context, key string, expireTime time.Time, ...) (bool, error)
- func (client *ClusterClient) ExpireTime(ctx context.Context, key string) (int64, error)
- func (client *ClusterClient) ExpireWithOptions(ctx context.Context, key string, expireTime time.Duration, ...) (bool, error)
- func (client *ClusterClient) FCall(ctx context.Context, function string) (any, error)
- func (client *ClusterClient) FCallReadOnly(ctx context.Context, function string) (any, error)
- func (client *ClusterClient) FCallReadOnlyWithArgs(ctx context.Context, function string, args []string) (models.ClusterValue[any], error)
- func (client *ClusterClient) FCallReadOnlyWithArgsWithRoute(ctx context.Context, function string, args []string, route options.RouteOption) (models.ClusterValue[any], error)
- func (client *ClusterClient) FCallReadOnlyWithKeysAndArgs(ctx context.Context, function string, keys []string, args []string) (any, error)
- func (client *ClusterClient) FCallReadOnlyWithRoute(ctx context.Context, function string, route options.RouteOption) (models.ClusterValue[any], error)
- func (client *ClusterClient) FCallWithArgs(ctx context.Context, function string, args []string) (models.ClusterValue[any], error)
- func (client *ClusterClient) FCallWithArgsWithRoute(ctx context.Context, function string, args []string, route options.RouteOption) (models.ClusterValue[any], error)
- func (client *ClusterClient) FCallWithKeysAndArgs(ctx context.Context, function string, keys []string, args []string) (any, error)
- func (client *ClusterClient) FCallWithRoute(ctx context.Context, function string, route options.RouteOption) (models.ClusterValue[any], error)
- func (client *ClusterClient) FlushAll(ctx context.Context) (string, error)
- func (client *ClusterClient) FlushAllWithOptions(ctx context.Context, flushOptions options.FlushClusterOptions) (string, error)
- func (client *ClusterClient) FlushDB(ctx context.Context) (string, error)
- func (client *ClusterClient) FlushDBWithOptions(ctx context.Context, flushOptions options.FlushClusterOptions) (string, error)
- func (client *ClusterClient) FunctionDelete(ctx context.Context, libName string) (string, error)
- func (client *ClusterClient) FunctionDeleteWithRoute(ctx context.Context, libName string, route options.RouteOption) (string, error)
- func (client *ClusterClient) FunctionDump(ctx context.Context) (string, error)
- func (client *ClusterClient) FunctionDumpWithRoute(ctx context.Context, route config.Route) (models.ClusterValue[string], error)
- func (client *ClusterClient) FunctionFlush(ctx context.Context) (string, error)
- func (client *ClusterClient) FunctionFlushAsync(ctx context.Context) (string, error)
- func (client *ClusterClient) FunctionFlushAsyncWithRoute(ctx context.Context, route options.RouteOption) (string, error)
- func (client *ClusterClient) FunctionFlushSync(ctx context.Context) (string, error)
- func (client *ClusterClient) FunctionFlushSyncWithRoute(ctx context.Context, route options.RouteOption) (string, error)
- func (client *ClusterClient) FunctionFlushWithRoute(ctx context.Context, route options.RouteOption) (string, error)
- func (client *ClusterClient) FunctionKill(ctx context.Context) (string, error)
- func (client *ClusterClient) FunctionKillWithRoute(ctx context.Context, route options.RouteOption) (string, error)
- func (client *ClusterClient) FunctionList(ctx context.Context, query models.FunctionListQuery) ([]models.LibraryInfo, error)
- func (client *ClusterClient) FunctionListWithRoute(ctx context.Context, query models.FunctionListQuery, route options.RouteOption) (models.ClusterValue[[]models.LibraryInfo], error)
- func (client *ClusterClient) FunctionLoad(ctx context.Context, libraryCode string, replace bool) (string, error)
- func (client *ClusterClient) FunctionLoadWithRoute(ctx context.Context, libraryCode string, replace bool, ...) (string, error)
- func (client *ClusterClient) FunctionRestore(ctx context.Context, payload string) (string, error)
- func (client *ClusterClient) FunctionRestoreWithPolicy(ctx context.Context, payload string, policy constants.FunctionRestorePolicy) (string, error)
- func (client *ClusterClient) FunctionRestoreWithPolicyWithRoute(ctx context.Context, payload string, policy constants.FunctionRestorePolicy, ...) (string, error)
- func (client *ClusterClient) FunctionRestoreWithRoute(ctx context.Context, payload string, route config.Route) (string, error)
- func (client *ClusterClient) FunctionStats(ctx context.Context) (map[string]models.FunctionStatsResult, error)
- func (client *ClusterClient) FunctionStatsWithRoute(ctx context.Context, opts options.RouteOption) (models.ClusterValue[models.FunctionStatsResult], error)
- func (client *ClusterClient) GeoAdd(ctx context.Context, key string, ...) (int64, error)
- func (client *ClusterClient) GeoAddWithOptions(ctx context.Context, key string, ...) (int64, error)
- func (client *ClusterClient) GeoDist(ctx context.Context, key string, member1 string, member2 string) (models.Result[float64], error)
- func (client *ClusterClient) GeoDistWithUnit(ctx context.Context, key string, member1 string, member2 string, ...) (models.Result[float64], error)
- func (client *ClusterClient) GeoHash(ctx context.Context, key string, members []string) ([]models.Result[string], error)
- func (client *ClusterClient) GeoPos(ctx context.Context, key string, members []string) ([][]float64, error)
- func (client *ClusterClient) GeoSearch(ctx context.Context, key string, searchFrom options.GeoSearchOrigin, ...) ([]string, error)
- func (client *ClusterClient) GeoSearchStore(ctx context.Context, destinationKey string, sourceKey string, ...) (int64, error)
- func (client *ClusterClient) GeoSearchStoreWithFullOptions(ctx context.Context, destinationKey string, sourceKey string, ...) (int64, error)
- func (client *ClusterClient) GeoSearchStoreWithInfoOptions(ctx context.Context, destinationKey string, sourceKey string, ...) (int64, error)
- func (client *ClusterClient) GeoSearchStoreWithResultOptions(ctx context.Context, destinationKey string, sourceKey string, ...) (int64, error)
- func (client *ClusterClient) GeoSearchWithFullOptions(ctx context.Context, key string, searchFrom options.GeoSearchOrigin, ...) ([]options.Location, error)
- func (client *ClusterClient) GeoSearchWithInfoOptions(ctx context.Context, key string, searchFrom options.GeoSearchOrigin, ...) ([]options.Location, error)
- func (client *ClusterClient) GeoSearchWithResultOptions(ctx context.Context, key string, searchFrom options.GeoSearchOrigin, ...) ([]string, error)
- func (client *ClusterClient) Get(ctx context.Context, key string) (models.Result[string], error)
- func (client *ClusterClient) GetBit(ctx context.Context, key string, offset int64) (int64, error)
- func (client *ClusterClient) GetDel(ctx context.Context, key string) (models.Result[string], error)
- func (client *ClusterClient) GetEx(ctx context.Context, key string) (models.Result[string], error)
- func (client *ClusterClient) GetExWithOptions(ctx context.Context, key string, options options.GetExOptions) (models.Result[string], error)
- func (client *ClusterClient) GetQueue() (*PubSubMessageQueue, error)
- func (client *ClusterClient) GetRange(ctx context.Context, key string, start int, end int) (string, error)
- func (client *ClusterClient) GetStatistics() map[string]uint64
- func (client *ClusterClient) GetSubscriptions(ctx context.Context) (*models.PubSubState, error)
- func (client *ClusterClient) HDel(ctx context.Context, key string, fields []string) (int64, error)
- func (client *ClusterClient) HExists(ctx context.Context, key string, field string) (bool, error)
- func (client *ClusterClient) HExpire(ctx context.Context, key string, expireTime time.Duration, fields []string, ...) ([]int64, error)
- func (client *ClusterClient) HExpireAt(ctx context.Context, key string, expireTime time.Time, fields []string, ...) ([]int64, error)
- func (client *ClusterClient) HExpireTime(ctx context.Context, key string, fields []string) ([]int64, error)
- func (client *ClusterClient) HGet(ctx context.Context, key string, field string) (models.Result[string], error)
- func (client *ClusterClient) HGetAll(ctx context.Context, key string) (map[string]string, error)
- func (client *ClusterClient) HGetEx(ctx context.Context, key string, fields []string, opts options.HGetExOptions) ([]models.Result[string], error)
- func (client *ClusterClient) HIncrBy(ctx context.Context, key string, field string, increment int64) (int64, error)
- func (client *ClusterClient) HIncrByFloat(ctx context.Context, key string, field string, increment float64) (float64, error)
- func (client *ClusterClient) HKeys(ctx context.Context, key string) ([]string, error)
- func (client *ClusterClient) HLen(ctx context.Context, key string) (int64, error)
- func (client *ClusterClient) HMGet(ctx context.Context, key string, fields []string) ([]models.Result[string], error)
- func (client *ClusterClient) HPExpire(ctx context.Context, key string, expireTime time.Duration, fields []string, ...) ([]int64, error)
- func (client *ClusterClient) HPExpireAt(ctx context.Context, key string, expireTime time.Time, fields []string, ...) ([]int64, error)
- func (client *ClusterClient) HPExpireTime(ctx context.Context, key string, fields []string) ([]int64, error)
- func (client *ClusterClient) HPTtl(ctx context.Context, key string, fields []string) ([]int64, error)
- func (client *ClusterClient) HPersist(ctx context.Context, key string, fields []string) ([]int64, error)
- func (client *ClusterClient) HRandField(ctx context.Context, key string) (models.Result[string], error)
- func (client *ClusterClient) HRandFieldWithCount(ctx context.Context, key string, count int64) ([]string, error)
- func (client *ClusterClient) HRandFieldWithCountWithValues(ctx context.Context, key string, count int64) ([][]string, error)
- func (client *ClusterClient) HScan(ctx context.Context, key string, cursor models.Cursor) (models.ScanResult, error)
- func (client *ClusterClient) HScanWithOptions(ctx context.Context, key string, cursor models.Cursor, ...) (models.ScanResult, error)
- func (client *ClusterClient) HSet(ctx context.Context, key string, values map[string]string) (int64, error)
- func (client *ClusterClient) HSetEx(ctx context.Context, key string, fieldsAndValues map[string]string, ...) (int64, error)
- func (client *ClusterClient) HSetNX(ctx context.Context, key string, field string, value string) (bool, error)
- func (client *ClusterClient) HStrLen(ctx context.Context, key string, field string) (int64, error)
- func (client *ClusterClient) HTtl(ctx context.Context, key string, fields []string) ([]int64, error)
- func (client *ClusterClient) HVals(ctx context.Context, key string) ([]string, error)
- func (client *ClusterClient) Incr(ctx context.Context, key string) (int64, error)
- func (client *ClusterClient) IncrBy(ctx context.Context, key string, amount int64) (int64, error)
- func (client *ClusterClient) IncrByFloat(ctx context.Context, key string, amount float64) (float64, error)
- func (client *ClusterClient) Info(ctx context.Context) (map[string]string, error)
- func (client *ClusterClient) InfoWithOptions(ctx context.Context, options options.ClusterInfoOptions) (models.ClusterValue[string], error)
- func (client *ClusterClient) InvokeScript(ctx context.Context, script options.Script) (any, error)
- func (client *ClusterClient) InvokeScriptWithClusterOptions(ctx context.Context, script options.Script, ...) (models.ClusterValue[any], error)
- func (client *ClusterClient) InvokeScriptWithOptions(ctx context.Context, script options.Script, ...) (any, error)
- func (client *ClusterClient) InvokeScriptWithRoute(ctx context.Context, script options.Script, route options.RouteOption) (models.ClusterValue[any], error)
- func (client *ClusterClient) LCS(ctx context.Context, key1 string, key2 string) (*models.LCSMatch, error)
- func (client *ClusterClient) LCSLen(ctx context.Context, key1, key2 string) (*models.LCSMatch, error)
- func (client *ClusterClient) LCSWithOptions(ctx context.Context, key1, key2 string, opts options.LCSIdxOptions) (*models.LCSMatch, error)
- func (client *ClusterClient) LIndex(ctx context.Context, key string, index int64) (models.Result[string], error)
- func (client *ClusterClient) LInsert(ctx context.Context, key string, insertPosition constants.InsertPosition, ...) (int64, error)
- func (client *ClusterClient) LLen(ctx context.Context, key string) (int64, error)
- func (client *ClusterClient) LMPop(ctx context.Context, keys []string, listDirection constants.ListDirection) ([]models.KeyValues, error)
- func (client *ClusterClient) LMPopCount(ctx context.Context, keys []string, listDirection constants.ListDirection, ...) ([]models.KeyValues, error)
- func (client *ClusterClient) LMove(ctx context.Context, source string, destination string, ...) (models.Result[string], error)
- func (client *ClusterClient) LPop(ctx context.Context, key string) (models.Result[string], error)
- func (client *ClusterClient) LPopCount(ctx context.Context, key string, count int64) ([]string, error)
- func (client *ClusterClient) LPos(ctx context.Context, key string, element string) (models.Result[int64], error)
- func (client *ClusterClient) LPosCount(ctx context.Context, key string, element string, count int64) ([]int64, error)
- func (client *ClusterClient) LPosCountWithOptions(ctx context.Context, key string, element string, count int64, ...) ([]int64, error)
- func (client *ClusterClient) LPosWithOptions(ctx context.Context, key string, element string, options options.LPosOptions) (models.Result[int64], error)
- func (client *ClusterClient) LPush(ctx context.Context, key string, elements []string) (int64, error)
- func (client *ClusterClient) LPushX(ctx context.Context, key string, elements []string) (int64, error)
- func (client *ClusterClient) LRange(ctx context.Context, key string, start int64, end int64) ([]string, error)
- func (client *ClusterClient) LRem(ctx context.Context, key string, count int64, element string) (int64, error)
- func (client *ClusterClient) LSet(ctx context.Context, key string, index int64, element string) (string, error)
- func (client *ClusterClient) LTrim(ctx context.Context, key string, start int64, end int64) (string, error)
- func (client *ClusterClient) LastSave(ctx context.Context) (models.ClusterValue[int64], error)
- func (client *ClusterClient) LastSaveWithOptions(ctx context.Context, opts options.RouteOption) (models.ClusterValue[int64], error)
- func (client *ClusterClient) Lolwut(ctx context.Context) (string, error)
- func (client *ClusterClient) LolwutWithOptions(ctx context.Context, lolwutOptions options.ClusterLolwutOptions) (models.ClusterValue[string], error)
- func (client *ClusterClient) MGet(ctx context.Context, keys []string) ([]models.Result[string], error)
- func (client *ClusterClient) MSet(ctx context.Context, keyValueMap map[string]string) (string, error)
- func (client *ClusterClient) MSetNX(ctx context.Context, keyValueMap map[string]string) (bool, error)
- func (client *ClusterClient) Move(ctx context.Context, key string, dbIndex int64) (bool, error)
- func (client *ClusterClient) ObjectEncoding(ctx context.Context, key string) (models.Result[string], error)
- func (client *ClusterClient) ObjectFreq(ctx context.Context, key string) (models.Result[int64], error)
- func (client *ClusterClient) ObjectIdleTime(ctx context.Context, key string) (models.Result[int64], error)
- func (client *ClusterClient) ObjectRefCount(ctx context.Context, key string) (models.Result[int64], error)
- func (client *ClusterClient) PExpire(ctx context.Context, key string, expireTime time.Duration) (bool, error)
- func (client *ClusterClient) PExpireAt(ctx context.Context, key string, expireTime time.Time) (bool, error)
- func (client *ClusterClient) PExpireAtWithOptions(ctx context.Context, key string, expireTime time.Time, ...) (bool, error)
- func (client *ClusterClient) PExpireTime(ctx context.Context, key string) (int64, error)
- func (client *ClusterClient) PExpireWithOptions(ctx context.Context, key string, expireTime time.Duration, ...) (bool, error)
- func (client *ClusterClient) PSubscribe(ctx context.Context, patterns []string, timeoutMs int) error
- func (client *ClusterClient) PSubscribeBlocking(ctx context.Context, patterns []string, timeoutMs int) error
- func (client *ClusterClient) PSubscribeLazy(ctx context.Context, patterns []string) error
- func (client *ClusterClient) PTTL(ctx context.Context, key string) (int64, error)
- func (client *ClusterClient) PUnsubscribe(ctx context.Context, patterns []string, timeoutMs int) error
- func (client *ClusterClient) PUnsubscribeLazy(ctx context.Context, patterns []string) error
- func (client *ClusterClient) Persist(ctx context.Context, key string) (bool, error)
- func (client *ClusterClient) PfAdd(ctx context.Context, key string, elements []string) (bool, error)
- func (client *ClusterClient) PfCount(ctx context.Context, keys []string) (int64, error)
- func (client *ClusterClient) PfMerge(ctx context.Context, destination string, sourceKeys []string) (string, error)
- func (client *ClusterClient) Ping(ctx context.Context) (string, error)
- func (client *ClusterClient) PingWithOptions(ctx context.Context, pingOptions options.ClusterPingOptions) (string, error)
- func (client *ClusterClient) PubSubChannels(ctx context.Context) ([]string, error)
- func (client *ClusterClient) PubSubChannelsWithPattern(ctx context.Context, pattern string) ([]string, error)
- func (client *ClusterClient) PubSubNumPat(ctx context.Context) (int64, error)
- func (client *ClusterClient) PubSubNumSub(ctx context.Context, channels ...string) (map[string]int64, error)
- func (client *ClusterClient) PubSubShardChannels(ctx context.Context) ([]string, error)
- func (client *ClusterClient) PubSubShardChannelsWithPattern(ctx context.Context, pattern string) ([]string, error)
- func (client *ClusterClient) PubSubShardNumSub(ctx context.Context, channels ...string) (map[string]int64, error)
- func (client *ClusterClient) Publish(ctx context.Context, channel string, message string, sharded bool) (int64, error)
- func (client *ClusterClient) RPop(ctx context.Context, key string) (models.Result[string], error)
- func (client *ClusterClient) RPopCount(ctx context.Context, key string, count int64) ([]string, error)
- func (client *ClusterClient) RPush(ctx context.Context, key string, elements []string) (int64, error)
- func (client *ClusterClient) RPushX(ctx context.Context, key string, elements []string) (int64, error)
- func (client *ClusterClient) RandomKey(ctx context.Context) (models.Result[string], error)
- func (client *ClusterClient) RandomKeyWithRoute(ctx context.Context, opts options.RouteOption) (models.Result[string], error)
- func (client *ClusterClient) RefreshIamToken(ctx context.Context) (string, error)
- func (client *ClusterClient) Rename(ctx context.Context, key string, newKey string) (string, error)
- func (client *ClusterClient) RenameNX(ctx context.Context, key string, newKey string) (bool, error)
- func (client *ClusterClient) ResetConnectionPassword(ctx context.Context) (string, error)
- func (client *ClusterClient) Restore(ctx context.Context, key string, ttl time.Duration, value string) (string, error)
- func (client *ClusterClient) RestoreWithOptions(ctx context.Context, key string, ttl time.Duration, value string, ...) (string, error)
- func (client *ClusterClient) SAdd(ctx context.Context, key string, members []string) (int64, error)
- func (client *ClusterClient) SCard(ctx context.Context, key string) (int64, error)
- func (client *ClusterClient) SDiff(ctx context.Context, keys []string) (map[string]struct{}, error)
- func (client *ClusterClient) SDiffStore(ctx context.Context, destination string, keys []string) (int64, error)
- func (client *ClusterClient) SInter(ctx context.Context, keys []string) (map[string]struct{}, error)
- func (client *ClusterClient) SInterCard(ctx context.Context, keys []string) (int64, error)
- func (client *ClusterClient) SInterCardLimit(ctx context.Context, keys []string, limit int64) (int64, error)
- func (client *ClusterClient) SInterStore(ctx context.Context, destination string, keys []string) (int64, error)
- func (client *ClusterClient) SIsMember(ctx context.Context, key string, member string) (bool, error)
- func (client *ClusterClient) SMIsMember(ctx context.Context, key string, members []string) ([]bool, error)
- func (client *ClusterClient) SMembers(ctx context.Context, key string) (map[string]struct{}, error)
- func (client *ClusterClient) SMove(ctx context.Context, source string, destination string, member string) (bool, error)
- func (client *ClusterClient) SPop(ctx context.Context, key string) (models.Result[string], error)
- func (client *ClusterClient) SPopCount(ctx context.Context, key string, count int64) (map[string]struct{}, error)
- func (client *ClusterClient) SRandMember(ctx context.Context, key string) (models.Result[string], error)
- func (client *ClusterClient) SRandMemberCount(ctx context.Context, key string, count int64) ([]string, error)
- func (client *ClusterClient) SRem(ctx context.Context, key string, members []string) (int64, error)
- func (client *ClusterClient) SScan(ctx context.Context, key string, cursor models.Cursor) (models.ScanResult, error)
- func (client *ClusterClient) SScanWithOptions(ctx context.Context, key string, cursor models.Cursor, ...) (models.ScanResult, error)
- func (client *ClusterClient) SSubscribe(ctx context.Context, channels []string, timeoutMs int) error
- func (client *ClusterClient) SSubscribeLazy(ctx context.Context, channels []string) error
- func (client *ClusterClient) SUnion(ctx context.Context, keys []string) (map[string]struct{}, error)
- func (client *ClusterClient) SUnionStore(ctx context.Context, destination string, keys []string) (int64, error)
- func (client *ClusterClient) SUnsubscribe(ctx context.Context, channels []string, timeoutMs int) error
- func (client *ClusterClient) SUnsubscribeLazy(ctx context.Context, channels []string) error
- func (client *ClusterClient) Scan(ctx context.Context, cursor models.ClusterScanCursor) (models.ClusterScanResult, error)
- func (client *ClusterClient) ScanWithOptions(ctx context.Context, cursor models.ClusterScanCursor, ...) (models.ClusterScanResult, error)
- func (client *ClusterClient) ScriptExists(ctx context.Context, sha1s []string) ([]bool, error)
- func (client *ClusterClient) ScriptExistsWithRoute(ctx context.Context, sha1s []string, route options.RouteOption) ([]bool, error)
- func (client *ClusterClient) ScriptFlush(ctx context.Context) (string, error)
- func (client *ClusterClient) ScriptFlushWithMode(ctx context.Context, mode options.FlushMode) (string, error)
- func (client *ClusterClient) ScriptFlushWithOptions(ctx context.Context, options options.ScriptFlushOptions) (string, error)
- func (client *ClusterClient) ScriptKill(ctx context.Context) (string, error)
- func (client *ClusterClient) ScriptKillWithRoute(ctx context.Context, route options.RouteOption) (string, error)
- func (client *ClusterClient) ScriptShow(ctx context.Context, sha1 string) (string, error)
- func (client *ClusterClient) Select(ctx context.Context, index int64) (string, error)
- func (client *ClusterClient) Set(ctx context.Context, key string, value string) (string, error)
- func (client *ClusterClient) SetBit(ctx context.Context, key string, offset int64, value int64) (int64, error)
- func (client *ClusterClient) SetRange(ctx context.Context, key string, offset int, value string) (int64, error)
- func (client *ClusterClient) SetWithOptions(ctx context.Context, key string, value string, options options.SetOptions) (models.Result[string], error)
- func (client *ClusterClient) Sort(ctx context.Context, key string) ([]models.Result[string], error)
- func (client *ClusterClient) SortReadOnly(ctx context.Context, key string) ([]models.Result[string], error)
- func (client *ClusterClient) SortReadOnlyWithOptions(ctx context.Context, key string, options options.SortOptions) ([]models.Result[string], error)
- func (client *ClusterClient) SortStore(ctx context.Context, key string, destination string) (int64, error)
- func (client *ClusterClient) SortStoreWithOptions(ctx context.Context, key string, destination string, opts options.SortOptions) (int64, error)
- func (client *ClusterClient) SortWithOptions(ctx context.Context, key string, options options.SortOptions) ([]models.Result[string], error)
- func (client *ClusterClient) Strlen(ctx context.Context, key string) (int64, error)
- func (client *ClusterClient) Subscribe(ctx context.Context, channels []string, timeoutMs int) error
- func (client *ClusterClient) SubscribeLazy(ctx context.Context, channels []string) error
- func (client *ClusterClient) TTL(ctx context.Context, key string) (int64, error)
- func (client *ClusterClient) Time(ctx context.Context) ([]string, error)
- func (client *ClusterClient) TimeWithOptions(ctx context.Context, opts options.RouteOption) (models.ClusterValue[[]string], error)
- func (client *ClusterClient) Touch(ctx context.Context, keys []string) (int64, error)
- func (client *ClusterClient) Type(ctx context.Context, key string) (string, error)
- func (client *ClusterClient) Unlink(ctx context.Context, keys []string) (int64, error)
- func (client *ClusterClient) Unsubscribe(ctx context.Context, channels []string, timeoutMs int) error
- func (client *ClusterClient) UnsubscribeLazy(ctx context.Context, channels []string) error
- func (client *ClusterClient) Unwatch(ctx context.Context) (string, error)
- func (client *ClusterClient) UnwatchWithOptions(ctx context.Context, route options.RouteOption) (string, error)
- func (client *ClusterClient) UpdateConnectionPassword(ctx context.Context, password string, immediateAuth bool) (string, error)
- func (client *ClusterClient) Wait(ctx context.Context, numberOfReplicas int64, timeout time.Duration) (int64, error)
- func (client *ClusterClient) Watch(ctx context.Context, keys []string) (string, error)
- func (client *ClusterClient) XAck(ctx context.Context, key string, group string, ids []string) (int64, error)
- func (client *ClusterClient) XAdd(ctx context.Context, key string, values []models.FieldValue) (string, error)
- func (client *ClusterClient) XAddWithOptions(ctx context.Context, key string, values []models.FieldValue, ...) (models.Result[string], error)
- func (client *ClusterClient) XAutoClaim(ctx context.Context, key string, group string, consumer string, ...) (models.XAutoClaimResponse, error)
- func (client *ClusterClient) XAutoClaimJustId(ctx context.Context, key string, group string, consumer string, ...) (models.XAutoClaimJustIdResponse, error)
- func (client *ClusterClient) XAutoClaimJustIdWithOptions(ctx context.Context, key string, group string, consumer string, ...) (models.XAutoClaimJustIdResponse, error)
- func (client *ClusterClient) XAutoClaimWithOptions(ctx context.Context, key string, group string, consumer string, ...) (models.XAutoClaimResponse, error)
- func (client *ClusterClient) XClaim(ctx context.Context, key string, group string, consumer string, ...) (map[string]models.XClaimResponse, error)
- func (client *ClusterClient) XClaimJustId(ctx context.Context, key string, group string, consumer string, ...) ([]string, error)
- func (client *ClusterClient) XClaimJustIdWithOptions(ctx context.Context, key string, group string, consumer string, ...) ([]string, error)
- func (client *ClusterClient) XClaimWithOptions(ctx context.Context, key string, group string, consumer string, ...) (map[string]models.XClaimResponse, error)
- func (client *ClusterClient) XDel(ctx context.Context, key string, ids []string) (int64, error)
- func (client *ClusterClient) XGroupCreate(ctx context.Context, key string, group string, id string) (string, error)
- func (client *ClusterClient) XGroupCreateConsumer(ctx context.Context, key string, group string, consumer string) (bool, error)
- func (client *ClusterClient) XGroupCreateWithOptions(ctx context.Context, key string, group string, id string, ...) (string, error)
- func (client *ClusterClient) XGroupDelConsumer(ctx context.Context, key string, group string, consumer string) (int64, error)
- func (client *ClusterClient) XGroupDestroy(ctx context.Context, key string, group string) (bool, error)
- func (client *ClusterClient) XGroupSetId(ctx context.Context, key string, group string, id string) (string, error)
- func (client *ClusterClient) XGroupSetIdWithOptions(ctx context.Context, key string, group string, id string, ...) (string, error)
- func (client *ClusterClient) XInfoConsumers(ctx context.Context, key string, group string) ([]models.XInfoConsumerInfo, error)
- func (client *ClusterClient) XInfoGroups(ctx context.Context, key string) ([]models.XInfoGroupInfo, error)
- func (client *ClusterClient) XInfoStream(ctx context.Context, key string) (models.XInfoStreamResponse, error)
- func (client *ClusterClient) XInfoStreamFullWithOptions(ctx context.Context, key string, opts options.XInfoStreamOptions) (models.XInfoStreamFullOptionsResponse, error)
- func (client *ClusterClient) XLen(ctx context.Context, key string) (int64, error)
- func (client *ClusterClient) XPending(ctx context.Context, key string, group string) (models.XPendingSummary, error)
- func (client *ClusterClient) XPendingWithOptions(ctx context.Context, key string, group string, opts options.XPendingOptions) ([]models.XPendingDetail, error)
- func (client *ClusterClient) XRange(ctx context.Context, key string, start options.StreamBoundary, ...) ([]models.StreamEntry, error)
- func (client *ClusterClient) XRangeWithOptions(ctx context.Context, key string, start options.StreamBoundary, ...) ([]models.StreamEntry, error)
- func (client *ClusterClient) XRead(ctx context.Context, keysAndIds map[string]string) (map[string]models.StreamResponse, error)
- func (client *ClusterClient) XReadGroup(ctx context.Context, group string, consumer string, ...) (map[string]models.StreamResponse, error)
- func (client *ClusterClient) XReadGroupWithOptions(ctx context.Context, group string, consumer string, ...) (map[string]models.StreamResponse, error)
- func (client *ClusterClient) XReadWithOptions(ctx context.Context, keysAndIds map[string]string, opts options.XReadOptions) (map[string]models.StreamResponse, error)
- func (client *ClusterClient) XRevRange(ctx context.Context, key string, start options.StreamBoundary, ...) ([]models.StreamEntry, error)
- func (client *ClusterClient) XRevRangeWithOptions(ctx context.Context, key string, start options.StreamBoundary, ...) ([]models.StreamEntry, error)
- func (client *ClusterClient) XTrim(ctx context.Context, key string, options options.XTrimOptions) (int64, error)
- func (client *ClusterClient) ZAdd(ctx context.Context, key string, membersScoreMap map[string]float64) (int64, error)
- func (client *ClusterClient) ZAddIncr(ctx context.Context, key string, member string, increment float64) (float64, error)
- func (client *ClusterClient) ZAddIncrWithOptions(ctx context.Context, key string, member string, increment float64, ...) (models.Result[float64], error)
- func (client *ClusterClient) ZAddWithOptions(ctx context.Context, key string, membersScoreMap map[string]float64, ...) (int64, error)
- func (client *ClusterClient) ZCard(ctx context.Context, key string) (int64, error)
- func (client *ClusterClient) ZCount(ctx context.Context, key string, rangeOptions options.ZCountRange) (int64, error)
- func (client *ClusterClient) ZDiff(ctx context.Context, keys []string) ([]string, error)
- func (client *ClusterClient) ZDiffStore(ctx context.Context, destination string, keys []string) (int64, error)
- func (client *ClusterClient) ZDiffWithScores(ctx context.Context, keys []string) ([]models.MemberAndScore, error)
- func (client *ClusterClient) ZIncrBy(ctx context.Context, key string, increment float64, member string) (float64, error)
- func (client *ClusterClient) ZInter(ctx context.Context, keys options.KeyArray) ([]string, error)
- func (client *ClusterClient) ZInterCard(ctx context.Context, keys []string) (int64, error)
- func (client *ClusterClient) ZInterCardWithOptions(ctx context.Context, keys []string, options options.ZInterCardOptions) (int64, error)
- func (client *ClusterClient) ZInterStore(ctx context.Context, destination string, ...) (int64, error)
- func (client *ClusterClient) ZInterStoreWithOptions(ctx context.Context, destination string, ...) (int64, error)
- func (client *ClusterClient) ZInterWithScores(ctx context.Context, keysOrWeightedKeys options.KeysOrWeightedKeys, ...) ([]models.MemberAndScore, error)
- func (client *ClusterClient) ZLexCount(ctx context.Context, key string, rangeQuery options.RangeByLex) (int64, error)
- func (client *ClusterClient) ZMPop(ctx context.Context, keys []string, scoreFilter constants.ScoreFilter) (models.Result[models.KeyWithArrayOfMembersAndScores], error)
- func (client *ClusterClient) ZMPopWithOptions(ctx context.Context, keys []string, scoreFilter constants.ScoreFilter, ...) (models.Result[models.KeyWithArrayOfMembersAndScores], error)
- func (client *ClusterClient) ZMScore(ctx context.Context, key string, members []string) ([]models.Result[float64], error)
- func (client *ClusterClient) ZPopMax(ctx context.Context, key string) (map[string]float64, error)
- func (client *ClusterClient) ZPopMaxWithOptions(ctx context.Context, key string, options options.ZPopOptions) (map[string]float64, error)
- func (client *ClusterClient) ZPopMin(ctx context.Context, key string) (map[string]float64, error)
- func (client *ClusterClient) ZPopMinWithOptions(ctx context.Context, key string, options options.ZPopOptions) (map[string]float64, error)
- func (client *ClusterClient) ZRandMember(ctx context.Context, key string) (models.Result[string], error)
- func (client *ClusterClient) ZRandMemberWithCount(ctx context.Context, key string, count int64) ([]string, error)
- func (client *ClusterClient) ZRandMemberWithCountWithScores(ctx context.Context, key string, count int64) ([]models.MemberAndScore, error)
- func (client *ClusterClient) ZRange(ctx context.Context, key string, rangeQuery options.ZRangeQuery) ([]string, error)
- func (client *ClusterClient) ZRangeStore(ctx context.Context, destination string, key string, ...) (int64, error)
- func (client *ClusterClient) ZRangeWithScores(ctx context.Context, key string, rangeQuery options.ZRangeQueryWithScores) ([]models.MemberAndScore, error)
- func (client *ClusterClient) ZRank(ctx context.Context, key string, member string) (models.Result[int64], error)
- func (client *ClusterClient) ZRankWithScore(ctx context.Context, key string, member string) (models.Result[models.RankAndScore], error)
- func (client *ClusterClient) ZRem(ctx context.Context, key string, members []string) (int64, error)
- func (client *ClusterClient) ZRemRangeByLex(ctx context.Context, key string, rangeQuery options.RangeByLex) (int64, error)
- func (client *ClusterClient) ZRemRangeByRank(ctx context.Context, key string, start int64, stop int64) (int64, error)
- func (client *ClusterClient) ZRemRangeByScore(ctx context.Context, key string, rangeQuery options.RangeByScore) (int64, error)
- func (client *ClusterClient) ZRevRank(ctx context.Context, key string, member string) (models.Result[int64], error)
- func (client *ClusterClient) ZRevRankWithScore(ctx context.Context, key string, member string) (models.Result[models.RankAndScore], error)
- func (client *ClusterClient) ZScan(ctx context.Context, key string, cursor models.Cursor) (models.ScanResult, error)
- func (client *ClusterClient) ZScanWithOptions(ctx context.Context, key string, cursor models.Cursor, ...) (models.ScanResult, error)
- func (client *ClusterClient) ZScore(ctx context.Context, key string, member string) (models.Result[float64], error)
- func (client *ClusterClient) ZUnion(ctx context.Context, keys options.KeyArray) ([]string, error)
- func (client *ClusterClient) ZUnionStore(ctx context.Context, destination string, ...) (int64, error)
- func (client *ClusterClient) ZUnionStoreWithOptions(ctx context.Context, destination string, ...) (int64, error)
- func (client *ClusterClient) ZUnionWithScores(ctx context.Context, keysOrWeightedKeys options.KeysOrWeightedKeys, ...) ([]models.MemberAndScore, error)
- type ConfigurationError
- type ConnectionError
- type DisconnectError
- type ExecAbortError
- type MessageCallbackError
- type MessageHandler
- type OpenTelemetry
- func (o *OpenTelemetry) CreateSpan(name string) (uint64, error)
- func (o *OpenTelemetry) EndSpan(spanPtr uint64)
- func (o *OpenTelemetry) GetSamplePercentage() int32
- func (o *OpenTelemetry) Init(openTelemetryConfig OpenTelemetryConfig) error
- func (o *OpenTelemetry) IsInitialized() bool
- func (o *OpenTelemetry) SetSamplePercentage(percentage int32) error
- type OpenTelemetryConfig
- type OpenTelemetryMetricsConfig
- type OpenTelemetryTracesConfig
- type PubSubMessageQueue
- func (queue *PubSubMessageQueue) Pop() *models.PubSubMessage
- func (queue *PubSubMessageQueue) Push(message *models.PubSubMessage)
- func (queue *PubSubMessageQueue) RegisterSignalChannel(ch chan struct{})
- func (queue *PubSubMessageQueue) UnregisterSignalChannel(ch chan struct{})
- func (queue *PubSubMessageQueue) WaitForMessage() <-chan *models.PubSubMessage
- type TimeoutError
Examples ¶
- Client (CompressionCustomLevel)
- Client (CompressionLZ4)
- Client (CompressionStatistics)
- Client (CompressionZSTD)
- Client.Append
- Client.BLMPop
- Client.BLMPopCount
- Client.BLMove
- Client.BLPop
- Client.BRPop
- Client.BZMPop
- Client.BZMPopWithOptions
- Client.BZPopMax
- Client.BZPopMin
- Client.BitCount
- Client.BitCountWithOptions
- Client.BitField
- Client.BitFieldRO
- Client.BitOp
- Client.BitPos
- Client.BitPosWithOptions
- Client.ClientGetName
- Client.ClientId
- Client.ClientSetName
- Client.ConfigGet
- Client.ConfigResetStat
- Client.ConfigRewrite
- Client.ConfigSet
- Client.Copy
- Client.CopyWithOptions
- Client.CustomCommand
- Client.DBSize
- Client.Decr
- Client.DecrBy
- Client.Del
- Client.Dump
- Client.Echo
- Client.Exec (Pipeline)
- Client.Exec (Transaction)
- Client.ExecWithOptions (Pipeline)
- Client.ExecWithOptions (Transaction)
- Client.Exists
- Client.Expire
- Client.ExpireAt
- Client.ExpireAtWithOptions
- Client.ExpireTime
- Client.ExpireWithOptions
- Client.FCall
- Client.FCallReadOnly
- Client.FCallReadOnlyWithKeysAndArgs
- Client.FCallWithKeysAndArgs
- Client.FlushAll
- Client.FlushAllWithOptions
- Client.FlushDB
- Client.FlushDBWithOptions
- Client.FunctionDelete
- Client.FunctionDump
- Client.FunctionFlush
- Client.FunctionFlushAsync
- Client.FunctionFlushSync
- Client.FunctionKill
- Client.FunctionList
- Client.FunctionLoad
- Client.FunctionRestore
- Client.FunctionRestoreWithPolicy
- Client.FunctionStats
- Client.GeoAdd
- Client.GeoDist
- Client.GeoHash
- Client.GeoPos
- Client.GeoSearch
- Client.GeoSearchStore
- Client.GeoSearchStoreWithFullOptions
- Client.GeoSearchStoreWithInfoOptions
- Client.GeoSearchStoreWithResultOptions
- Client.GeoSearchWithFullOptions
- Client.GeoSearchWithInfoOptions
- Client.GeoSearchWithResultOptions
- Client.Get (Keyexists)
- Client.Get (Keynotexists)
- Client.GetBit
- Client.GetDel
- Client.GetEx
- Client.GetExWithOptions
- Client.GetRange (One)
- Client.GetRange (Two)
- Client.HDel
- Client.HExists
- Client.HExpire
- Client.HGet
- Client.HGetAll
- Client.HGetEx
- Client.HIncrBy
- Client.HIncrByFloat
- Client.HKeys
- Client.HLen
- Client.HMGet
- Client.HPersist
- Client.HRandField
- Client.HRandFieldWithCount
- Client.HRandFieldWithCountWithValues
- Client.HScan
- Client.HScanWithOptions
- Client.HSet
- Client.HSetEx
- Client.HSetNX
- Client.HStrLen
- Client.HTtl
- Client.HVals
- Client.Incr
- Client.IncrBy
- Client.IncrByFloat
- Client.Info
- Client.InfoWithOptions
- Client.InvokeScript
- Client.InvokeScriptWithOptions
- Client.LCS
- Client.LCSLen
- Client.LCSWithOptions (Basic)
- Client.LCSWithOptions (Minmatchlen)
- Client.LIndex
- Client.LInsert
- Client.LLen
- Client.LMPop
- Client.LMPopCount
- Client.LMove
- Client.LPop
- Client.LPopCount
- Client.LPos
- Client.LPosCount
- Client.LPosCountWithOptions
- Client.LPosWithOptions
- Client.LPush
- Client.LPushX
- Client.LRange
- Client.LRem
- Client.LSet
- Client.LTrim
- Client.LastSave
- Client.Lolwut
- Client.LolwutWithOptions
- Client.MGet
- Client.MSet
- Client.MSetNX
- Client.Move
- Client.ObjectEncoding
- Client.ObjectFreq
- Client.ObjectIdleTime
- Client.ObjectRefCount
- Client.PExpire
- Client.PExpireAt
- Client.PExpireAtWithOptions
- Client.PExpireTime
- Client.PExpireWithOptions
- Client.PTTL
- Client.Persist
- Client.PfAdd
- Client.PfCount
- Client.PfMerge
- Client.Ping
- Client.PingWithOptions
- Client.PubSubChannels
- Client.PubSubChannelsWithPattern
- Client.PubSubNumPat
- Client.PubSubNumSub
- Client.Publish
- Client.RPop
- Client.RPopCount
- Client.RPush
- Client.RPushX
- Client.RandomKey
- Client.Rename
- Client.RenameNX
- Client.ResetConnectionPassword
- Client.Restore
- Client.RestoreWithOptions
- Client.SAdd
- Client.SCard
- Client.SDiff
- Client.SDiffStore
- Client.SInter
- Client.SInterCard
- Client.SInterCardLimit
- Client.SInterStore
- Client.SIsMember
- Client.SMIsMember
- Client.SMembers
- Client.SMove
- Client.SPop
- Client.SPopCount
- Client.SRandMember
- Client.SRandMemberCount
- Client.SRem
- Client.SScan
- Client.SScanWithOptions
- Client.SUnion
- Client.SUnionStore
- Client.Scan
- Client.ScanWithOptions
- Client.ScriptExists
- Client.ScriptFlush
- Client.ScriptFlushWithMode
- Client.ScriptKill
- Client.ScriptShow
- Client.Select
- Client.Set
- Client.SetBit
- Client.SetRange (One)
- Client.SetRange (Two)
- Client.SetWithOptions
- Client.Sort
- Client.SortReadOnly
- Client.SortReadOnlyWithOptions
- Client.SortStore
- Client.SortStoreWithOptions
- Client.SortWithOptions
- Client.Strlen
- Client.TTL
- Client.Time
- Client.Touch
- Client.Type
- Client.Unlink
- Client.Unwatch
- Client.UpdateConnectionPassword
- Client.Wait
- Client.Watch (ChangedKey)
- Client.Watch (UnchangedKey)
- Client.XAck
- Client.XAdd
- Client.XAddWithOptions
- Client.XAutoClaim
- Client.XAutoClaimJustId
- Client.XAutoClaimJustIdWithOptions
- Client.XAutoClaimWithOptions
- Client.XClaim
- Client.XClaimJustId
- Client.XClaimJustIdWithOptions
- Client.XClaimWithOptions
- Client.XDel
- Client.XGroupCreate
- Client.XGroupCreateConsumer
- Client.XGroupCreateWithOptions
- Client.XGroupDelConsumer
- Client.XGroupDestroy
- Client.XGroupSetId
- Client.XGroupSetIdWithOptions
- Client.XInfoConsumers
- Client.XInfoGroups
- Client.XInfoStream
- Client.XInfoStreamFullWithOptions
- Client.XLen
- Client.XPending
- Client.XPendingWithOptions
- Client.XRange
- Client.XRangeWithOptions
- Client.XRead
- Client.XReadGroup
- Client.XReadGroupWithOptions
- Client.XReadWithOptions
- Client.XRevRange
- Client.XRevRangeWithOptions
- Client.XTrim
- Client.ZAdd
- Client.ZAddIncr
- Client.ZAddIncrWithOptions
- Client.ZAddWithOptions
- Client.ZCard
- Client.ZCount
- Client.ZDiff
- Client.ZDiffStore
- Client.ZDiffWithScores
- Client.ZIncrBy
- Client.ZInter
- Client.ZInterCard
- Client.ZInterCardWithOptions
- Client.ZInterStore
- Client.ZInterStoreWithOptions
- Client.ZInterWithScores
- Client.ZLexCount
- Client.ZMPop
- Client.ZMPopWithOptions
- Client.ZMScore
- Client.ZPopMax
- Client.ZPopMaxWithOptions
- Client.ZPopMin
- Client.ZPopMinWithOptions
- Client.ZRandMember
- Client.ZRandMemberWithCount
- Client.ZRandMemberWithCountWithScores
- Client.ZRange
- Client.ZRangeStore
- Client.ZRangeWithScores
- Client.ZRank
- Client.ZRankWithScore
- Client.ZRem
- Client.ZRemRangeByLex
- Client.ZRemRangeByRank
- Client.ZRemRangeByScore
- Client.ZRevRank
- Client.ZRevRankWithScore
- Client.ZScan
- Client.ZScanWithOptions
- Client.ZScore
- Client.ZUnion
- Client.ZUnionStore
- Client.ZUnionStoreWithOptions
- Client.ZUnionWithScores
- ClusterClient (Compression)
- ClusterClient.Append
- ClusterClient.BLMPop
- ClusterClient.BLMPopCount
- ClusterClient.BLMove
- ClusterClient.BLPop
- ClusterClient.BRPop
- ClusterClient.BZMPop
- ClusterClient.BZMPopWithOptions
- ClusterClient.BZPopMax
- ClusterClient.BZPopMin
- ClusterClient.BitCount
- ClusterClient.BitCountWithOptions
- ClusterClient.BitField
- ClusterClient.BitFieldRO
- ClusterClient.BitOp
- ClusterClient.BitPos
- ClusterClient.BitPosWithOptions
- ClusterClient.ClientGetName
- ClusterClient.ClientGetNameWithOptions
- ClusterClient.ClientId
- ClusterClient.ClientIdWithOptions
- ClusterClient.ClientSetName
- ClusterClient.ClientSetNameWithOptions
- ClusterClient.ConfigGet
- ClusterClient.ConfigGetWithOptions
- ClusterClient.ConfigResetStat
- ClusterClient.ConfigResetStatWithOptions
- ClusterClient.ConfigRewrite
- ClusterClient.ConfigRewriteWithOptions
- ClusterClient.ConfigSet
- ClusterClient.ConfigSetWithOptions
- ClusterClient.Copy
- ClusterClient.CopyWithOptions
- ClusterClient.CopyWithOptions (DbDestination)
- ClusterClient.CustomCommand
- ClusterClient.CustomCommandWithRoute
- ClusterClient.DBSizeWithOptions
- ClusterClient.Decr
- ClusterClient.DecrBy
- ClusterClient.Del
- ClusterClient.Dump
- ClusterClient.Echo
- ClusterClient.EchoWithOptions
- ClusterClient.Exec (Pipeline)
- ClusterClient.Exec (Transaction)
- ClusterClient.ExecWithOptions (Pipeline)
- ClusterClient.ExecWithOptions (Route)
- ClusterClient.ExecWithOptions (Transaction)
- ClusterClient.Exists
- ClusterClient.Expire
- ClusterClient.ExpireAt
- ClusterClient.ExpireAtWithOptions
- ClusterClient.ExpireTime
- ClusterClient.ExpireWithOptions
- ClusterClient.FCall
- ClusterClient.FCallReadOnly
- ClusterClient.FCallReadOnlyWithArgs
- ClusterClient.FCallReadOnlyWithArgsWithRoute
- ClusterClient.FCallReadOnlyWithKeysAndArgs
- ClusterClient.FCallReadOnlyWithRoute
- ClusterClient.FCallWithArgs
- ClusterClient.FCallWithArgsWithRoute
- ClusterClient.FCallWithKeysAndArgs
- ClusterClient.FCallWithRoute
- ClusterClient.FlushAll
- ClusterClient.FlushAllWithOptions
- ClusterClient.FlushDB
- ClusterClient.FlushDBWithOptions
- ClusterClient.FunctionDelete
- ClusterClient.FunctionDeleteWithRoute
- ClusterClient.FunctionDump
- ClusterClient.FunctionDumpWithRoute
- ClusterClient.FunctionFlush
- ClusterClient.FunctionFlushAsync
- ClusterClient.FunctionFlushAsyncWithRoute
- ClusterClient.FunctionFlushSync
- ClusterClient.FunctionFlushSyncWithRoute
- ClusterClient.FunctionFlushWithRoute
- ClusterClient.FunctionKill
- ClusterClient.FunctionKillWithRoute
- ClusterClient.FunctionList
- ClusterClient.FunctionListWithRoute
- ClusterClient.FunctionLoad
- ClusterClient.FunctionLoadWithRoute
- ClusterClient.FunctionRestore
- ClusterClient.FunctionRestoreWithPolicy
- ClusterClient.FunctionRestoreWithPolicyWithRoute
- ClusterClient.FunctionRestoreWithRoute
- ClusterClient.FunctionStats
- ClusterClient.FunctionStatsWithRoute
- ClusterClient.GeoAdd
- ClusterClient.GeoDist
- ClusterClient.GeoHash
- ClusterClient.GeoPos
- ClusterClient.GeoSearch
- ClusterClient.GeoSearchStore
- ClusterClient.GeoSearchStoreWithFullOptions
- ClusterClient.GeoSearchStoreWithInfoOptions
- ClusterClient.GeoSearchStoreWithResultOptions
- ClusterClient.GeoSearchWithFullOptions
- ClusterClient.GeoSearchWithInfoOptions
- ClusterClient.GeoSearchWithResultOptions
- ClusterClient.Get (Keyexists)
- ClusterClient.Get (Keynotexists)
- ClusterClient.GetBit
- ClusterClient.GetDel
- ClusterClient.GetEx
- ClusterClient.GetExWithOptions
- ClusterClient.GetRange (One)
- ClusterClient.GetRange (Two)
- ClusterClient.HDel
- ClusterClient.HExists
- ClusterClient.HExpire
- ClusterClient.HGet
- ClusterClient.HGetAll
- ClusterClient.HGetEx
- ClusterClient.HIncrBy
- ClusterClient.HIncrByFloat
- ClusterClient.HKeys
- ClusterClient.HLen
- ClusterClient.HMGet
- ClusterClient.HPersist
- ClusterClient.HRandField
- ClusterClient.HRandFieldWithCount
- ClusterClient.HRandFieldWithCountWithValues
- ClusterClient.HScan
- ClusterClient.HScanWithOptions
- ClusterClient.HSet
- ClusterClient.HSetEx
- ClusterClient.HSetNX
- ClusterClient.HStrLen
- ClusterClient.HTtl
- ClusterClient.HVals
- ClusterClient.Incr
- ClusterClient.IncrBy
- ClusterClient.IncrByFloat
- ClusterClient.Info
- ClusterClient.InfoWithOptions
- ClusterClient.InvokeScript
- ClusterClient.InvokeScriptWithClusterOptions
- ClusterClient.InvokeScriptWithOptions
- ClusterClient.LCS
- ClusterClient.LCSLen
- ClusterClient.LCSWithOptions (Basic)
- ClusterClient.LCSWithOptions (Minmatchlen)
- ClusterClient.LIndex
- ClusterClient.LInsert
- ClusterClient.LLen
- ClusterClient.LMPop
- ClusterClient.LMPopCount
- ClusterClient.LMove
- ClusterClient.LPop
- ClusterClient.LPopCount
- ClusterClient.LPos
- ClusterClient.LPosCount
- ClusterClient.LPosCountWithOptions
- ClusterClient.LPosWithOptions
- ClusterClient.LPush
- ClusterClient.LPushX
- ClusterClient.LRange
- ClusterClient.LRem
- ClusterClient.LSet
- ClusterClient.LTrim
- ClusterClient.LastSave
- ClusterClient.LastSaveWithOptions
- ClusterClient.Lolwut
- ClusterClient.LolwutWithOptions
- ClusterClient.MGet
- ClusterClient.MSet
- ClusterClient.MSetNX
- ClusterClient.Move
- ClusterClient.ObjectEncoding
- ClusterClient.ObjectFreq
- ClusterClient.ObjectIdleTime
- ClusterClient.ObjectRefCount
- ClusterClient.PExpire
- ClusterClient.PExpireAt
- ClusterClient.PExpireAtWithOptions
- ClusterClient.PExpireTime
- ClusterClient.PExpireWithOptions
- ClusterClient.PTTL
- ClusterClient.Persist
- ClusterClient.PfAdd
- ClusterClient.PfCount
- ClusterClient.PfMerge
- ClusterClient.Ping
- ClusterClient.PingWithOptions
- ClusterClient.PubSubChannels
- ClusterClient.PubSubChannelsWithPattern
- ClusterClient.PubSubNumPat
- ClusterClient.PubSubNumSub
- ClusterClient.PubSubShardChannels
- ClusterClient.PubSubShardChannelsWithPattern
- ClusterClient.PubSubShardNumSub
- ClusterClient.Publish
- ClusterClient.RPop
- ClusterClient.RPopCount
- ClusterClient.RPush
- ClusterClient.RPushX
- ClusterClient.RandomKey
- ClusterClient.RandomKeyWithRoute
- ClusterClient.Rename
- ClusterClient.RenameNX
- ClusterClient.ResetConnectionPassword
- ClusterClient.Restore
- ClusterClient.RestoreWithOptions
- ClusterClient.SAdd
- ClusterClient.SCard
- ClusterClient.SDiff
- ClusterClient.SDiffStore
- ClusterClient.SInter
- ClusterClient.SInterCard
- ClusterClient.SInterCardLimit
- ClusterClient.SInterStore
- ClusterClient.SIsMember
- ClusterClient.SMIsMember
- ClusterClient.SMembers
- ClusterClient.SMove
- ClusterClient.SPop
- ClusterClient.SPopCount
- ClusterClient.SRandMember
- ClusterClient.SRandMemberCount
- ClusterClient.SRem
- ClusterClient.SScan
- ClusterClient.SScanWithOptions
- ClusterClient.SUnion
- ClusterClient.SUnionStore
- ClusterClient.Scan
- ClusterClient.ScanWithOptions (Count)
- ClusterClient.ScanWithOptions (Match)
- ClusterClient.ScanWithOptions (MatchNonUTF8)
- ClusterClient.ScanWithOptions (Type)
- ClusterClient.ScriptExists
- ClusterClient.ScriptExistsWithRoute
- ClusterClient.ScriptFlush
- ClusterClient.ScriptFlushWithMode
- ClusterClient.ScriptFlushWithOptions
- ClusterClient.ScriptKill (WithRoute)
- ClusterClient.ScriptKill (WithoutRoute)
- ClusterClient.ScriptShow
- ClusterClient.Set
- ClusterClient.SetBit
- ClusterClient.SetRange (One)
- ClusterClient.SetRange (Two)
- ClusterClient.SetWithOptions
- ClusterClient.Sort
- ClusterClient.SortReadOnly
- ClusterClient.SortReadOnlyWithOptions
- ClusterClient.SortStore
- ClusterClient.SortStoreWithOptions
- ClusterClient.SortWithOptions
- ClusterClient.Strlen
- ClusterClient.TTL
- ClusterClient.Time
- ClusterClient.TimeWithOptions
- ClusterClient.Touch
- ClusterClient.Type
- ClusterClient.Unlink
- ClusterClient.Unwatch
- ClusterClient.UnwatchWithOptions
- ClusterClient.UpdateConnectionPassword
- ClusterClient.Wait
- ClusterClient.Watch (ChangedKey)
- ClusterClient.Watch (UnchangedKey)
- ClusterClient.XAck
- ClusterClient.XAdd
- ClusterClient.XAddWithOptions
- ClusterClient.XAutoClaim
- ClusterClient.XAutoClaimJustId
- ClusterClient.XAutoClaimJustIdWithOptions
- ClusterClient.XAutoClaimWithOptions
- ClusterClient.XClaim
- ClusterClient.XClaimJustId
- ClusterClient.XClaimJustIdWithOptions
- ClusterClient.XClaimWithOptions
- ClusterClient.XDel
- ClusterClient.XGroupCreate
- ClusterClient.XGroupCreateConsumer
- ClusterClient.XGroupCreateWithOptions
- ClusterClient.XGroupDelConsumer
- ClusterClient.XGroupDestroy
- ClusterClient.XGroupSetId
- ClusterClient.XGroupSetIdWithOptions
- ClusterClient.XInfoConsumers
- ClusterClient.XInfoGroups
- ClusterClient.XInfoStream
- ClusterClient.XInfoStreamFullWithOptions
- ClusterClient.XLen
- ClusterClient.XPending
- ClusterClient.XPendingWithOptions
- ClusterClient.XRange
- ClusterClient.XRangeWithOptions
- ClusterClient.XRead
- ClusterClient.XReadGroup
- ClusterClient.XReadGroupWithOptions
- ClusterClient.XReadWithOptions
- ClusterClient.XRevRange
- ClusterClient.XRevRangeWithOptions
- ClusterClient.XTrim
- ClusterClient.ZAdd
- ClusterClient.ZAddIncr
- ClusterClient.ZAddIncrWithOptions
- ClusterClient.ZAddWithOptions
- ClusterClient.ZCard
- ClusterClient.ZCount
- ClusterClient.ZDiff
- ClusterClient.ZDiffStore
- ClusterClient.ZDiffWithScores
- ClusterClient.ZIncrBy
- ClusterClient.ZInter
- ClusterClient.ZInterCard
- ClusterClient.ZInterCardWithOptions
- ClusterClient.ZInterStore
- ClusterClient.ZInterStoreWithOptions
- ClusterClient.ZInterWithScores
- ClusterClient.ZLexCount
- ClusterClient.ZMPop
- ClusterClient.ZMPopWithOptions
- ClusterClient.ZMScore
- ClusterClient.ZPopMax
- ClusterClient.ZPopMaxWithOptions
- ClusterClient.ZPopMin
- ClusterClient.ZPopMinWithOptions
- ClusterClient.ZRandMember
- ClusterClient.ZRandMemberWithCount
- ClusterClient.ZRandMemberWithCountWithScores
- ClusterClient.ZRange
- ClusterClient.ZRangeStore
- ClusterClient.ZRangeWithScores
- ClusterClient.ZRank
- ClusterClient.ZRankWithScore
- ClusterClient.ZRem
- ClusterClient.ZRemRangeByLex
- ClusterClient.ZRemRangeByRank
- ClusterClient.ZRemRangeByScore
- ClusterClient.ZRevRank
- ClusterClient.ZRevRankWithScore
- ClusterClient.ZScan
- ClusterClient.ZScanWithOptions
- ClusterClient.ZScore
- ClusterClient.ZUnion
- ClusterClient.ZUnionStore
- ClusterClient.ZUnionStoreWithOptions
- ClusterClient.ZUnionWithScores
- NewClient
- NewClusterClient
- NewClusterClient (WithDatabaseId)
- OpenTelemetry
Constants ¶
const OK = "OK"
Variables ¶
var ( ErrPubSubPushInvalid = errors.New("received invalid push: empty or in incorrect format") ErrPubSubPushMissingKind = errors.New("received invalid push: missing kind field") ErrPubSubPushMissingValues = errors.New("received invalid push: missing values field") )
var AllChannels []string = nil
AllChannels represents "unsubscribe from all channels". Pass nil to Unsubscribe or UnsubscribeLazy to unsubscribe from all channels.
var AllPatterns []string = nil
AllPatterns represents "unsubscribe from all patterns". Pass nil to PUnsubscribe or PUnsubscribeLazy to unsubscribe from all patterns.
var AllShardedChannels []string = nil
AllShardedChannels represents "unsubscribe from all sharded channels". Pass nil to SUnsubscribe or SUnsubscribeLazy to unsubscribe from all sharded channels.
var SpanContextKey = spanContextKeyType{}
SpanContextKey is the default context key used to store Glide span pointers in context.Context. This key is used by WithSpan() and DefaultSpanFromContext() functions.
Functions ¶
func DefaultSpanFromContext ¶ added in v2.1.0
DefaultSpanFromContext is a default implementation of the SpanFromContext function that extracts span pointers stored using WithSpan().
This function can be used directly in OpenTelemetryConfig or as a reference for implementing custom span extraction logic.
Parameters:
- ctx: The context to extract the span pointer from
Returns:
- spanPtr: The span pointer if found, 0 if no parent span is available
Example usage:
config := glide.OpenTelemetryConfig{
Traces: &glide.OpenTelemetryTracesConfig{
Endpoint: "http://localhost:4318/v1/traces",
SamplePercentage: 10,
},
SpanFromContext: glide.DefaultSpanFromContext,
}
func ErrorsToString ¶
ErrorsToString converts a slice of errors into a single string.
func WithSpan ¶ added in v2.1.0
WithSpan stores a Glide span pointer in a context.Context for later retrieval. This is a helper function that users can use to attach span pointers to contexts for parent-child span relationships.
Parameters:
- ctx: The parent context
- spanPtr: A span pointer obtained from CreateSpan()
Returns:
- context.Context: A new context containing the span pointer
Example usage:
spanPtr, err := glide.GetOtelInstance().CreateSpan("user-operation")
if err != nil {
return err
}
defer glide.GetOtelInstance().EndSpan(spanPtr)
// Store span in context
ctx = glide.WithSpan(ctx, spanPtr)
// Now all Glide operations with this context will be child spans
result, err := client.Get(ctx, "key")
Types ¶
type BatchError ¶
type BatchError struct {
// contains filtered or unexported fields
}
func NewBatchError ¶
func NewBatchError(errs []error) *BatchError
func (*BatchError) Error ¶
func (e *BatchError) Error() string
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client used for connection to standalone servers. Use NewClient to request a client.
For full documentation refer to Valkey GLIDE Documentation.
Example (CompressionCustomLevel) ¶
This example demonstrates creating a client with a custom compression level and min size. It validates that values below the minimum size threshold are not compressed, while larger values are compressed and the compressed size is smaller than the original.
compressionConfig := config.NewCompressionConfiguration().
WithBackend(config.ZSTD).
WithCompressionLevel(10).
WithMinCompressionSize(256)
clientConfig := config.NewClientConfiguration().
WithAddress(&getStandaloneAddresses()[0]).
WithCompressionConfiguration(compressionConfig)
client, err := NewClient(clientConfig)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
defer client.Close()
// Capture statistics before operations
statsBefore := client.GetStatistics()
compressedCountBefore := statsBefore["total_values_compressed"]
skippedCountBefore := statsBefore["compression_skipped_count"]
// Only values >= 256 bytes will be compressed — this short value should be skipped
smallValue := "short"
result, err := client.Set(context.Background(), "small_key", smallValue)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
fmt.Println(result)
statsAfterSmall := client.GetStatistics()
fmt.Println("Small value compression skipped:",
statsAfterSmall["compression_skipped_count"] > skippedCountBefore)
fmt.Println("Small value was not compressed:",
statsAfterSmall["total_values_compressed"] == compressedCountBefore)
// Now send a large value that exceeds the 256-byte threshold
originalBytesBefore := statsAfterSmall["total_original_bytes"]
compressedBytesBefore := statsAfterSmall["total_bytes_compressed"]
largeValue := strings.Repeat("compressible data pattern ", 50) // ~1300 bytes
result, err = client.Set(context.Background(), "large_key", largeValue)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
fmt.Println(result)
statsAfterLarge := client.GetStatistics()
originalBytes := statsAfterLarge["total_original_bytes"] - originalBytesBefore
compressedBytes := statsAfterLarge["total_bytes_compressed"] - compressedBytesBefore
fmt.Println("Large value was compressed:",
statsAfterLarge["total_values_compressed"] > compressedCountBefore)
fmt.Println("Compressed bytes < original bytes:", compressedBytes < originalBytes)
Output: OK Small value compression skipped: true Small value was not compressed: true OK Large value was compressed: true Compressed bytes < original bytes: true
Example (CompressionLZ4) ¶
This example demonstrates creating a standalone client with LZ4 compression. It validates that compression actually reduces the data size using client statistics.
compressionConfig := config.NewCompressionConfiguration().
WithBackend(config.LZ4)
clientConfig := config.NewClientConfiguration().
WithAddress(&getStandaloneAddresses()[0]).
WithCompressionConfiguration(compressionConfig)
client, err := NewClient(clientConfig)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
defer client.Close()
// Capture statistics before the SET
statsBefore := client.GetStatistics()
originalBytesBefore := statsBefore["total_original_bytes"]
compressedBytesBefore := statsBefore["total_bytes_compressed"]
compressedCountBefore := statsBefore["total_values_compressed"]
value := strings.Repeat("data ", 200)
result, err := client.Set(context.Background(), "lz4_key", value)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
fmt.Println(result)
// Validate compression using client statistics
statsAfter := client.GetStatistics()
originalBytes := statsAfter["total_original_bytes"] - originalBytesBefore
compressedBytes := statsAfter["total_bytes_compressed"] - compressedBytesBefore
compressedCount := statsAfter["total_values_compressed"] - compressedCountBefore
fmt.Println("Value was compressed:", compressedCount > 0)
fmt.Println("Compressed bytes < original bytes:", compressedBytes < originalBytes)
Output: OK Value was compressed: true Compressed bytes < original bytes: true
Example (CompressionStatistics) ¶
This example demonstrates reading compression statistics from the client and validating that compressed bytes are smaller than the original value.
compressionConfig := config.NewCompressionConfiguration()
clientConfig := config.NewClientConfiguration().
WithAddress(&getStandaloneAddresses()[0]).
WithCompressionConfiguration(compressionConfig)
client, err := NewClient(clientConfig)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
defer client.Close()
// Capture statistics before the SET to isolate this operation's metrics
statsBefore := client.GetStatistics()
originalBytesBefore := statsBefore["total_original_bytes"]
compressedBytesBefore := statsBefore["total_bytes_compressed"]
// Perform a SET with a compressible value
value := strings.Repeat("statistics test ", 100)
_, err = client.Set(context.Background(), "stats_key", value)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
// Read compression statistics and validate compression occurred
stats := client.GetStatistics()
originalBytes := stats["total_original_bytes"] - originalBytesBefore
compressedBytes := stats["total_bytes_compressed"] - compressedBytesBefore
fmt.Println("total_values_compressed exists:", stats["total_values_compressed"] > 0)
fmt.Println("Compressed bytes < original bytes:", compressedBytes < originalBytes)
Output: total_values_compressed exists: true Compressed bytes < original bytes: true
Example (CompressionZSTD) ¶
This example demonstrates creating a standalone client with ZSTD compression enabled using default settings (level: default, min size: 64 bytes). It validates that compression actually reduces the data size using client statistics.
compressionConfig := config.NewCompressionConfiguration()
clientConfig := config.NewClientConfiguration().
WithAddress(&getStandaloneAddresses()[0]).
WithCompressionConfiguration(compressionConfig)
client, err := NewClient(clientConfig)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
defer client.Close()
// Capture statistics before the SET to isolate this operation's metrics
statsBefore := client.GetStatistics()
originalBytesBefore := statsBefore["total_original_bytes"]
compressedBytesBefore := statsBefore["total_bytes_compressed"]
compressedCountBefore := statsBefore["total_values_compressed"]
// Values >= 64 bytes will be automatically compressed before sending to the server
value := strings.Repeat("hello world ", 100) // ~1200 bytes, will be compressed
result, err := client.Set(context.Background(), "compressed_key", value)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
fmt.Println(result)
// Values are automatically decompressed on retrieval
retrieved, err := client.Get(context.Background(), "compressed_key")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
fmt.Println("Data integrity check:", retrieved.Value() == value)
// Validate compression using client statistics
statsAfter := client.GetStatistics()
originalBytes := statsAfter["total_original_bytes"] - originalBytesBefore
compressedBytes := statsAfter["total_bytes_compressed"] - compressedBytesBefore
compressedCount := statsAfter["total_values_compressed"] - compressedCountBefore
fmt.Println("Value was compressed:", compressedCount > 0)
fmt.Println("Compressed bytes < original bytes:", compressedBytes < originalBytes)
Output: OK Data integrity check: true Value was compressed: true Compressed bytes < original bytes: true
func NewClient ¶
func NewClient(config *config.ClientConfiguration) (*Client, error)
Creates a new Client instance and establishes a connection to a standalone Valkey server.
Parameters:
ctx - The context for controlling the command execution.
config - The configuration options for the client, including server addresses, authentication credentials,
TLS settings, database selection, reconnection strategy, and Pub/Sub subscriptions.
Return value:
A connected [Client] instance.
Remarks:
Use this static method to create and connect a `Client` to a standalone Valkey server.
The client will automatically handle connection establishment, including any authentication and TLS configurations.
- **Authentication**: If `ServerCredentials` are provided, the client will attempt to authenticate
using the specified username and password.
- **TLS**: If `UseTLS` is set to `true`, the client will establish a secure connection using TLS.
- **Reconnection Strategy**: The `BackoffStrategy` settings define how the client will attempt to reconnect
in case of disconnections.
- **Pub/Sub Subscriptions**: Predefine Pub/Sub channels and patterns to subscribe to upon connection establishment.
Example ¶
clientConf := config.NewClientConfiguration().
WithAddress(&getStandaloneAddresses()[0]).
WithUseTLS(false).
WithReconnectStrategy(config.NewBackoffStrategy(5, 1000, 2)).
WithDatabaseId(1).
WithSubscriptionConfig(
config.NewStandaloneSubscriptionConfig().
WithSubscription(config.PatternChannelMode, "news.*").
WithCallback(func(message *models.PubSubMessage, ctx any) {
fmt.Printf("Received message on '%s': %s", message.Channel, message.Message)
}, nil),
)
client, err := NewClient(clientConf)
if err != nil {
fmt.Println("Failed to create a client and connect: ", err)
}
fmt.Printf("Client created and connected: %T", client)
Output: Client created and connected: *glide.Client
func (*Client) AclCat ¶ added in v2.3.0
AclCat returns a list of all ACL categories.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
An array of ACL categories.
func (*Client) AclCatWithCategory ¶ added in v2.3.0
AclCatWithCategory returns a list of commands within the specified ACL category.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. category - The ACL category to list commands for.
Return value:
An array of commands within the specified category.
func (*Client) AclDelUser ¶ added in v2.3.0
AclDelUser deletes all specified ACL users and terminates their connections.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. usernames - An array of usernames to delete.
Return value:
The number of users deleted.
func (*Client) AclDryRun ¶ added in v2.3.0
func (client *Client) AclDryRun(ctx context.Context, username string, command string, args []string) (string, error)
AclDryRun simulates the execution of a command by a user without actually executing it.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. username - The username to simulate command execution for. command - The command to simulate. args - The command arguments.
Return value:
"OK" if the user can execute the command, otherwise a string describing why the command cannot be executed.
func (*Client) AclGenPass ¶ added in v2.3.0
AclGenPass generates a random password for ACL users.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
A randomly generated password string (64 hex characters by default).
func (*Client) AclGenPassWithBits ¶ added in v2.3.0
AclGenPassWithBits generates a random password with the specified number of bits.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. bits - The number of bits for the password (must be between 1 and 4096).
Return value:
A randomly generated password string.
func (*Client) AclGetUser ¶ added in v2.3.0
AclGetUser returns all ACL rules for the specified user.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. username - The username to get ACL rules for.
Return value:
A value describing the ACL rules for the user, or nil if user doesn't exist.
func (*Client) AclList ¶ added in v2.3.0
AclList returns a list of all ACL users and their rules in ACL configuration file format.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
An array of ACL rules for all users.
func (*Client) AclLoad ¶ added in v2.3.0
AclLoad reloads ACL rules from the configured ACL configuration file.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
"OK" on success.
func (*Client) AclLog ¶ added in v2.3.0
AclLog returns the ACL security events log.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
An array of ACL security events.
func (*Client) AclLogReset ¶ added in v2.3.0
AclLogReset resets the ACL log.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
"OK" on success.
func (*Client) AclLogWithCount ¶ added in v2.3.0
AclLogWithCount returns the specified number of ACL security events from the log.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. count - The number of entries to return.
Return value:
An array of ACL security events.
func (*Client) AclSave ¶ added in v2.3.0
AclSave saves the current ACL rules to the configured ACL configuration file.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
"OK" on success.
func (*Client) AclSetUser ¶ added in v2.3.0
func (client *Client) AclSetUser(ctx context.Context, username string, rules []string) (string, error)
AclSetUser creates or modifies an ACL user and its rules.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. username - The username for the ACL user. rules - An array of ACL rules to apply to the user.
Return value:
"OK" on success.
func (*Client) AclUsers ¶ added in v2.3.0
AclUsers returns a list of all ACL usernames.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
An array of ACL usernames.
func (*Client) AclWhoAmI ¶ added in v2.3.0
AclWhoAmI returns the username of the current connection.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
The username of the current connection.
func (*Client) Append ¶
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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the string. value - The value to append.
Return value:
The length of the string after appending the value.
Example ¶
var client *Client = getExampleClient() // example helper function
client.Set(context.Background(), "my_key", "my_valu")
result, err := client.Append(context.Background(), "my_key", "e")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
value, _ := client.Get(context.Background(), "my_key")
fmt.Println(value.Value())
Output: 8 my_value
func (*Client) BLMPop ¶
func (client *Client) BLMPop( ctx context.Context, keys []string, listDirection constants.ListDirection, timeout time.Duration, ) ([]models.KeyValues, error)
Blocks the connection until it pops one element from the first non-empty list from the provided keys. BLMPop is the blocking variant of Client.LMPop and ClusterClient.LMPop.
Note:
- When in cluster mode, all keys must map to the same hash slot.
- BLMPop is a client blocking command, see Blocking Commands for more details and best practices.
Since:
Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - An array of keys to lists. listDirection - The direction based on which elements are popped from - see [options.ListDirection]. timeout - The duration to wait for a blocking operation to complete. A value of 0 will block indefinitely.
Return value:
A slice of [models.KeyValues], each containing a key name and an array of popped elements. If no member could be popped and the timeout expired, returns `nil`.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.LPush(context.Background(), "my_list", []string{"one", "two", "three"})
result1, err := client.BLMPop(context.Background(), []string{"my_list"}, constants.Left, 100*time.Millisecond)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
jsonResult1, err := json.Marshal(result1)
fmt.Println(string(jsonResult1))
Output: 3 [{"Key":"my_list","Values":["three"]}]
func (*Client) BLMPopCount ¶
func (client *Client) BLMPopCount( ctx context.Context, keys []string, listDirection constants.ListDirection, count int64, timeout time.Duration, ) ([]models.KeyValues, error)
Blocks the connection until it pops one or more elements from the first non-empty list from the provided keys. BLMPopCount is the blocking variant of Client.LMPopCount ClusterClient.LMPopCount.
Note:
- When in cluster mode, all keys must map to the same hash slot.
- BLMPopCount is a client blocking command, see Blocking Commands for more details and best practices.
Since:
Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - An array of keys to lists. listDirection - The direction based on which elements are popped from - see [options.ListDirection]. count - The maximum number of popped elements. timeout - The duration to wait for a blocking operation to complete. A value of `0` will block
indefinitely.
Return value:
A slice of [models.KeyValues], each containing a key name and an array of popped elements. If no member could be popped and the timeout expired, returns `nil`.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.LPush(context.Background(), "my_list", []string{"one", "two", "three"})
result1, err := client.BLMPopCount(context.Background(), []string{"my_list"}, constants.Left, 2, 100*time.Millisecond)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
jsonResult1, err := json.Marshal(result1)
fmt.Println(string(jsonResult1))
Output: 3 [{"Key":"my_list","Values":["three","two"]}]
func (*Client) BLMove ¶
func (client *Client) BLMove( ctx context.Context, source string, destination string, whereFrom constants.ListDirection, whereTo constants.ListDirection, timeout time.Duration, ) (models.Result[string], error)
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 `whereFrom`. `BLMove` is the blocking variant of Client.LMove and ClusterClient.LMove.
Note:
- When in cluster mode, `source` and `destination` must map to the same hash slot.
- `BLMove` is a client blocking command, see Blocking Commands for more details and best practices.
Since:
Valkey 6.2.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. source - The key to the source list. destination - The key to the destination list. whereFrom - The ListDirection the element should be removed from. whereTo - The ListDirection the element should be added to. timeout - The duration to wait for a blocking operation to complete. A value of `0` will block indefinitely.
Return value:
A models.Result[string] containing the popped element or models.CreateNilStringResult() if `source` does not exist or if the operation timed-out.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.LPush(context.Background(), "my_list1", []string{"two", "one"})
result1, err := client.LPush(context.Background(), "my_list2", []string{"four", "three"})
result2, err := client.BLMove(
context.Background(),
"my_list1",
"my_list2",
constants.Left,
constants.Left,
100*time.Millisecond,
)
result3, err := client.LRange(context.Background(), "my_list1", 0, -1)
result4, err := client.LRange(context.Background(), "my_list2", 0, -1)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
Output: 2 2 {one false} [two] [one three four]
func (*Client) BLPop ¶
func (client *Client) BLPop(ctx context.Context, keys []string, timeout time.Duration) ([]string, error)
Pops 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.
Note:
- When in cluster mode, all keys must map to the same hash slot.
- BLPop is a client blocking command, see Blocking Commands for more details and best practices.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - The keys of the lists to pop from. timeout - The duration to wait for a blocking operation to complete. A value of 0 will block indefinitely.
Return value:
A two-element 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 `nil`.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.RPush(context.Background(), "list_a", []string{"a", "b", "c", "d", "e"})
result1, err := client.RPush(context.Background(), "list_b", []string{"f", "g", "h", "i", "j"})
result2, err := client.BLPop(context.Background(), []string{"list_a", "list_b"}, 500*time.Millisecond)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: 5 5 [list_a a]
func (*Client) BRPop ¶
func (client *Client) BRPop(ctx context.Context, keys []string, timeout time.Duration) ([]string, error)
Pops 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.
Note:
- When in cluster mode, all keys must map to the same hash slot.
- BRPop is a client blocking command, see Blocking Commands for more details and best practices.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - The keys of the lists to pop from. timeout - The duration to wait for a blocking operation to complete. A value of 0 will block indefinitely.
Return value:
A two-element 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 `nil`.
Example ¶
var client *Client = getExampleClient() // example helper function
client.Del(context.Background(), []string{"my_list", "list_a", "list_b"})
result, err := client.RPush(context.Background(), "list_a", []string{"a", "b", "c", "d", "e"})
result1, err := client.RPush(context.Background(), "list_b", []string{"f", "g", "h", "i", "j"})
result2, err := client.BRPop(context.Background(), []string{"list_a", "list_b"}, 500*time.Millisecond)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: 5 5 [list_a e]
func (*Client) BZMPop ¶
func (client *Client) BZMPop( ctx context.Context, keys []string, scoreFilter constants.ScoreFilter, timeout time.Duration, ) (models.Result[models.KeyWithArrayOfMembersAndScores], error)
Blocks the connection until it pops and returns a member-score pair from the first non-empty sorted set, with the given keys being checked in the order they are provided. BZMPop is the blocking variant of Client.ZMPop and ClusterClient.ZMPop.
Note:
- When in cluster mode, all keys must map to the same hash slot.
- BZMPop is a client blocking command, see Blocking Commands for more details and best practices.
Since:
Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - An array of keys to lists. scoreFilter - The element pop criteria - either [options.MIN] or [options.MAX] to pop members with the lowest/highest scores accordingly. timeout - The duration to wait for a blocking operation to complete. A value of `0` will block indefinitely.
Return value:
An object containing the following elements: - The key name of the set from which the element was popped. - An array of member scores of the popped elements. Returns `nil` if no member could be popped and the timeout expired.
Example ¶
var client *Client = getExampleClient() // example helper function
client.ZAdd(context.Background(), "key1", map[string]float64{"a": 1.0, "b": 2.0, "c": 3.0, "d": 4.0})
result, err := client.BZMPop(context.Background(), []string{"key1"}, constants.MAX, 500*time.Millisecond)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
jsonSummary, _ := json.Marshal(result.Value())
fmt.Println(string(jsonSummary))
Output: {"Key":"key1","MembersAndScores":[{"Member":"d","Score":4}]}
func (*Client) BZMPopWithOptions ¶
func (client *Client) BZMPopWithOptions( ctx context.Context, keys []string, scoreFilter constants.ScoreFilter, timeout time.Duration, opts options.ZMPopOptions, ) (models.Result[models.KeyWithArrayOfMembersAndScores], error)
Blocks the connection until it pops and returns a member-score pair from the first non-empty sorted set, with the given keys being checked in the order they are provided. BZMPop is the blocking variant of Client.ZMPop and ClusterClient.ZMPop.
Note:
- When in cluster mode, all keys must map to the same hash slot.
- BZMPop is a client blocking command, see Blocking Commands for more details and best practices.
Since:
Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - An array of keys to lists. scoreFilter - The element pop criteria - either [options.MIN] or [options.MAX] to pop members with the lowest/highest scores accordingly. count - The maximum number of popped elements. timeout - The duration to wait for a blocking operation to complete. A value of `0` will block indefinitely. opts - Pop options, see [options.ZMPopOptions].
Return value:
An object containing the following elements: - The key name of the set from which the element was popped. - An array of member scores of the popped elements. Returns `nil` if no member could be popped and the timeout expired.
Example ¶
var client *Client = getExampleClient() // example helper function
client.ZAdd(context.Background(), "key1", map[string]float64{"a": 1.0, "b": 2.0, "c": 3.0, "d": 4.0})
result, err := client.BZMPopWithOptions(
context.Background(),
[]string{"key1"},
constants.MAX,
100*time.Millisecond,
*options.NewZMPopOptions().SetCount(2),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
kms := models.KeyWithArrayOfMembersAndScores{
Key: "key1",
MembersAndScores: []models.MemberAndScore{
{Member: "d", Score: 4},
{Member: "c", Score: 3},
},
}
fmt.Println(kms.Key == result.Value().Key)
// isEqual := CompareUnorderedSlices[models.MemberAndScore](
// kms.MembersAndScores,
// result.Value().MembersAndScores,
// ) // helper function for comparing arrays and slices
// fmt.Println(isEqual)
Output: true
func (*Client) BZPopMax ¶
func (client *Client) BZPopMax( ctx context.Context, keys []string, timeout time.Duration, ) (models.Result[models.KeyWithMemberAndScore], error)
Blocks the connection until it pops and returns a member-score pair with the highest score from the first non-empty sorted set. The given `keys` being checked in the order they are provided. `BZPopMax` is the blocking variant of Client.ZPopMax and ClusterClient.ZPopMax.
Note:
- When in cluster mode, all keys must map to the same hash slot.
- `BZPopMax` is a client blocking command, see Blocking Commands for more details and best practices.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - An array of keys to check for elements. timeout - The maximum number of seconds to block (0 blocks indefinitely).
Return value:
A `models.KeyWithMemberAndScore` struct containing the key from which the member was popped, the popped member, and its score. If no element could be popped and the timeout expired, returns `nil`.
Example ¶
var client *Client = getExampleClient() // example helper function
// Add members to the sorted set
client.ZAdd(context.Background(), "mySortedSet", map[string]float64{"a": 1.0, "b": 2.0, "c": 3.0})
// Pop the highest-score member
res, err := client.BZPopMax(context.Background(), []string{"mySortedSet"}, 1.0)
if err != nil {
fmt.Println("Glide example failed with an error:", err)
return
}
value := res.Value()
fmt.Printf("{Key: %q, Member: %q, Score: %.1f}\n", value.Key, value.Member, value.Score)
Output: {Key: "mySortedSet", Member: "c", Score: 3.0}
func (*Client) BZPopMin ¶
func (client *Client) BZPopMin( ctx context.Context, keys []string, timeout time.Duration, ) (models.Result[models.KeyWithMemberAndScore], error)
Blocks the connection until it removes and returns a member-score pair with the lowest score from the first non-empty sorted set. The given `keys` being checked in the order they are provided. `BZPopMin` is the blocking variant of Client.BZPopMin and ClusterClient.BZPopMin.
Note:
- When in cluster mode, all `keys` must map to the same hash slot.
- `BZPopMin` is a client blocking command, see [Blocking Commands] for more details and best practices.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. keys - The keys of the sorted sets. timeout - The duration to wait for a blocking operation to complete. A value of `0` will block indefinitely.
Return value:
A `models.KeyWithMemberAndScore` struct 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 `nil`.
Example ¶
var client *Client = getExampleClient() // example helper function
zaddResult1, err := client.ZAdd(context.Background(), "key1", map[string]float64{"a": 1.0, "b": 1.5})
zaddResult2, err := client.ZAdd(context.Background(), "key2", map[string]float64{"c": 2.0})
result1, err := client.BZPopMin(context.Background(), []string{"key1", "key2"}, 500*time.Millisecond)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(zaddResult1)
fmt.Println(zaddResult2)
fmt.Println(result1)
Output: 2 1 {{key1 a 1} false}
func (*Client) BitCount ¶
Counts the number of set bits (population counting) in a string stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key for the string to count the set bits of.
Return value:
The number of set bits in the string. Returns `0` if the key is missing as it is treated as an empty string.
Example ¶
var client *Client = getExampleClient() // example helper function
client.SetBit(context.Background(), "my_key", 1, 1)
client.SetBit(context.Background(), "my_key", 2, 1)
result, err := client.BitCount(context.Background(), "my_key")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 2
func (*Client) BitCountWithOptions ¶
func (client *Client) BitCountWithOptions(ctx context.Context, key string, opts options.BitCountOptions) (int64, error)
Counts the number of set bits (population counting) in a string 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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key for the string to count the set bits of. options - The offset options - see [options.BitCountOptions].
Return value:
The number of set bits in the string interval specified by start, end, and options. Returns zero if the key is missing as it is treated as an empty string.
Example ¶
var client *Client = getExampleClient() // example helper function
options := options.NewBitCountOptions().
SetStart(1).
SetEnd(1).
SetBitmapIndexType(options.BYTE)
result, err := client.BitCountWithOptions(context.Background(), "my_key", *options)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 0
func (*Client) BitField ¶
func (client *Client) BitField( ctx context.Context, key string, subCommands []options.BitFieldSubCommands, ) ([]models.Result[int64], error)
Reads or modifies the array of bits representing the string that is held at key based on the specified sub commands.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
key - The key of the string.
subCommands - The subCommands to be performed on the binary value of the string at
key, which could be any of the following:
- [BitFieldGet].
- [BitFieldSet].
- [BitFieldIncrby].
- [BitFieldOverflow].
Use `options.NewBitFieldGet()` to specify a BitField GET command.
Use `options.NewBitFieldSet()` to specify a BitField SET command.
Use `options.NewBitFieldIncrby()` to specify a BitField INCRYBY command.
Use `options.BitFieldOverflow()` to specify a BitField OVERFLOW command.
Return value:
Result from the executed subcommands.
- BitFieldGet returns the value in the binary representation of the string.
- BitFieldSet returns the previous value before setting the new value in the binary representation.
- BitFieldIncrBy returns the updated value after increasing or decreasing the bits.
- BitFieldOverflow controls the behavior of subsequent operations and returns
a result based on the specified overflow type (WRAP, SAT, FAIL).
Example ¶
var client *Client = getExampleClient() // example helper function
commands := []options.BitFieldSubCommands{
options.NewBitFieldGet(options.SignedInt, 8, 16),
options.NewBitFieldOverflow(options.SAT),
options.NewBitFieldSet(options.UnsignedInt, 4, 0, 7),
options.NewBitFieldIncrBy(options.SignedInt, 5, 100, 1),
}
result, err := client.BitField(context.Background(), "mykey", commands)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [{0 false} {0 false} {1 false}]
func (*Client) BitFieldRO ¶
func (client *Client) BitFieldRO( ctx context.Context, key string, commands []options.BitFieldROCommands, ) ([]models.Result[int64], error)
Reads the array of bits representing the string that is held at key based on the specified sub commands.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
key - The key of the string.
subCommands - The read-only subCommands to be performed on the binary value
of the string at key, which could be:
- [BitFieldGet].
Use `options.NewBitFieldGet()` to specify a BitField GET command.
Return value:
Result from the executed GET subcommands. - BitFieldGet returns the value in the binary representation of the string.
Example ¶
var client *Client = getExampleClient() // example helper function
key := "mykey"
bfcommands := []options.BitFieldSubCommands{
options.NewBitFieldSet(options.UnsignedInt, 8, 0, 24),
}
client.BitField(context.Background(), key, bfcommands)
commands := []options.BitFieldROCommands{
options.NewBitFieldGet(options.UnsignedInt, 8, 0),
}
result, err := client.BitFieldRO(context.Background(), key, commands)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [{24 false}]
func (*Client) BitOp ¶
func (client *Client) BitOp( ctx context.Context, bitwiseOperation options.BitOpType, destination string, keys []string, ) (int64, error)
Perform a bitwise operation between multiple keys (containing string values) and store the result in the destination.
Note:
When in cluster mode, `destination` and all `keys` must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. bitwiseOperation - The bitwise operation to perform. destination - The key that will store the resulting string. keys - The list of keys to perform the bitwise operation on.
Return value:
The size of the string stored in destination.
Example ¶
var client *Client = getExampleClient()
bitopkey1 := "{bitop_test}key1"
bitopkey2 := "{bitop_test}key2"
destKey := "{bitop_test}dest"
// Set initial values
client.Set(context.Background(), bitopkey1, "foobar")
client.Set(context.Background(), bitopkey2, "abcdef")
// Perform BITOP AND
result, err := client.BitOp(context.Background(), options.AND, destKey, []string{bitopkey1, bitopkey2})
if err != nil {
fmt.Println("BitOp AND failed:", err)
} else {
fmt.Println("BitOp AND Result:", result)
}
// Perform BITOP OR
result, err = client.BitOp(context.Background(), options.OR, destKey, []string{bitopkey1, bitopkey2})
if err != nil {
fmt.Println("BitOp OR failed:", err)
} else {
fmt.Println("BitOp OR Result:", result)
}
// Perform BITOP XOR
result, err = client.BitOp(context.Background(), options.XOR, destKey, []string{bitopkey1, bitopkey2})
if err != nil {
fmt.Println("BitOp XOR failed:", err)
} else {
fmt.Println("BitOp XOR Result:", result)
}
// Perform BITOP NOT (only one source key allowed)
result, err = client.BitOp(context.Background(), options.NOT, destKey, []string{bitopkey1})
if err != nil {
fmt.Println("BitOp NOT failed:", err)
} else {
fmt.Println("BitOp NOT Result:", result)
}
Output: BitOp AND Result: 6 BitOp OR Result: 6 BitOp XOR Result: 6 BitOp NOT Result: 6
func (*Client) BitPos ¶
Returns the position of the first bit matching the given bit value.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the string. bit - The bit value to match. The value must be 0 or 1.
Return value:
The position of the first occurrence matching bit in the binary value of the string held at key. If bit is not found, a -1 is returned.
Example ¶
var client *Client = getExampleClient() // example helper function
client.SetBit(context.Background(), "my_key", 7, 1)
result, err := client.BitPos(context.Background(), "my_key", 1)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 7
func (*Client) BitPosWithOptions ¶
func (client *Client) BitPosWithOptions( ctx context.Context, key string, bit int64, bitposOptions options.BitPosOptions, ) (int64, error)
Returns the position of the first bit matching the given bit value.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the string. bit - The bit value to match. The value must be 0 or 1. bitposOptions - The [BitPosOptions] type.
Return value:
The position of the first occurrence matching bit in the binary value of the string held at key. If bit is not found, a -1 is returned.
Example ¶
var client *Client = getExampleClient() // example helper function
client.Set(context.Background(), "my_key", "\x00\x01\x00")
options := options.NewBitPosOptions().
SetStart(0).
SetEnd(1)
result, err := client.BitPosWithOptions(context.Background(), "my_key", 1, *options)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 15
func (*Client) ClientGetName ¶
Gets the name of the current connection.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
If a name is set, returns the name of the client connection as a models.Result[string]. Otherwise, returns [models.CreateNilStringResult()] if no name is assigned.
Example ¶
var client *Client = getExampleClient() // example helper function
connectionName := "ConnectionName-" + uuid.NewString()
client.ClientSetName(context.Background(), connectionName)
result, err := client.ClientGetName(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.Value() == connectionName)
Output: true
func (*Client) ClientId ¶
Gets the current connection id.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
The id of the client.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.ClientId(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
assert := result > 0
fmt.Println(assert)
Output: true
func (*Client) ClientSetName ¶
Set the name of the current connection.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. connectionName - Connection name of the current connection.
Return value:
OK - when connection name is set
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.ClientSetName(context.Background(), "ConnectionName")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*Client) Close ¶
func (client *Client) Close()
Close terminates the client by closing all associated resources.
func (*Client) ConfigGet ¶
Gets the values of configuration parameters.
Note:
Prior to Version 7.0.0, only one parameter can be send.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. args - A slice of configuration parameter names to retrieve values for.
Return value:
A map of values corresponding to the configuration parameters.
Example ¶
var client *Client = getExampleClient() // example helper function
client.ConfigSet(context.Background(), map[string]string{"timeout": "1000", "maxmemory": "1GB"}) // example configuration
result, err := client.ConfigGet(context.Background(), []string{"timeout", "maxmemory"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: map[maxmemory:1073741824 timeout:1000]
func (*Client) ConfigResetStat ¶
Resets the statistics reported by the server using the INFO and LATENCY HISTOGRAM.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
OK to confirm that the statistics were successfully reset.
Example ¶
var client *Client = getExampleClient() // example helper function
response, err := client.ConfigResetStat(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(response)
Output: OK
func (*Client) ConfigRewrite ¶
Rewrites the configuration file with the current configuration.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
"OK" when the configuration was rewritten properly, otherwise an error is thrown.
Example ¶
var client *Client = getExampleClient() // example helper function
opts := options.InfoOptions{Sections: []constants.Section{constants.Server}}
var resultRewrite string
response, err := client.InfoWithOptions(context.Background(), opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
lines := strings.Split(response, "\n")
var configFile string
for _, line := range lines {
if strings.HasPrefix(line, "config_file:") {
configFile = strings.TrimSpace(strings.TrimPrefix(line, "config_file:"))
break
}
}
if len(configFile) > 0 {
response, err = client.ConfigRewrite(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
resultRewrite = response
} else {
resultRewrite = "OK"
}
fmt.Println(resultRewrite)
Output: OK
func (*Client) ConfigSet ¶
Sets configuration parameters to the specified values.
Note:
Prior to Version 7.0.0, only one parameter can be send.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. parameters - A map consisting of configuration parameters and their respective values to set.
Return value:
`"OK"` if all configurations have been successfully set. Otherwise, raises an error.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.ConfigSet(
context.Background(),
map[string]string{"timeout": "1000", "maxmemory": "1GB"},
) // example configuration
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*Client) Copy ¶
Copies the value stored at the source to the destination key if the destination key does not yet exist.
Note:
When in cluster mode, both `source` and `destination` must map to the same hash slot.
Since:
Valkey 6.2.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. source - The key to the source value. destination - The key where the value should be copied to.
Return value:
`true` if source was copied, `false` if source was not copied.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.Set(context.Background(), "key1", "someValue")
result1, err := client.Copy(context.Background(), "key1", "key2")
result2, err := client.Get(context.Background(), "key2")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: OK true {someValue false}
func (*Client) CopyWithOptions ¶
func (client *Client) CopyWithOptions( ctx context.Context, source string, destination string, options options.CopyOptions, ) (bool, error)
Copies the value stored at the source to the destination key. When `replace` in `options` is `true`, removes the destination key first if it already exists, otherwise performs no action.
Note:
When in cluster mode, both `source` and `destination` must map to the same hash slot.
Since:
Valkey 6.2.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. source - The key to the source value. destination - The key where the value should be copied to. copyOptions - Set copy options with replace and DB destination-db
Return value:
`true` if source was copied, `false` if source was not copied.
Example ¶
var client *Client = getExampleClient() // example helper function
client.Set(context.Background(), "key1", "someValue")
opts := options.NewCopyOptions().SetReplace()
client.CopyWithOptions(context.Background(), "key1", "key2", *opts)
result, err := client.Get(context.Background(), "key2")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.Value())
Output: someValue
func (*Client) CustomCommand ¶
CustomCommand executes a single command, specified by args, without checking inputs. Every part of the command, including the command name and subcommands, should be added as a separate value in args. The returning value depends on the executed command.
See Valkey GLIDE Documentation for details on the restrictions and limitations of the custom command API.
This function should only be used for single-response commands. Commands that don't return complete response and awaits (such as SUBSCRIBE), or that return potentially more than a single response (such as XREAD), or that change the client's behavior (such as entering pub/sub mode on RESP2 connections) shouldn't be called using this function.
Parameters:
ctx - The context for controlling the command execution. args - Arguments for the custom command including the command name.
Return value:
The returned value for the custom command.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.CustomCommand(context.Background(), []string{"ping"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: PONG
func (*Client) DBSize ¶
Returns the number of keys in the currently selected database.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
The number of keys in the currently selected database.
Example ¶
var client *Client = getExampleClient() // example helper function
// Assume flushed client, so no keys are currently stored
client.Set(context.Background(), "key", "val")
result, err := client.DBSize(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 1
func (*Client) Decr ¶
Decrements the number stored at key by one. If key does not exist, it is set to 0 before performing the operation.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to decrement its value.
Return value:
The value of `key` after the decrement.
Example ¶
var client *Client = getExampleClient() // example helper function
client.Set(context.Background(), "my_key", "0")
result, err := client.Decr(context.Background(), "my_key")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: -1
func (*Client) DecrBy ¶
Decrements the number stored at code by amount. If key does not exist, it is set to 0 before performing the operation.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to decrement its value. amount - The amount to decrement.
Return value:
The value of `key` after the decrement.
Example ¶
var client *Client = getExampleClient() // example helper function
client.Set(context.Background(), "my_key", "20")
result, err := client.DecrBy(context.Background(), "my_key", 5)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 15
func (*Client) Del ¶
Del removes the specified keys from the database. A key is ignored if it does not exist.
Note:
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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - One or more keys to delete.
Return value:
Returns the number of keys that were removed.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.Set(context.Background(), "key1", "someValue")
result1, err := client.Set(context.Background(), "key2", "someValue")
result2, err := client.Del(context.Background(), []string{"key1", "key2", "key3"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: OK OK 2
func (*Client) Dump ¶
Serializes the value stored at key in a Valkey-specific format.
Parameters:
ctx - The context for controlling the command execution. key - The key to serialize.
Return value:
The serialized value of the data stored at key. If key does not exist, `nil` will be returned.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.Set(context.Background(), "key1", "someValue")
result1, err := client.Dump(context.Background(), "key1") // Contains serialized value of the data stored at key1
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1.IsNil())
Output: OK false
func (*Client) Echo ¶
Echo the provided message back.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. message - The provided message.
Return value:
The provided message
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.Echo(context.Background(), "Hello World")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: {Hello World false}
func (*Client) Exec ¶
func (client *Client) Exec(ctx context.Context, batch pipeline.StandaloneBatch, raiseOnError bool) ([]any, error)
Executes a batch by processing the queued commands.
See Valkey Transactions (Atomic Batches) and Valkey Pipelines (Non-Atomic Batches) for details.
Parameters:
ctx - The context for controlling the command execution batch - A `ClusterBatch` object containing a list of commands to be executed. raiseOnError - Determines how errors are handled within the batch response. When set to `true`, the first encountered error in the batch will be raised as an error after all retries and reconnections have been executed. When set to `false`, errors will be included as part of the batch response array, allowing the caller to process both successful and failed commands together. In this case, error details will be provided as instances of error.
Return value:
A list of results corresponding to the execution of each command in the batch. 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 `nil`. If the batch failed due to a `WATCH` command, `Exec` will return `nil`.
Example (Pipeline) ¶
var client *Client = getExampleClient() // example helper function
// Example 2: Non-Atomic Batch (Pipeline)
batch := pipeline.NewStandaloneBatch(false)
batch.Set("key1", "value1").Set("key2", "value2").Get("key1").Get("key2")
result, err := client.Exec(context.Background(), *batch, true)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [OK OK value1 value2]
Example (Transaction) ¶
var client *Client = getExampleClient() // example helper function
// Example 1: Atomic Batch (Transaction)
batch := pipeline.NewStandaloneBatch(true)
batch.Set("key", "1").CustomCommand([]string{"incr", "key"}).Get("key")
result, err := client.Exec(context.Background(), *batch, true)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [OK 2 2]
func (*Client) ExecWithOptions ¶
func (client *Client) ExecWithOptions( ctx context.Context, batch pipeline.StandaloneBatch, raiseOnError bool, options pipeline.StandaloneBatchOptions, ) ([]any, error)
Executes a batch by processing the queued commands.
See Valkey Transactions (Atomic Batches) and Valkey Pipelines (Non-Atomic Batches) for details.
Parameters:
ctx - The context for controlling the command execution batch - A `ClusterBatch` object containing a list of commands to be executed. raiseOnError - Determines how errors are handled within the batch response. When set to `true`, the first encountered error in the batch will be raised as an error after all retries and reconnections have been executed. When set to `false`, errors will be included as part of the batch response array, allowing the caller to process both successful and failed commands together. In this case, error details will be provided as instances of `RequestError`. options - A [StandaloneBatchOptions] object containing execution options.
Return value:
A list of results corresponding to the execution of each command in the batch. 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 `nil`. If the batch failed due to a `WATCH` command, `ExecWithOptions` will return `nil`.
Example (Pipeline) ¶
var client *Client = getExampleClient() // example helper function
// Example 2: Non-Atomic Batch (Pipeline)
batch := pipeline.NewStandaloneBatch(false)
batch.Set("key1", "value1").Set("key2", "value2").Get("key1").Get("key2")
// Set a timeout of 1000 milliseconds
options := pipeline.NewStandaloneBatchOptions().WithTimeout(1000 * time.Millisecond)
result, err := client.ExecWithOptions(context.Background(), *batch, false, *options)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [OK OK value1 value2]
Example (Transaction) ¶
var client *Client = getExampleClient() // example helper function
// Example 1: Atomic Batch (Transaction)
batch := pipeline.NewStandaloneBatch(true)
batch.Set("key", "1").CustomCommand([]string{"incr", "key"}).Get("key")
// Set a timeout of 1000 milliseconds
options := pipeline.NewStandaloneBatchOptions().WithTimeout(1000 * time.Millisecond)
result, err := client.ExecWithOptions(context.Background(), *batch, false, *options)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [OK 2 2]
func (*Client) Exists ¶
Exists returns the number of keys that exist in the database.
Note:
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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - One or more keys to check if they exist.
Return value:
Returns the number of existing keys.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.Set(context.Background(), "key1", "someValue")
result1, err := client.Set(context.Background(), "key2", "someValue")
result2, err := client.Exists(context.Background(), []string{"key1", "key2", "key3"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: OK OK 2
func (*Client) Expire ¶
func (client *Client) Expire(ctx context.Context, key string, expireTime time.Duration) (bool, error)
Expire sets a timeout on key. 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 expireTime is a 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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to expire. expireTime - Duration for the key to expire
Return value:
`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 ¶
var client *Client = getExampleClient() // example helper function
result, err := client.Set(context.Background(), "key", "someValue")
result1, err := client.ExpireAt(context.Background(), "key", time.Now().Add(1*time.Second))
result2, err := client.Expire(context.Background(), "key", 1*time.Second)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: OK true true
func (*Client) ExpireAt ¶
ExpireAt 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 If key already has an existing expire set, the time to live is updated to the new value. If expireTime is a 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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to expire. expireTime - The timestamp for expiry.
Return value:
`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 ¶
var client *Client = getExampleClient() // example helper function
result, err := client.Set(context.Background(), "key", "someValue")
result1, err := client.ExpireAt(context.Background(), "key", time.Now().Add(1*time.Second))
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK true
func (*Client) ExpireAtWithOptions ¶
func (client *Client) ExpireAtWithOptions( ctx context.Context, key string, expireTime time.Time, expireCondition constants.ExpireCondition, ) (bool, error)
ExpireAt 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 If key already has an existing expire set, the time to live is updated to the new value. If expireTime is a 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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to expire. expireTime - The timestamp for expiry. expireCondition - The option to set expiry - see [options.ExpireCondition].
Return value:
`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 ¶
var client *Client = getExampleClient() // example helper function
result, err := client.Set(context.Background(), "key", "someValue")
result1, err := client.ExpireAtWithOptions(
context.Background(),
"key",
time.Now().Add(1*time.Second),
constants.HasNoExpiry,
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK true
func (*Client) ExpireTime ¶
Expire Time returns the absolute Unix timestamp (since January 1, 1970) at which the given key will expire, in seconds.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to determine the expiration value of.
Return value:
The expiration Unix timestamp in seconds. `-2` if key does not exist or `-1` is key exists but has no associated expiration.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.Set(context.Background(), "key", "someValue")
result1, err := client.ExpireTime(context.Background(), "key")
_, err = client.ExpireAt(
context.Background(),
"key",
time.Now().Add(10*time.Second),
) // ExpireTime("key") returns proper unix timestamp in seconds
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK -1
func (*Client) ExpireWithOptions ¶
func (client *Client) ExpireWithOptions( ctx context.Context, key string, expireTime time.Duration, expireCondition constants.ExpireCondition, ) (bool, error)
Expire sets a timeout on key. 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 expireTime is a 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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to expire. expireTime - Duration for the key to expire expireCondition - The option to set expiry, see [options.ExpireCondition].
Return value:
`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 ¶
var client *Client = getExampleClient() // example helper function
result, err := client.Set(context.Background(), "key", "someValue")
result1, err := client.ExpireWithOptions(context.Background(), "key", 1*time.Second, constants.HasNoExpiry)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK true
func (*Client) FCall ¶
Invokes a previously loaded function. The command will be routed to a primary random node. To route to a replica please refer to Client.FCallReadOnly or ClusterClient.FCallReadOnly.
Since:
Valkey 7.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. function - The function name.
Return value:
The invoked function's return value.
Example ¶
FCall Examples
client := getExampleClient()
// Load function
_, err := client.FunctionLoad(context.Background(), libraryCode, true)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Call function
fcallResult, err := client.FCall(context.Background(), "myfunc")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(fcallResult)
Output: 42
func (*Client) FCallReadOnly ¶
Invokes a previously loaded read-only function. This command is routed depending on the client's {@link ReadFrom} strategy.
Since:
Valkey 7.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. function - The function name.
Return value:
The invoked function's return value.
Example ¶
client := getExampleClient()
// Load function
_, err := client.FunctionLoad(context.Background(), libraryCode, true)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Call function
fcallResult, err := client.FCallReadOnly(context.Background(), "myfunc")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(fcallResult)
Output: 42
func (*Client) FCallReadOnlyWithKeysAndArgs ¶
func (client *Client) FCallReadOnlyWithKeysAndArgs( ctx context.Context, function string, keys []string, args []string, ) (any, error)
Invokes a previously loaded read-only function. This command is routed depending on the client's {@link ReadFrom} strategy.
Note: When in cluster mode, all `keys` must map to the same hash slot.
Since:
Valkey 7.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. function - The function name. keys - An `array` of keys accessed by the function. To ensure the correct execution of functions, both in standalone and clustered deployments, all names of keys that a function accesses must be explicitly provided as `keys`. arguments - An `array` of `function` arguments. `arguments` should not represent names of keys.
Return value:
The invoked function's return value.
Example ¶
client := getExampleClient()
// Load function
_, err := client.FunctionLoad(context.Background(), libraryCodeWithArgs, true)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Call function
key1 := "{testKey}-" + uuid.New().String()
key2 := "{testKey}-" + uuid.New().String()
result, err := client.FCallReadOnlyWithKeysAndArgs(
context.Background(),
"myfunc",
[]string{key1, key2},
[]string{"3", "4"},
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 3
func (*Client) FCallWithKeysAndArgs ¶
func (client *Client) FCallWithKeysAndArgs( ctx context.Context, function string, keys []string, args []string, ) (any, error)
Invokes a previously loaded function. This command is routed to primary nodes only. To route to a replica please refer to Client.FCallReadOnly or ClusterClient.FCallReadOnly.
Since:
Valkey 7.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. function - The function name. keys - An `array` of keys accessed by the function. To ensure the correct execution of functions, both in standalone and clustered deployments, all names of keys that a function accesses must be explicitly provided as `keys`. arguments - An `array` of `function` arguments. `arguments` should not represent names of keys.
Return value:
The invoked function's return value.
Example ¶
client := getExampleClient()
// Load function
_, err := client.FunctionLoad(context.Background(), libraryCodeWithArgs, true)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Call function
key1 := "{testKey}-" + uuid.New().String()
key2 := "{testKey}-" + uuid.New().String()
result, err := client.FCallWithKeysAndArgs(context.Background(), "myfunc", []string{key1, key2}, []string{"3", "4"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 3
func (*Client) FlushAll ¶
FlushAll deletes all the keys of all the existing databases.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
`"OK"` response on success.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.FlushAll(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*Client) FlushAllWithOptions ¶
func (client *Client) FlushAllWithOptions(ctx context.Context, mode options.FlushMode) (string, error)
Deletes all the keys of all the existing databases.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. mode - The flushing mode, could be either [options.SYNC] or [options.ASYNC}.
Return value:
`"OK"` response on success.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.FlushAllWithOptions(context.Background(), options.ASYNC)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*Client) FlushDB ¶
Deletes all the keys of the currently selected database.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
`"OK"` response on success.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.FlushDB(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*Client) FlushDBWithOptions ¶
func (client *Client) FlushDBWithOptions(ctx context.Context, mode options.FlushMode) (string, error)
Deletes all the keys of the currently selected database.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. mode - The flushing mode, could be either [options.SYNC] or [options.ASYNC}.
Return value:
`"OK"` response on success.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.FlushDBWithOptions(context.Background(), options.SYNC)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*Client) FunctionDelete ¶
Deletes a library and all its functions.
Since:
Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. libName - The library name to delete.
Return value:
"OK" if the library exists, otherwise an error is thrown.
Example ¶
client := getExampleClient()
// Load a function first
_, err := client.FunctionLoad(context.Background(), libraryCode, true)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
// Delete function
result, err := client.FunctionDelete(context.Background(), "mylib")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*Client) FunctionDump ¶
Returns the serialized payload of all loaded libraries.
Since:
Valkey 7.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
The serialized payload of all loaded libraries.
Example ¶
client := getExampleClient()
// Call FunctionDump to get the serialized payload of all loaded libraries
dump, _ := client.FunctionDump(context.Background())
if len(dump) > 0 {
fmt.Println("Function dump got a payload")
}
Output: Function dump got a payload
func (*Client) FunctionFlush ¶
Deletes all function libraries.
Since:
Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
`OK`
Example ¶
FunctionFlush Examples
client := getExampleClient()
result, err := client.FunctionFlush(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*Client) FunctionFlushAsync ¶
Deletes all function libraries in asynchronous mode.
Since:
Valkey 7.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
`OK`
Example ¶
client := getExampleClient()
result, err := client.FunctionFlushAsync(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*Client) FunctionFlushSync ¶
Deletes all function libraries in synchronous mode.
Since:
Valkey 7.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
`OK`
Example ¶
client := getExampleClient()
result, err := client.FunctionFlushSync(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*Client) FunctionKill ¶
Kills a function that is currently executing.
`FUNCTION KILL` terminates read-only functions only.
Since:
Valkey 7.0 and above.
Note:
When in cluster mode, this command will be routed to all nodes.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
`OK` if function is terminated. Otherwise, throws an error.
Example ¶
client := getExampleClient()
// Try to kill when no function is running
_, err := client.FunctionKill(context.Background())
if err != nil {
fmt.Println("Expected error:", err)
}
Output: Expected error: An error was signalled by the server: - NotBusy: No scripts in execution right now.
func (*Client) FunctionList ¶
func (client *Client) FunctionList(ctx context.Context, query models.FunctionListQuery) ([]models.LibraryInfo, error)
Returns information about the functions and libraries.
Since:
Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. query - The query to use to filter the functions and libraries.
Return value:
A list of info about queried libraries and their functions.
Example ¶
client := getExampleClient()
// Load a function first
_, err := client.FunctionLoad(context.Background(), libraryCode, true)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
query := models.FunctionListQuery{
LibraryName: "mylib",
WithCode: true,
}
libs, err := client.FunctionList(context.Background(), query)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Printf("There are %d libraries loaded.\n", len(libs))
for i, lib := range libs {
fmt.Printf("%d) Library name '%s', on engine %s, with %d functions\n", i+1, lib.Name, lib.Engine, len(lib.Functions))
for j, fn := range lib.Functions {
fmt.Printf(" %d) function '%s'\n", j+1, fn.Name)
}
}
Output: There are 1 libraries loaded. 1) Library name 'mylib', on engine LUA, with 1 functions 1) function 'myfunc'
func (*Client) FunctionLoad ¶
func (client *Client) FunctionLoad(ctx context.Context, libraryCode string, replace bool) (string, error)
Loads a library to Valkey.
Since:
Valkey 7.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. libraryCode - The source code that implements the library. replace - Whether the given library should overwrite a library with the same name if it already exists.
Return value:
The library name that was loaded.
Example ¶
FunctionLoad Examples
client := getExampleClient()
result, err := client.FunctionLoad(context.Background(), libraryCode, true)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: mylib
func (*Client) FunctionRestore ¶
Restores libraries from the serialized payload returned by Client.FunctionDump.
Since:
Valkey 7.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. payload - The serialized data from [FunctionDump].
Return value:
`OK`
Example ¶
client := getExampleClient()
// Attempt to restore with invalid dump data
invalidDump := "invalid_dump_data"
_, err := client.FunctionRestore(context.Background(), invalidDump)
if err != nil {
fmt.Println("Error:", err.Error())
}
Output: Error: An error was signalled by the server: - ResponseError: DUMP payload version or checksum are wrong
func (*Client) FunctionRestoreWithPolicy ¶
func (client *Client) FunctionRestoreWithPolicy( ctx context.Context, payload string, policy constants.FunctionRestorePolicy, ) (string, error)
Restores libraries from the serialized payload returned by Client.FunctionDump.
Since:
Valkey 7.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. payload - The serialized data from [FunctionDump]. policy - A policy for handling existing libraries.
Return value:
`OK`
Example ¶
client := getExampleClient()
// Attempt to restore with invalid dump data and policy
invalidDump := "invalid_dump_data"
_, err := client.FunctionRestoreWithPolicy(context.Background(), invalidDump, constants.FlushPolicy)
if err != nil {
fmt.Println("Error:", err.Error())
}
Output: Error: An error was signalled by the server: - ResponseError: DUMP payload version or checksum are wrong
func (*Client) FunctionStats ¶
func (client *Client) FunctionStats(ctx context.Context) (map[string]models.FunctionStatsResult, error)
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.
Since:
Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
A map of node addresses to their function statistics represented by [models.FunctionStatsResult] object containing the following information: running_script - Information about the running script. engines - Information about available engines and their stats.
Example ¶
client := getExampleClient()
// Load a function first
_, err := client.FunctionLoad(context.Background(), libraryCode, true)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
// Get function statistics
stats, err := client.FunctionStats(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
// Print statistics for each node
for _, nodeStats := range stats {
fmt.Println("Example stats:")
for engineName, engine := range nodeStats.Engines {
fmt.Printf(" Engine %s: %d functions, %d libraries\n",
engineName, engine.FunctionCount, engine.LibraryCount)
}
}
Output: Example stats: Engine LUA: 1 functions, 1 libraries
func (*Client) GeoAdd ¶
func (client *Client) GeoAdd( ctx context.Context, key string, membersToGeospatialData map[string]options.GeospatialData, ) (int64, error)
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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. membersToGeospatialData - A map of member names to their corresponding positions. See [options.GeospatialData]. The command will report an error when index coordinates are out of the specified range.
Return value:
The number of elements added to the sorted set.
Example ¶
client := getExampleClient()
membersToCoordinates := map[string]options.GeospatialData{
"Palermo": {Longitude: 13.361389, Latitude: 38.115556},
"Catania": {Longitude: 15.087269, Latitude: 37.502669},
}
result, err := client.GeoAdd(context.Background(), uuid.New().String(), membersToCoordinates)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 2
func (*Client) GeoAddWithOptions ¶
func (client *Client) GeoAddWithOptions( ctx context.Context, key string, membersToGeospatialData map[string]options.GeospatialData, geoAddOptions options.GeoAddOptions, ) (int64, error)
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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. membersToGeospatialData - A map of member names to their corresponding positions. See [options.GeospatialData]. The command will report an error when index coordinates are out of the specified range. geoAddOptions - The options for the GeoAdd command, see - [options.GeoAddOptions].
Return value:
The number of elements added to the sorted set.
func (*Client) GeoDist ¶
func (client *Client) GeoDist( ctx context.Context, key string, member1 string, member2 string, ) (models.Result[float64], error)
Returns the distance between `member1` and `member2` saved in the geospatial index stored at `key`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. member1 - The name of the first member. member2 - The name of the second member.
Return value:
The distance between `member1` and `member2`. If one or both members do not exist, or if the key does not exist, returns `nil`. The default unit is meters, see - [options.Meters]
Example ¶
client := getExampleClient()
key := uuid.New().String()
member1 := "Palermo"
member2 := "Catania"
membersToCoordinates := map[string]options.GeospatialData{
"Palermo": {Longitude: 13.361389, Latitude: 38.115556},
"Catania": {Longitude: 15.087269, Latitude: 37.502669},
}
// Add the coordinates
_, err := client.GeoAdd(context.Background(), key, membersToCoordinates)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Test getting geodist for multiple members
result, err := client.GeoDist(context.Background(), key, member1, member2)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.Value())
Output: 166274.1516
func (*Client) GeoDistWithUnit ¶
func (client *Client) GeoDistWithUnit( ctx context.Context, key string, member1 string, member2 string, unit constants.GeoUnit, ) (models.Result[float64], error)
Returns the distance between `member1` and `member2` saved in the geospatial index stored at `key`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. member1 - The name of the first member. member2 - The name of the second member. unit - The unit of distance measurement - see [options.GeoUnit].
Return value:
The distance between `member1` and `member2`. If one or both members do not exist, or if the key does not exist, returns `nil`.
func (*Client) GeoHash ¶
func (client *Client) GeoHash(ctx context.Context, key string, members []string) ([]models.Result[string], error)
Returns the GeoHash strings representing the positions of all the specified `members` in the sorted set stored at the `key`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. members - The array of members whose GeoHash strings are to be retrieved.
Returns value:
An array of GeoHash strings (of type models.Result[string]) representing the positions of the specified members stored at key. If a member does not exist in the sorted set, a `nil` value is returned for that member.
Example ¶
client := getExampleClient()
key := uuid.New().String()
membersToCoordinates := map[string]options.GeospatialData{
"Palermo": {Longitude: 13.361389, Latitude: 38.115556},
"Catania": {Longitude: 15.087269, Latitude: 37.502669},
}
// Add the coordinates
_, err := client.GeoAdd(context.Background(), key, membersToCoordinates)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Test getting geohash for multiple members
geoHashResults, err := client.GeoHash(context.Background(), key, []string{"Palermo", "Catania"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(geoHashResults)
Output: [{sqc8b49rny0 false} {sqdtr74hyu0 false}]
func (*Client) GeoPos ¶
func (client *Client) GeoPos(ctx context.Context, key string, members []string) ([][]float64, error)
Returns the positions (longitude,latitude) of all the specified members of the geospatial index represented by the sorted set at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. members - The members of the sorted set.
Return value:
A 2D `array` which represent positions (longitude and latitude) corresponding to the given members. If a member does not exist, its position will be `nil`.
Example ¶
client := getExampleClient()
key := uuid.New().String()
_, err := client.GeoAdd(context.Background(), key, map[string]options.GeospatialData{
"Palermo": {Longitude: 13.361389, Latitude: 38.115556},
"Catania": {Longitude: 15.087269, Latitude: 37.502669},
})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
positions, err := client.GeoPos(context.Background(), key, []string{"Palermo", "Catania"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(positions)
Output: [[13.361389338970184 38.1155563954963] [15.087267458438873 37.50266842333162]]
func (*Client) GeoSearch ¶
func (client *Client) GeoSearch( ctx context.Context, key string, searchFrom options.GeoSearchOrigin, searchByShape options.GeoSearchShape, ) ([]string, error)
Returns the members of a sorted set populated with geospatial information using Client.GeoAdd or ClusterClient.GeoAdd, which are within the borders of the area specified by a given shape.
Since:
Valkey 6.2.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. searchFrom - 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. searchByShape - The query's shape options: - `BYRADIUS` to search inside circular area according to given radius. - `BYBOX` to search inside an axis-aligned rectangle, determined by height and width.
Return value:
An array of matched member names.
Example ¶
client := getExampleClient()
key := uuid.New().String()
AddInitialGeoData(client, key)
result, err := client.GeoSearch(context.Background(),
key,
&options.GeoMemberOrigin{Member: "Palermo"},
*options.NewCircleSearchShape(200, constants.GeoUnitKilometers),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [Palermo]
func (*Client) GeoSearchStore ¶
func (client *Client) GeoSearchStore( ctx context.Context, destinationKey string, sourceKey string, searchFrom options.GeoSearchOrigin, searchByShape options.GeoSearchShape, ) (int64, error)
Searches for members in a sorted set stored at `sourceKey` representing geospatial data within a circular or rectangular area and stores the result in `destinationKey`. If `destinationKey` already exists, it is overwritten. Otherwise, a new sorted set will be created. To get the result directly, see Client.GeoSearchWithFullOptions or ClusterClient.GeoSearchWithFullOptions.
Since:
Valkey 6.2.0 and above.
Note:
When in cluster mode, `destinationKey` and `sourceKey` must map to the same hash slot.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution.
destinationKey - The key of the sorted set to store the result.
sourceKey - The key of the sorted set to search.
searchFrom - 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.
searchByShape - The query's shape options:
- `BYRADIUS` to search inside circular area according to given radius.
- `BYBOX` to search inside an axis-aligned rectangle, determined by height and width.
Return value:
The number of elements in the resulting set.
Example ¶
client := getExampleClient()
source := uuid.New().String()
destination := uuid.New().String()
AddInitialGeoData(client, source)
result, err := client.GeoSearchStore(context.Background(),
destination,
source,
&options.GeoMemberOrigin{Member: "Palermo"},
*options.NewCircleSearchShape(200, constants.GeoUnitKilometers),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 1
func (*Client) GeoSearchStoreWithFullOptions ¶
func (client *Client) GeoSearchStoreWithFullOptions( ctx context.Context, destinationKey string, sourceKey string, searchFrom options.GeoSearchOrigin, searchByShape options.GeoSearchShape, resultOptions options.GeoSearchResultOptions, infoOptions options.GeoSearchStoreInfoOptions, ) (int64, error)
Searches for members in a sorted set stored at `sourceKey` representing geospatial data within a circular or rectangular area and stores the result in `destinationKey`. If `destinationKey` already exists, it is overwritten. Otherwise, a new sorted set will be created. To get the result directly, see Client.GeoSearchWithFullOptions or ClusterClient.GeoSearchWithFullOptions.
Since:
Valkey 6.2.0 and above.
Note:
When in cluster mode, `destinationKey` and `sourceKey` must map to the same hash slot.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. destinationKey - The key of the sorted set to store the result. sourceKey - The key of the sorted set to search. searchFrom - 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. searchByShape - The query's shape options: - `BYRADIUS` to search inside circular area according to given radius. - `BYBOX` to search inside an axis-aligned rectangle, determined by height and width. resultOptions - Optional inputs for sorting/limiting the results. infoOptions - The optional inputs to request additional information.
Return value:
The number of elements in the resulting set.
Example ¶
client := getExampleClient()
source := uuid.New().String()
destination := uuid.New().String()
AddInitialGeoData(client, source)
result, err := client.GeoSearchStoreWithFullOptions(context.Background(),
destination,
source,
&options.GeoMemberOrigin{Member: "Palermo"},
*options.NewCircleSearchShape(200, constants.GeoUnitKilometers),
*options.NewGeoSearchResultOptions().SetCount(1).SetSortOrder(options.DESC),
*options.NewGeoSearchStoreInfoOptions().SetStoreDist(true),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 1
func (*Client) GeoSearchStoreWithInfoOptions ¶
func (client *Client) GeoSearchStoreWithInfoOptions( ctx context.Context, destinationKey string, sourceKey string, searchFrom options.GeoSearchOrigin, searchByShape options.GeoSearchShape, infoOptions options.GeoSearchStoreInfoOptions, ) (int64, error)
Searches for members in a sorted set stored at `sourceKey` representing geospatial data within a circular or rectangular area and stores the result in `destinationKey`. If `destinationKey` already exists, it is overwritten. Otherwise, a new sorted set will be created. To get the result directly, see Client.GeoSearchWithFullOptions or ClusterClient.GeoSearchWithFullOptions.
Since:
Valkey 6.2.0 and above.
Note:
When in cluster mode, `destinationKey` and `sourceKey` must map to the same hash slot.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution.
destinationKey - The key of the sorted set to store the result.
sourceKey - The key of the sorted set to search.
searchFrom - 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.
searchByShape - The query's shape options:
- `BYRADIUS` to search inside circular area according to given radius.
- `BYBOX` to search inside an axis-aligned rectangle, determined by height and width.
infoOptions - The optional inputs to request additional information.
Return value:
The number of elements in the resulting set.
Example ¶
client := getExampleClient()
source := uuid.New().String()
destination := uuid.New().String()
AddInitialGeoData(client, source)
result, err := client.GeoSearchStoreWithInfoOptions(context.Background(),
destination,
source,
&options.GeoMemberOrigin{Member: "Palermo"},
*options.NewCircleSearchShape(200, constants.GeoUnitKilometers),
*options.NewGeoSearchStoreInfoOptions().SetStoreDist(true),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 1
func (*Client) GeoSearchStoreWithResultOptions ¶
func (client *Client) GeoSearchStoreWithResultOptions( ctx context.Context, destinationKey string, sourceKey string, searchFrom options.GeoSearchOrigin, searchByShape options.GeoSearchShape, resultOptions options.GeoSearchResultOptions, ) (int64, error)
Searches for members in a sorted set stored at `sourceKey` representing geospatial data within a circular or rectangular area and stores the result in `destinationKey`. If `destinationKey` already exists, it is overwritten. Otherwise, a new sorted set will be created. To get the result directly, see Client.GeoSearchWithFullOptions or ClusterClient.GeoSearchWithFullOptions.
Since:
Valkey 6.2.0 and above.
Note:
When in cluster mode, `destinationKey` and `sourceKey` must map to the same hash slot.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution.
destinationKey - The key of the sorted set to store the result.
sourceKey - The key of the sorted set to search.
searchFrom - 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.
searchByShape - The query's shape options:
- `BYRADIUS` to search inside circular area according to given radius.
- `BYBOX` to search inside an axis-aligned rectangle, determined by height and width.
resultOptions - Optional inputs for sorting/limiting the results.
Return value:
The number of elements in the resulting set.
Example ¶
client := getExampleClient()
source := uuid.New().String()
destination := uuid.New().String()
AddInitialGeoData(client, source)
result, err := client.GeoSearchStoreWithResultOptions(context.Background(),
destination,
source,
&options.GeoMemberOrigin{Member: "Palermo"},
*options.NewCircleSearchShape(200, constants.GeoUnitKilometers),
*options.NewGeoSearchResultOptions().SetCount(1).SetSortOrder(options.DESC),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 1
func (*Client) GeoSearchWithFullOptions ¶
func (client *Client) GeoSearchWithFullOptions( ctx context.Context, key string, searchFrom options.GeoSearchOrigin, searchByShape options.GeoSearchShape, resultOptions options.GeoSearchResultOptions, infoOptions options.GeoSearchInfoOptions, ) ([]options.Location, error)
Returns the members of a sorted set populated with geospatial information using Client.GeoAdd or ClusterClient.GeoAdd, which are within the borders of the area specified by a given shape.
Since:
Valkey 6.2.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. searchFrom - 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. searchByShape - The query's shape options: - `BYRADIUS` to search inside circular area according to given radius. - `BYBOX` to search inside an axis-aligned rectangle, determined by height and width. resultOptions - Optional inputs for sorting/limiting the results. infoOptions - The optional inputs to request additional information.
Return value:
An array of [options.Location] containing the following information: - The coordinates as a [options.GeospatialData] object. - The member (location) name. - The distance from the center as a `float64`, in the same unit specified for `searchByShape`. - The geohash of the location as a `int64`.
Example ¶
client := getExampleClient()
key := uuid.New().String()
AddInitialGeoData(client, key)
result, err := client.GeoSearchWithFullOptions(context.Background(),
key,
&options.GeoMemberOrigin{Member: "Palermo"},
*options.NewCircleSearchShape(200, constants.GeoUnitKilometers),
*options.NewGeoSearchResultOptions().SetCount(2).SetSortOrder(options.DESC),
*options.NewGeoSearchInfoOptions().SetWithDist(true).SetWithCoord(true).SetWithHash(true),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [{Palermo {38.1155563954963 13.361389338970184} 0 3479099956230698}]
func (*Client) GeoSearchWithInfoOptions ¶
func (client *Client) GeoSearchWithInfoOptions( ctx context.Context, key string, searchFrom options.GeoSearchOrigin, searchByShape options.GeoSearchShape, infoOptions options.GeoSearchInfoOptions, ) ([]options.Location, error)
Returns the members of a sorted set populated with geospatial information using Client.GeoAdd or ClusterClient.GeoAdd, which are within the borders of the area specified by a given shape.
Since:
Valkey 6.2.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. searchFrom - 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. searchByShape - The query's shape options: - `BYRADIUS` to search inside circular area according to given radius. - `BYBOX` to search inside an axis-aligned rectangle, determined by height and width. infoOptions - The optional inputs to request additional information.
Return value:
An array of [options.Location] containing the following information: - The coordinates as a [options.GeospatialData] object. - The member (location) name. - The distance from the center as a `float64`, in the same unit specified for `searchByShape`. - The geohash of the location as a `int64`.
Example ¶
client := getExampleClient()
key := uuid.New().String()
AddInitialGeoData(client, key)
result, err := client.GeoSearchWithInfoOptions(context.Background(),
key,
&options.GeoMemberOrigin{Member: "Palermo"},
*options.NewCircleSearchShape(200, constants.GeoUnitKilometers),
*options.NewGeoSearchInfoOptions().SetWithDist(true).SetWithCoord(true).SetWithHash(true),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [{Palermo {38.1155563954963 13.361389338970184} 0 3479099956230698}]
func (*Client) GeoSearchWithResultOptions ¶
func (client *Client) GeoSearchWithResultOptions( ctx context.Context, key string, searchFrom options.GeoSearchOrigin, searchByShape options.GeoSearchShape, resultOptions options.GeoSearchResultOptions, ) ([]string, error)
Returns the members of a sorted set populated with geospatial information using Client.GeoAdd or ClusterClient.GeoAdd, which are within the borders of the area specified by a given shape.
Since:
Valkey 6.2.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. searchFrom - 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. searchByShape - The query's shape options: - `BYRADIUS` to search inside circular area according to given radius. - `BYBOX` to search inside an axis-aligned rectangle, determined by height and width. resultOptions - Optional inputs for sorting/limiting the results.
Return value:
An array of matched member names.
Example ¶
client := getExampleClient()
key := uuid.New().String()
AddInitialGeoData(client, key)
result, err := client.GeoSearchWithResultOptions(context.Background(),
key,
&options.GeoMemberOrigin{Member: "Palermo"},
*options.NewCircleSearchShape(200, constants.GeoUnitKilometers),
*options.NewGeoSearchResultOptions().SetCount(1).SetSortOrder(options.DESC),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [Palermo]
func (*Client) Get ¶
Get string value associated with the given key, or models.CreateNilStringResult() is returned if no such key exists.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to be retrieved from the database.
Return value:
If key exists, returns the value of key as a String. Otherwise, return [models.CreateNilStringResult()].
Example (Keyexists) ¶
var client *Client = getExampleClient() // example helper function
client.Set(context.Background(), "my_key", "my_value")
result, err := client.Get(context.Background(), "my_key")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.Value())
Output: my_value
Example (Keynotexists) ¶
var client *Client = getExampleClient() // example helper function
result, err := client.Get(context.Background(), "my_key")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.IsNil()) // missing key returns nil result
Output: true
func (*Client) GetBit ¶
Returns the bit value at offset in the string value stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the string. offset - The index of the bit to return. Should be greater than or equal to zero.
Return value:
The bit at offset of the string. Returns zero if the key is empty or if the positive offset exceeds the length of the string.
Example ¶
var client *Client = getExampleClient() // example helper function
client.SetBit(context.Background(), "my_key", 1, 1)
result, err := client.GetBit(context.Background(), "my_key", 1)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 1
func (*Client) GetDel ¶
GetDel gets the value associated with the given key and deletes the key.
Parameters:
ctx - The context for controlling the command execution. key - The key to get and delete.
Return value:
If key exists, returns the value of the key as a String and deletes the key. If key does not exist, returns a [models.Result[string]](models.CreateNilStringResult()).
Example ¶
var client *Client = getExampleClient() // example helper function
client.Set(context.Background(), "my_key", "my_value")
result, err := client.GetDel(context.Background(), "my_key") // return value and delete key
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.Value())
value, _ := client.Get(context.Background(), "my_key") // key should be missing
fmt.Println(value.IsNil())
Output: my_value true
func (*Client) GetEx ¶
Get string value associated with the given key, or an empty string is returned [models.CreateNilStringResult()] if no such value exists.
Since:
Valkey 6.2.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to be retrieved from the database.
Return value:
If key exists, returns the value of key as a models.Result[string]. Otherwise, return [models.CreateNilStringResult()].
Example ¶
var client *Client = getExampleClient() // example helper function
client.Set(context.Background(), "my_key", "my_value")
result, err := client.GetEx(context.Background(), "my_key")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.Value())
ttl, _ := client.TTL(context.Background(), "my_key")
fmt.Println(ttl)
Output: my_value -1
func (*Client) GetExWithOptions ¶
func (client *Client) GetExWithOptions( ctx context.Context, key string, options options.GetExOptions, ) (models.Result[string], error)
Get string value associated with the given key and optionally sets the expiration of the key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to be retrieved from the database. options - The [options.GetExOptions].
Return value:
If key exists, returns the value of key as a models.Result[string]. Otherwise, return [models.CreateNilStringResult()].
Example ¶
var client *Client = getExampleClient() // example helper function
client.Set(context.Background(), "my_key", "my_value")
options := options.NewGetExOptions().
SetExpiry(options.NewExpiryIn(5 * time.Second))
result, err := client.GetExWithOptions(context.Background(), "my_key", *options)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.Value())
ttl, _ := client.TTL(context.Background(), "my_key")
fmt.Println(ttl)
Output: my_value 5
func (*Client) GetQueue ¶
func (client *Client) GetQueue() (*PubSubMessageQueue, error)
GetQueue returns the pub/sub queue for the client. GetQueue returns the pub/sub queue for the client. Returns an error if the client is configured with a callback.
func (*Client) GetRange ¶
Returns the substring of the string value stored at key, determined by the byte's 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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the string. start - The starting offset. end - The ending offset.
Return value:
A substring extracted from the value stored at key. Returns empty string if the offset is out of bounds.
Example (One) ¶
var client *Client = getExampleClient() // example helper function
client.Set(context.Background(), "my_key", "Welcome to Valkey Glide!")
result, err := client.GetRange(context.Background(), "my_key", 0, 7)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: Welcome
Example (Two) ¶
var client *Client = getExampleClient() // example helper function
client.Set(context.Background(), "my_key", "愛")
fmt.Println([]byte("愛")) // "愛" is a single character in UTF-8, but 3 bytes long
result, err := client.GetRange(context.Background(), "my_key", 0, 1)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println([]byte(result))
Output: [230 132 155] [230 132]
func (*Client) GetStatistics ¶ added in v2.3.0
GetStatistics retrieves compression, connection, and PubSub statistics for this client.
Return value:
A map[string]uint64 containing statistics: - total_connections: Total number of connections opened to Valkey - total_clients: Total number of GLIDE clients - total_values_compressed: Number of values successfully compressed - total_values_decompressed: Number of values successfully decompressed - total_original_bytes: Total bytes of original data before compression - total_bytes_compressed: Total bytes after compression - total_bytes_decompressed: Total bytes after decompression - compression_skipped_count: Number of times compression was skipped - subscription_out_of_sync_count: Number of times subscriptions were out of sync during reconciliation - subscription_last_sync_timestamp: Timestamp of last successful subscription sync (milliseconds since epoch)
func (*Client) GetSubscriptions ¶ added in v2.3.0
func (client *Client) GetSubscriptions(ctx context.Context) (*models.PubSubState, error)
GetSubscriptions retrieves both the desired and current subscription states. This allows verification of synchronization between what the client intends to be subscribed to (desired) and what it is actually subscribed to on the server (actual).
Parameters:
ctx - The context for the operation.
Return value:
A PubSubState containing desired and actual subscriptions, or an error.
Example:
state, err := client.GetSubscriptions(ctx)
if err != nil {
return err
}
// Check if subscribed to a channel
if _, ok := state.ActualSubscriptions[models.Exact]["channel1"]; ok {
fmt.Println("Subscribed to channel1")
}
func (*Client) HDel ¶
HDel removes the specified fields from the hash stored at key. Specified fields that do not exist within this hash are ignored. If key does not exist, it is treated as an empty hash and this command returns 0.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. fields - The fields to remove from the hash stored at key.
Return value:
The number of fields that were removed from the hash, not including specified but non-existing fields.
Example ¶
var client *Client = getExampleClient() // example helper function
fields := map[string]string{
"field1": "someValue",
"field2": "someOtherValue",
}
result, err := client.HSet(context.Background(), "my_hash", fields)
result1, err := client.HDel(context.Background(), "my_hash", []string{"field1", "field2"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 2 2
func (*Client) HExists ¶
HExists returns if field is an existing field in the hash stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. field - The field to check in the hash stored at key.
Return value:
A bool containing true if the hash contains the specified field. false if the hash does not contain the field, or if the key does not exist.
Example ¶
var client *Client = getExampleClient() // example helper function
fields := map[string]string{
"field1": "someValue",
"field2": "someOtherValue",
}
result, err := client.HSet(context.Background(), "my_hash", fields)
result1, err := client.HExists(context.Background(), "my_hash", "field1")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 2 true
func (*Client) HExpire ¶ added in v2.1.0
func (client *Client) HExpire( ctx context.Context, key string, expireTime time.Duration, fields []string, opts options.HExpireOptions, ) ([]int64, error)
Sets an expiration (TTL or time to live) on one or more fields of a given hash key. You must specify at least one field. Field(s) will automatically be deleted from the hash key when their TTLs expire. Field expirations will only be cleared by commands that delete or overwrite the contents of the hash fields, including HDEL and HSET commands. This means that all the operations that conceptually alter the value stored at a hash key's field without replacing it with a new one will leave the TTL untouched. You can clear the TTL of a specific field by specifying 0 for the `seconds` argument.
Note:
Calling HEXPIRE/HPEXPIRE with a time in the past will result in the hash field being deleted immediately.
Since:
Valkey 9.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. expireTime - The expiration time as a duration. fields - The fields to set expiration for. options - Optional arguments for the command, see [options.HExpireOptions].
Return value:
An array of integers indicating the result for each field: - -2: Field does not exist in the hash, or key does not exist. - 0: The specified condition was not met. - 1: The expiration time was applied. - 2: When called with 0 seconds.
Example ¶
// This command requires Valkey 9.0+
var client *Client = getExampleClient() // example helper function
// First set some fields
fields := map[string]string{
"field1": "value1",
"field2": "value2",
}
client.HSet(context.Background(), "my_hash", fields)
// Set 30 second expiration on fields
result, err := client.HExpire(
context.Background(),
"my_hash",
30*time.Second,
[]string{"field1", "field2"},
options.HExpireOptions{},
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result[0]) // 1 means expiration was set
fmt.Println(result[1]) // 1 means expiration was set
Output: 1 1
func (*Client) HExpireAt ¶ added in v2.1.0
func (client *Client) HExpireAt( ctx context.Context, key string, expireTime time.Time, fields []string, opts options.HExpireOptions, ) ([]int64, error)
Sets an expiration (TTL or time to live) on one or more fields of a given hash key using an absolute Unix timestamp. A timestamp in the past will delete the field immediately. Field(s) will automatically be deleted from the hash key when their TTLs expire.
Since:
Valkey 9.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. expireTime - The expiration time as a time.Time. fields - The fields to set expiration for. options - Optional arguments for the command, see [options.HExpireOptions].
Return value:
An array of integers indicating the result for each field: - -2: Field does not exist in the hash, or hash is empty. - 0: The specified condition was not met. - 1: The expiration time was applied. - 2: When called with 0 seconds or past Unix time.
func (*Client) HExpireTime ¶ added in v2.1.0
func (client *Client) HExpireTime(ctx context.Context, key string, fields []string) ([]int64, error)
Returns the absolute Unix timestamp in seconds since Unix epoch at which the given key's field(s) will expire.
Since:
Valkey 9.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. fields - The fields to get expiration time for.
Return value:
An array of integers indicating the expiration timestamp for each field in seconds: - Positive number: expiration timestamp. - -1: field exists but has no expiration. - -2: field doesn't exist.
func (*Client) HGet ¶
func (client *Client) HGet(ctx context.Context, key string, field string) (models.Result[string], error)
HGet returns the value associated with field in the hash stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. field - The field in the hash stored at key to retrieve from the database.
Return value:
The models.Result[string] associated with field, or [models.Result[string]](models.CreateNilStringResult()) when field is not present in the hash or key does not exist.
Example ¶
var client *Client = getExampleClient() // example helper function
fields := map[string]string{
"field1": "someValue",
"field2": "someOtherValue",
}
result, err := client.HSet(context.Background(), "my_hash", fields)
payload, err := client.HGet(context.Background(), "my_hash", "field1")
payload2, err := client.HGet(context.Background(), "my_hash", "nonexistent_field")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(payload)
fmt.Println(payload2.IsNil())
Output: 2 {someValue false} true
func (*Client) HGetAll ¶
HGetAll returns all fields and values of the hash stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash.
Return value:
A map of all fields and their values in the hash, or an empty map when key does not exist.
Example ¶
var client *Client = getExampleClient() // example helper function
fields := map[string]string{
"field1": "someValue",
"field2": "someOtherValue",
}
result, err := client.HSet(context.Background(), "my_hash", fields)
payload, err := client.HGetAll(context.Background(), "my_hash")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(payload["field1"])
fmt.Println(payload["field2"])
fmt.Println(payload["notExistentField"]) // prints nothing
Output: 2 someValue someOtherValue
func (*Client) HGetEx ¶ added in v2.1.0
func (client *Client) HGetEx( ctx context.Context, key string, fields []string, opts options.HGetExOptions, ) ([]models.Result[string], error)
Gets the values of one or more fields of a given hash key and optionally sets their expiration time or time-to-live (TTL).
Since:
Valkey 9.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. fields - The fields in the hash stored at key to retrieve from the database. options - Optional arguments for the command.
Return value:
An array of [models.Result[string]] 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 [models.CreateNilStringResult()] is returned. - If key does not exist, returns an empty string array.
Example ¶
// This command requires Valkey 9.0+
var client *Client = getExampleClient() // example helper function
// First set some fields
fields := map[string]string{
"field1": "value1",
"field2": "value2",
}
client.HSet(context.Background(), "my_hash", fields)
// Get fields and set 5 second expiration
options := options.NewHGetExOptions().SetExpiry(options.NewExpiryIn(5 * time.Second))
result, err := client.HGetEx(context.Background(), "my_hash", []string{"field1", "field2"}, options)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result[0].Value())
fmt.Println(result[1].Value())
Output: value1 value2
func (*Client) HIncrBy ¶
func (client *Client) HIncrBy(ctx context.Context, key string, field string, increment int64) (int64, error)
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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. field - The field in the hash stored at `key` to increment its value. increment - The amount to increment.
Return value:
The value of `field` in the hash stored at `key` after the increment.
Example ¶
var client *Client = getExampleClient() // example helper function
fields := map[string]string{
"field1": "10",
"field2": "14",
}
result, err := client.HSet(context.Background(), "my_hash", fields)
result1, err := client.HIncrBy(context.Background(), "my_hash", "field1", 1)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 2 11
func (*Client) HIncrByFloat ¶
func (client *Client) HIncrByFloat(ctx context.Context, key string, field string, increment float64) (float64, error)
Increments 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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. field - The field in the hash stored at `key` to increment its value. increment - The amount to increment.
Return value:
The value of `field` in the hash stored at `key` after the increment.
Example ¶
var client *Client = getExampleClient() // example helper function
fields := map[string]string{
"field1": "10",
"field2": "14",
}
result, err := client.HSet(context.Background(), "my_hash", fields)
result1, err := client.HIncrByFloat(context.Background(), "my_hash", "field1", 1.5)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 2 11.5
func (*Client) HKeys ¶
HKeys returns all field names in the hash stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash.
Return value:
A slice containing all the field names in the hash, or an empty slice when key does not exist.
Example ¶
var client *Client = getExampleClient() // example helper function
fields := map[string]string{
"field1": "someValue",
}
client.HSet(context.Background(), "my_hash", fields)
result, err := client.HKeys(context.Background(), "my_hash")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [field1]
func (*Client) HLen ¶
HLen returns the number of fields contained in the hash stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash.
Return value:
The number of fields in the hash, or `0` when key does not exist. If key holds a value that is not a hash, an error is returned.
Example ¶
var client *Client = getExampleClient() // example helper function
fields := map[string]string{
"field1": "someValue",
"field2": "someOtherValue",
}
result, err := client.HSet(context.Background(), "my_hash", fields)
result1, err := client.HLen(context.Background(), "my_hash")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 2 2
func (*Client) HMGet ¶
func (client *Client) HMGet(ctx context.Context, key string, fields []string) ([]models.Result[string], error)
HMGet returns the values associated with the specified fields in the hash stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. fields - The fields in the hash stored at key to retrieve from the database.
Return value:
An array of [models.Result[string]] 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 [models.CreateNilStringResult()] is returned. If key does not exist, returns an empty string array.
Example ¶
var client *Client = getExampleClient() // example helper function
fields := map[string]string{
"field1": "someValue",
"field2": "someOtherValue",
}
result, err := client.HSet(context.Background(), "my_hash", fields)
values, err := client.HMGet(context.Background(), "my_hash", []string{"field1", "field2"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(values[0])
fmt.Println(values[1])
Output: 2 {someValue false} {someOtherValue false}
func (*Client) HPExpire ¶ added in v2.1.0
func (client *Client) HPExpire( ctx context.Context, key string, expireTime time.Duration, fields []string, opts options.HExpireOptions, ) ([]int64, error)
Sets an expiration (TTL or time to live) on one or more fields of a given hash key. Field(s) will automatically be deleted from the hash key when their TTLs expire.
Since:
Valkey 9.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. expireTime - The expiration time as a duration. fields - The fields to set expiration for. options - Optional arguments for the command, see [options.HExpireOptions].
Return value:
An array of integers indicating the result for each field: - -2: Field does not exist in the hash, or hash is empty. - 0: The specified condition was not met. - 1: The expiration time was applied. - 2: When called with 0 milliseconds.
func (*Client) HPExpireAt ¶ added in v2.1.0
func (client *Client) HPExpireAt( ctx context.Context, key string, expireTime time.Time, fields []string, opts options.HExpireOptions, ) ([]int64, error)
Sets an expiration (TTL or time to live) on one or more fields of a given hash key using an absolute Unix timestamp. A timestamp in the past will delete the field immediately. Field(s) will automatically be deleted from the hash key when their TTLs expire.
Since:
Valkey 9.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. expireTime - The expiration time as a time.Time. fields - The fields to set expiration for. options - Optional arguments for the command, see [options.HExpireOptions].
Return value:
An array of integers indicating the result for each field: - -2: Field does not exist in the hash, or hash is empty. - 0: The specified condition was not met. - 1: The expiration time was applied. - 2: When called with 0 milliseconds or past Unix time.
func (*Client) HPExpireTime ¶ added in v2.1.0
func (client *Client) HPExpireTime(ctx context.Context, key string, fields []string) ([]int64, error)
Returns the absolute Unix timestamp in milliseconds since Unix epoch at which the given key's field(s) will expire.
Since:
Valkey 9.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. fields - The fields to get expiration time for.
Return value:
An array of integers indicating the expiration timestamp for each field in milliseconds: - Positive number: expiration timestamp. - -1: field exists but has no expiration. - -2: field doesn't exist.
func (*Client) HPTtl ¶ added in v2.1.0
Returns the remaining TTL (time to live) of a hash key's field(s) that have a set expiration, in milliseconds.
Since:
Valkey 9.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. fields - The fields to get TTL for.
Return value:
An array of integers indicating the TTL for each field in milliseconds: - Positive number: remaining TTL. - -1: field exists but has no expiration. - -2: field doesn't exist.
func (*Client) HPersist ¶ added in v2.1.0
Removes the existing expiration on a hash key's field(s), turning the field(s) from volatile (a field with expiration set) to persistent (a field that will never expire as no TTL (time to live) is associated).
Since:
Valkey 9.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. fields - The fields to remove expiration from.
Return value:
An array of integers indicating the result for each field: - -2: Field does not exist in the hash, or hash does not exist. - -1: Field exists but has no expiration. - 1: The expiration was successfully removed from the field.
Example ¶
// This command requires Valkey 9.0+
var client *Client = getExampleClient() // example helper function
// First set some fields with expiration
fields := map[string]string{
"field1": "value1",
"field2": "value2",
}
options := options.NewHSetExOptions().SetExpiry(options.NewExpiryIn(60 * time.Second))
client.HSetEx(context.Background(), "my_hash", fields, options)
// Remove expiration from fields
result, err := client.HPersist(context.Background(), "my_hash", []string{"field1", "field2"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result[0]) // 1 means expiration was removed
fmt.Println(result[1]) // 1 means expiration was removed
Output: 1 1
func (*Client) HRandField ¶
Returns a random field name from the hash value stored at `key`.
Since:
Valkey 6.2.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash.
Return value:
A random field name from the hash stored at `key`, or `nil` when the key does not exist.
Example ¶
var client *Client = getExampleClient() // example helper function
// For this example we only use 1 field to ensure consistent output
fields := map[string]string{
"field1": "someValue",
// other fields here...
}
client.HSet(context.Background(), "my_hash", fields)
result, err := client.HRandField(context.Background(), "my_hash")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: {field1 false}
func (*Client) HRandFieldWithCount ¶
func (client *Client) HRandFieldWithCount(ctx context.Context, key string, count int64) ([]string, error)
Retrieves up to `count` random field names from the hash value stored at `key`.
Since:
Valkey 6.2.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. count - The number of field names to return. If `count` is positive, returns unique elements. If negative, allows for duplicates.
Return value:
An array of random field names from the hash stored at `key`, or an empty array when the key does not exist.
Example ¶
var client *Client = getExampleClient() // example helper function
fields := map[string]string{
"field1": "someValue",
"field2": "someOtherValue",
}
client.HSet(context.Background(), "my_hash", fields)
result, err := client.HRandFieldWithCount(context.Background(), "my_hash", 2)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(len(result) == 2)
Output: true
func (*Client) HRandFieldWithCountWithValues ¶
func (client *Client) HRandFieldWithCountWithValues(ctx context.Context, key string, count int64) ([][]string, error)
Retrieves up to `count` random field names along with their values from the hash value stored at `key`.
Since:
Valkey 6.2.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. count - The number of field names to return. If `count` is positive, returns unique elements. If negative, allows for duplicates.
Return value:
A 2D `array` of `[field, value]` arrays, where `field` 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.
Example ¶
var client *Client = getExampleClient() // example helper function
fields := map[string]string{
"field1": "someValue",
"field2": "someOtherValue",
}
client.HSet(context.Background(), "my_hash", fields)
result, err := client.HRandFieldWithCountWithValues(context.Background(), "my_hash", 2)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(len(result) == 2)
Output: true
func (*Client) HScan ¶
func (client *Client) HScan(ctx context.Context, key string, cursor models.Cursor) (models.ScanResult, error)
Iterates fields of Hash types and their associated values. This definition of HSCAN command does not include the optional arguments of the command.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. cursor - The cursor that points to the next iteration of results.
Return value:
An object which holds the next cursor and the subset of the hash held by `key`. The cursor will return `false` from `IsFinished()` method on the last iteration of the subset. The data array in the result is always a flattened series of string pairs, where the hash field names are at even indices, and the hash field value are at odd indices.
Example ¶
var client *Client = getExampleClient() // example helper function
// For this example we only use 1 field to ensure a consistent output
fields := map[string]string{
"field1": "someValue",
// other fields here
}
client.HSet(context.Background(), "my_hash", fields)
result, err := client.HScan(context.Background(), "my_hash", models.NewCursor())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println("Cursor:", result.Cursor)
fmt.Println("Collection:", result.Data)
Output: Cursor: 0 Collection: [field1 someValue]
func (*Client) HScanWithOptions ¶
func (client *Client) HScanWithOptions( ctx context.Context, key string, cursor models.Cursor, options options.HashScanOptions, ) (models.ScanResult, error)
Iterates fields of Hash types and their associated values. This definition of HSCAN includes optional arguments of the command.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. cursor - The cursor that points to the next iteration of results. options - The [options.HashScanOptions].
Return value:
An object which holds the next cursor and the subset of the hash held by `key`. The cursor will return `false` from `IsFinished()` method on the last iteration of the subset. The data array in the result is always a flattened series of string pairs, where the hash field names are at even indices, and the hash field value are at odd indices.
Example ¶
var client *Client = getExampleClient() // example helper function
fields := map[string]string{
"a": "1",
"b": "2",
}
client.HSet(context.Background(), "my_hash", fields)
opts := options.NewHashScanOptions().SetMatch("a")
result, err := client.HScanWithOptions(context.Background(), "my_hash", models.NewCursor(), *opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println("Cursor:", result.Cursor)
fmt.Println("Collection:", result.Data)
// The collection only contains the hash map entry that matches with the match option provided with the command
Output: Cursor: 0 Collection: [a 1]
func (*Client) HSet ¶
func (client *Client) HSet(ctx context.Context, key string, values map[string]string) (int64, error)
HSet sets the specified fields to their respective values in the hash stored at key. This command overwrites the values of specified fields that exist in the hash. If key doesn't exist, a new key holding a hash is created.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. values - A map of field-value pairs to set in the hash.
Return value:
The number of fields that were added or updated.
Example ¶
var client *Client = getExampleClient() // example helper function
fields := map[string]string{
"field1": "someValue",
"field2": "someOtherValue",
}
result, err := client.HSet(context.Background(), "my_hash", fields)
result1, err := client.HGet(context.Background(), "my_hash", "field1")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 2 {someValue false}
func (*Client) HSetEx ¶ added in v2.1.0
func (client *Client) HSetEx( ctx context.Context, key string, fieldsAndValues map[string]string, opts options.HSetExOptions, ) (int64, error)
Sets the value of one or more fields of a given hash key, and optionally set their expiration time or time-to-live (TTL). This command overwrites the values and expirations of specified fields that exist in the hash. If `key` doesn't exist, a new key holding a hash is created.
Since:
Valkey 9.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. fieldsAndValues - A map of field-value pairs to set in the hash. options - Optional arguments for the command.
Return value:
- 1 if all fields were set successfully.
- 0 if no fields were set due to conditional restrictions.
Example ¶
// This command requires Valkey 9.0+
var client *Client = getExampleClient() // example helper function
fields := map[string]string{
"field1": "value1",
"field2": "value2",
}
// Set fields with 10 second expiration
options := options.NewHSetExOptions().SetExpiry(options.NewExpiryIn(10 * time.Second))
result, err := client.HSetEx(context.Background(), "my_hash", fields, options)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 1
func (*Client) HSetNX ¶
func (client *Client) HSetNX(ctx context.Context, key string, field string, value string) (bool, error)
HSetNX 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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. field - The field to set. value - The value to set.
Return value:
A bool containing true if field is a new field in the hash and value was set. false if field already exists in the hash and no operation was performed.
Example ¶
var client *Client = getExampleClient() // example helper function
fields := map[string]string{
"field1": "someValue",
"field2": "someOtherValue",
}
result, err := client.HSet(context.Background(), "my_hash", fields)
result1, err := client.HSetNX(context.Background(), "my_hash", "field3", "value")
payload, err := client.HGet(context.Background(), "my_hash", "field3")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(payload)
Output: 2 true {value false}
func (*Client) HStrLen ¶
HStrLen returns the string length of the value associated with field in the hash stored at key. If the key or the field do not exist, 0 is returned.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. field - The field to get the string length of its value.
Return value:
The length of the string value associated with field, or `0` when field or key do not exist.
Example ¶
var client *Client = getExampleClient() // example helper function
fields := map[string]string{
"field1": "someValue",
"field2": "someOtherValue",
}
result, err := client.HSet(context.Background(), "my_hash", fields)
result1, err := client.HStrLen(context.Background(), "my_hash", "field1")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 2 9
func (*Client) HTtl ¶ added in v2.1.0
Returns the remaining TTL (time to live) of a hash key's field(s) that have a set expiration.
Since:
Valkey 9.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. fields - The fields to get TTL for.
Return value:
An array of integers indicating the TTL for each field in seconds: - Positive number: remaining TTL. - -1: field exists but has no expiration. - -2: field doesn't exist.
Example ¶
// This command requires Valkey 9.0+
var client *Client = getExampleClient() // example helper function
// First set some fields with expiration
fields := map[string]string{
"field1": "value1",
"field2": "value2",
}
options := options.NewHSetExOptions().SetExpiry(options.NewExpiryIn(60 * time.Second))
client.HSetEx(context.Background(), "my_hash", fields, options)
// Get TTL for fields
result, err := client.HTtl(context.Background(), "my_hash", []string{"field1", "field2"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Printf("Field1 TTL > 0: %t\n", result[0] > 0)
fmt.Printf("Field2 TTL > 0: %t\n", result[1] > 0)
Output: Field1 TTL > 0: true Field2 TTL > 0: true
func (*Client) HVals ¶
HVals returns all values in the hash stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash.
Return value:
A slice containing all the values in the hash, or an empty slice when key does not exist.
Example ¶
var client *Client = getExampleClient() // example helper function
// For this example, we only use 1 field for consistent output
fields := map[string]string{
"field1": "someValue",
// other fields here
}
result, err := client.HSet(context.Background(), "my_hash", fields)
result1, err := client.HVals(context.Background(), "my_hash")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 1 [someValue]
func (*Client) Incr ¶
Increments the number stored at key by one. If key does not exist, it is set to 0 before performing the operation.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to increment its value.
Return value:
The value of `key` after the increment.
Example ¶
var client *Client = getExampleClient() // example helper function
client.Set(context.Background(), "my_key", "1")
result, err := client.Incr(context.Background(), "my_key")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 2
func (*Client) IncrBy ¶
Increments the number stored at key by amount. If key does not exist, it is set to 0 before performing the operation.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to increment its value. amount - The amount to increment.
Return value:
The value of `key` after the increment.
Example ¶
var client *Client = getExampleClient() // example helper function
client.Set(context.Background(), "my_key", "5")
result, err := client.IncrBy(context.Background(), "my_key", 5)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 10
func (*Client) IncrByFloat ¶
Increments 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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to increment its value. amount - The amount to increment.
Return value:
The value of key after the increment.
Example ¶
var client *Client = getExampleClient() // example helper function
client.Set(context.Background(), "my_key", "1")
result, err := client.IncrByFloat(context.Background(), "my_key", 5.5)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 6.5
func (*Client) Info ¶
Gets information and statistics about the server.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
A string with the information for the default sections.
Example ¶
var client *Client = getExampleClient() // example helper function
response, err := client.Info(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Printf("response is of type %T\n", response)
Output: response is of type string
func (*Client) InfoWithOptions ¶
func (client *Client) InfoWithOptions(ctx context.Context, options options.InfoOptions) (string, error)
Gets information and statistics about the server.
Note:
Starting from server version 7, command supports multiple section arguments.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. options - Additional command parameters, see [InfoOptions] for more details.
Return value:
A string containing the information for the sections requested.
Example ¶
var client *Client = getExampleClient() // example helper function
opts := options.InfoOptions{Sections: []constants.Section{constants.Server}}
response, err := client.InfoWithOptions(context.Background(), opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Printf("response is of type %T\n", response)
Output: response is of type string
func (*Client) InvokeScript ¶
Executes a Lua script on the server.
This function simplifies the process of invoking scripts on the server by using an object that represents a Lua script. The script loading 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.
See LOAD and EVALSHA for details.
Parameters:
ctx - The context for controlling the command execution. script - The Lua script to execute.
Return value:
The result of the script execution.
Example ¶
client := getExampleClient()
// Create a simple Lua script that returns a string
script := options.NewScript("return 'Hello from Lua'")
// Execute the script
result, err := client.InvokeScript(context.Background(), *script)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
fmt.Println(result)
Output: Hello from Lua
func (*Client) InvokeScriptWithOptions ¶
func (client *Client) InvokeScriptWithOptions( ctx context.Context, script options.Script, scriptOptions options.ScriptOptions, ) (any, error)
Executes a Lua script on the server with additional options.
This function simplifies the process of invoking scripts on the 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.
Note:
When in cluster mode: - all `keys` in `scriptOptions` must map to the same hash slot. - if no `keys` are given, command will be routed to a random primary node.
See LOAD and EVALSHA for details.
Parameters:
ctx - The context for controlling the command execution. script - The Lua script to execute. scriptOptions - Options for script execution including keys and arguments.
Return value:
The result of the script execution.
Example ¶
client := getExampleClient()
// Create a Lua script that uses keys and arguments
scriptText := `
local key = KEYS[1]
local value = ARGV[1]
redis.call('SET', key, value)
return redis.call('GET', key)
`
script := options.NewScript(scriptText)
// Create a unique key for testing
testKey := "test-key-" + uuid.New().String()
// Set up script options with keys and arguments
scriptOptions := options.NewScriptOptions().
WithKeys([]string{testKey}).
WithArgs([]string{"Hello World"})
// Execute the script with options
result, err := client.InvokeScriptWithOptions(context.Background(), *script, *scriptOptions)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
fmt.Println(result)
Output: Hello World
func (*Client) LCS ¶
Returns the longest common subsequence between strings stored at `key1` and `key2`.
Since:
Valkey 7.0 and above.
Note:
When in cluster mode, `key1` and `key2` must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key1 - The key that stores the first string. key2 - The key that stores the second string.
Return value:
A [models.LCSMatch] object containing: - `MatchString`: A string containing all the longest common subsequences combined between the 2 strings. An empty string is returned if the keys do not exist or have no common subsequences. - `Matches`: Empty array. - `Len`: 0
Example ¶
var client *Client = getExampleClient() // example helper function
client.MSet(context.Background(), map[string]string{"my_key1": "oh my gosh", "my_key2": "hello world"})
result, err := client.LCS(context.Background(), "my_key1", "my_key2")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.MatchString)
// LCS is only available in 7.0 and above. It will fail in any server < 7.0
Output: h o
func (*Client) LCSLen ¶
Returns the total length of all the longest common subsequences between strings stored at `key1` and `key2`.
Since:
Valkey 7.0 and above.
Note:
When in cluster mode, `key1` and `key2` must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key1 - The key that stores the first string. key2 - The key that stores the second string.
Return value:
A [models.LCSMatch] object containing: - `MatchString`: Empty string. - `Matches`: Empty array. - `Len`: The total length of all the longest common subsequences the 2 strings.
Example ¶
var client *Client = getExampleClient() // example helper function
client.Set(context.Background(), "my_key1", "ohmytext")
client.Set(context.Background(), "my_key2", "mynewtext")
result, err := client.LCSLen(context.Background(), "my_key1", "my_key2")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.Len)
// LCS is only available in 7.0 and above. It will fail in any server < 7.0
Output: 6
func (*Client) LCSWithOptions ¶
func (client *Client) LCSWithOptions( ctx context.Context, key1, key2 string, opts options.LCSIdxOptions, ) (*models.LCSMatch, error)
Returns the longest common subsequence between strings stored at `key1` and `key2`.
Since:
Valkey 7.0 and above.
Note:
When in cluster mode, `key1` and `key2` must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key1 - The key that stores the first string. key2 - The key that stores the second string. opts - The [LCSIdxOptions] type.
Return value:
A [models.LCSMatch] object containing: - `MatchString`: Empty string. - `Matches`: Array of [models.LCSMatchedPosition] objects with the common subsequences in the strings held by key1 and key2. If WithMatchLen is specified, the array also contains the length of each match, otherwise the length is 0. - `Len`: The total length of all the longest common subsequences the 2 strings.
Example (Basic) ¶
var client *Client = getExampleClient() // example helper function
client.Set(context.Background(), "my_key1", "ohmytext")
client.Set(context.Background(), "my_key2", "mynewtext")
// Basic LCS IDX without additional options
opts := options.NewLCSIdxOptions()
result, err := client.LCSWithOptions(context.Background(), "my_key1", "my_key2", *opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
jsonRes, _ := json.MarshalIndent(result, "", " ")
fmt.Println("Basic LCS result:\n", string(jsonRes))
// LCS is only available in 7.0 and above. It will fail in any server < 7.0
Output: Basic LCS result: { "MatchString": "", "Matches": [ { "Key1": { "Start": 4, "End": 7 }, "Key2": { "Start": 5, "End": 8 }, "MatchLen": 0 }, { "Key1": { "Start": 2, "End": 3 }, "Key2": { "Start": 0, "End": 1 }, "MatchLen": 0 } ], "Len": 6 }
Example (Minmatchlen) ¶
var client *Client = getExampleClient() // example helper function
client.Set(context.Background(), "my_key1", "ohmytext")
client.Set(context.Background(), "my_key2", "mynewtext")
// LCS IDX with MINMATCHLEN = 4
optsWithMin := options.NewLCSIdxOptions()
optsWithMin.SetMinMatchLen(4)
result2, err := client.LCSWithOptions(context.Background(), "my_key1", "my_key2", *optsWithMin)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
jsonRes2, _ := json.MarshalIndent(result2, "", " ")
fmt.Println("With MinMatchLen 4:\n", string(jsonRes2))
// LCS is only available in 7.0 and above. It will fail in any server < 7.0
Output: With MinMatchLen 4: { "MatchString": "", "Matches": [ { "Key1": { "Start": 4, "End": 7 }, "Key2": { "Start": 5, "End": 8 }, "MatchLen": 0 } ], "Len": 6 }
func (*Client) LIndex ¶
func (client *Client) LIndex(ctx context.Context, key string, index int64) (models.Result[string], error)
Returns the element at index from 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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list. index - The index of the element in the list to retrieve.
Return value:
The models.Result[string] containing element at index in the list stored at key. If index is out of range or if key does not exist, [models.CreateNilStringResult()] is returned.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.RPush(context.Background(), "my_list", []string{"a", "b", "c", "d", "e", "e", "e"})
result1, err := client.LIndex(context.Background(), "my_list", 3)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 7 {d false}
func (*Client) LInsert ¶
func (client *Client) LInsert( ctx context.Context, key string, insertPosition constants.InsertPosition, pivot string, element string, ) (int64, error)
Inserts element in the list at key either before or after the pivot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list. insertPosition - The relative position to insert into - either constants.Before or constants.After the pivot. pivot - An element of the list. element - The new element to insert.
Return value:
The list length after a successful insert operation. If the `key` doesn't exist returns `-1`. If the `pivot` wasn't found, returns `0`.
Example ¶
var client *Client = getExampleClient() // example helper function
client.Del(context.Background(), []string{"my_list"})
result, err := client.RPush(context.Background(), "my_list", []string{"hello", "world"})
result1, err := client.LInsert(context.Background(), "my_list", constants.Before, "world", "there")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 2 3
func (*Client) LLen ¶
Returns the length of the list stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list.
Return value:
The length of the list at `key`. If `key` does not exist, it is interpreted as an empty list and `0` is returned.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.RPush(context.Background(), "my_list", []string{"a", "b", "c", "d", "e", "e", "e"})
result1, err := client.LLen(context.Background(), "my_list")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 7 7
func (*Client) LMPop ¶
func (client *Client) LMPop( ctx context.Context, keys []string, listDirection constants.ListDirection, ) ([]models.KeyValues, error)
Pops one element from the first non-empty list from the provided keys.
Note:
When in cluster mode, `keys` must map to the same hash slot.
Since:
Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - An array of keys to lists. listDirection - The direction based on which elements are popped from - see [options.ListDirection].
Return value:
A slice of [models.KeyValues], each containing a key name and an array of popped elements. If no elements could be popped, returns 'nil'.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.LPush(context.Background(), "my_list", []string{"one", "two", "three"})
result1, err := client.LMPop(context.Background(), []string{"my_list"}, constants.Left)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
jsonResult1, err := json.Marshal(result1)
fmt.Println(string(jsonResult1))
Output: 3 [{"Key":"my_list","Values":["three"]}]
func (*Client) LMPopCount ¶
func (client *Client) LMPopCount( ctx context.Context, keys []string, listDirection constants.ListDirection, count int64, ) ([]models.KeyValues, error)
Pops one or more elements from the first non-empty list from the provided keys.
Note:
When in cluster mode, `keys` must map to the same hash slot.
Since:
Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - An array of keys to lists. listDirection - The direction based on which elements are popped from - see [options.ListDirection]. count - The maximum number of popped elements.
Return value:
A slice of [models.KeyValues], each containing a key name and an array of popped elements. If no elements could be popped, returns 'nil'.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.LPush(context.Background(), "my_list", []string{"one", "two", "three"})
result1, err := client.LMPopCount(context.Background(), []string{"my_list"}, constants.Left, 2)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
jsonResult1, err := json.Marshal(result1)
fmt.Println(string(jsonResult1))
Output: 3 [{"Key":"my_list","Values":["three","two"]}]
func (*Client) LMove ¶
func (client *Client) LMove( ctx context.Context, source string, destination string, whereFrom constants.ListDirection, whereTo constants.ListDirection, ) (models.Result[string], error)
Atomically pops 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`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. source - The key to the source list. destination - The key to the destination list. wherefrom - The ListDirection the element should be removed from. whereto - The ListDirection the element should be added to.
Return value:
A models.Result[string] containing the popped element or models.CreateNilStringResult() if source does not exist.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.LPush(context.Background(), "my_list1", []string{"two", "one"})
result1, err := client.LPush(context.Background(), "my_list2", []string{"four", "three"})
result2, err := client.LMove(context.Background(), "my_list1", "my_list2", constants.Left, constants.Left)
result3, err := client.LRange(context.Background(), "my_list1", 0, -1)
result4, err := client.LRange(context.Background(), "my_list2", 0, -1)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
Output: 2 2 {one false} [two] [one three four]
func (*Client) LPop ¶
Removes and returns the first elements of the list stored at key. The command pops a single element from the beginning of the list.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list.
Return value:
The models.Result[string] containing the value of the first element. If key does not exist, [models.CreateNilStringResult()] will be returned.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.LPush(context.Background(), "my_list", []string{"value1", "value2"})
result1, err := client.LPop(context.Background(), "my_list")
result2, err := client.LPop(context.Background(), "non_existent")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2.IsNil())
Output: 2 {value2 false} true
func (*Client) LPopCount ¶
Removes and returns up to `count` elements of the list stored at key, depending on the list's length.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list. count - The count of the elements to pop from the list.
Return value:
An array of the popped elements as strings will be returned depending on the list's length If key does not exist, nil will be returned.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.LPush(context.Background(), "my_list", []string{"value1", "value2"})
result1, err := client.LPopCount(context.Background(), "my_list", 2)
result2, err := client.LPop(context.Background(), "non_existent")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2.IsNil())
Output: 2 [value2 value1] true
func (*Client) LPos ¶
func (client *Client) LPos(ctx context.Context, key string, element string) (models.Result[int64], error)
Returns the index of the first occurrence of element inside the list specified by key. If no match is found, [models.CreateNilInt64Result()] is returned.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The name of the list. element - The value to search for within the list.
Return value:
The models.Result[int64] containing the index of the first occurrence of element, or [models.CreateNilInt64Result()] if element is not in the list.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.RPush(context.Background(), "my_list", []string{"a", "b", "c", "d", "e", "e"})
result1, err := client.LPos(context.Background(), "my_list", "e")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 6 {4 false}
func (*Client) LPosCount ¶
func (client *Client) LPosCount(ctx context.Context, key string, element string, count int64) ([]int64, error)
Returns an array of indices of matching elements within a list.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The name of the list. element - The value to search for within the list. count - The number of matches wanted.
Return value:
An array that holds the indices of the matching elements within the list.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.RPush(context.Background(), "my_list", []string{"a", "b", "c", "d", "e", "e", "e"})
result1, err := client.LPosCount(context.Background(), "my_list", "e", 3)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 7 [4 5 6]
func (*Client) LPosCountWithOptions ¶
func (client *Client) LPosCountWithOptions( ctx context.Context, key string, element string, count int64, opts options.LPosOptions, ) ([]int64, error)
Returns an array of indices of matching elements within a list based on the given options. If no match is found, an empty array is returned.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The name of the list. element - The value to search for within the list. count - The number of matches wanted. opts - The LPos options.
Return value:
An array that holds the indices of the matching elements within the list.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.RPush(context.Background(), "my_list", []string{"a", "b", "c", "d", "e", "e", "e"})
result1, err := client.LPosCountWithOptions(context.Background(), "my_list", "e", 1, *options.NewLPosOptions().SetRank(2))
result2, err := client.LPosCountWithOptions(context.Background(), "my_list", "e", 3,
*options.NewLPosOptions().SetRank(2).SetMaxLen(1000))
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: 7 [5] [5 6]
func (*Client) LPosWithOptions ¶
func (client *Client) LPosWithOptions( ctx context.Context, key string, element string, options options.LPosOptions, ) (models.Result[int64], error)
Returns the index of an occurrence of element within a list based on the given options. If no match is found, [models.CreateNilInt64Result()] is returned.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The name of the list. element - The value to search for within the list. options - The LPos options.
Return value:
The models.Result[int64] containing the index of element, or [models.CreateNilInt64Result()] if element is not in the list.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.RPush(context.Background(), "my_list", []string{"a", "b", "c", "d", "e", "e"})
result1, err := client.LPosWithOptions(context.Background(),
"my_list",
"e",
*options.NewLPosOptions().SetRank(2),
) // (Returns the second occurrence of the element "e")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 6 {5 false}
func (*Client) LPush ¶
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 an empty list before performing the push operation.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list. elements - The elements to insert at the head of the list stored at key.
Return value:
The length of the list after the push operation.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.LPush(context.Background(), "my_list", []string{"value1", "value2"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 2
func (*Client) LPushX ¶
Inserts all the specified values at the head of the list stored at key, only if key exists and holds a list. If key is not a list, this performs no operation.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list. elements - The elements to insert at the head of the list stored at key.
Return value:
The length of the list after the push operation.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.RPush(context.Background(), "my_list", []string{"value1"})
result1, err := client.LPushX(context.Background(), "my_list", []string{"value2", "value3"})
result2, err := client.LRange(context.Background(), "my_list", 0, -1)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: 1 3 [value3 value2 value1]
func (*Client) LRange ¶
func (client *Client) LRange(ctx context.Context, key string, start int64, end int64) ([]string, error)
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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list. start - The starting point of the range. end - The end of the range.
Return value:
Array of strings in the specified range. If start exceeds the end of the list, or if start is greater than end, an empty array 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 array will be returned.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.RPush(context.Background(), "my_list", []string{"a", "b", "c", "d", "e", "e", "e"})
result1, err := client.LRange(context.Background(), "my_list", 0, 2)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 7 [a b c]
func (*Client) LRem ¶
func (client *Client) LRem(ctx context.Context, key string, count int64, element string) (int64, error)
Removes the first count occurrences of elements equal to element from the list stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list. count - 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, it removes all elements equal to element. element - The element to remove from the list.
Return value:
The number of the removed elements. If `key` does not exist, `0` is returned.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.RPush(context.Background(), "my_list", []string{"a", "b", "c", "d", "e", "e", "e"})
result1, err := client.LRem(context.Background(), "my_list", 2, "e")
result2, err := client.LRange(context.Background(), "my_list", 0, -1)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: 7 2 [a b c d e]
func (*Client) LSet ¶
func (client *Client) LSet(ctx context.Context, key string, index int64, element string) (string, error)
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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list. index - The index of the element in the list to be set. element - The element to be set.
Return value:
`"OK"`.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.LPush(context.Background(), "my_list", []string{"one", "two", "three"})
result1, err := client.LSet(context.Background(), "my_list", 1, "someOtherValue")
result2, err := client.LRange(context.Background(), "my_list", 0, -1)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: 3 OK [three someOtherValue one]
func (*Client) LTrim ¶
func (client *Client) LTrim(ctx context.Context, key string, start int64, end int64) (string, error)
Trims 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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list. start - The starting point of the range. end - The end of the range.
Return value:
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, `"OK"` will be returned without changes to the database.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.RPush(context.Background(), "my_list", []string{"a", "b", "c", "d", "e", "e", "e"})
result1, err := client.LTrim(context.Background(), "my_list", 0, 4)
result2, err := client.LRange(context.Background(), "my_list", 0, -1)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: 7 OK [a b c d e]
func (*Client) LastSave ¶
Returns UNIX TIME of the last DB save timestamp or startup timestamp if no save was made since then.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
UNIX TIME of the last DB save executed with success.
Example ¶
var client *Client = getExampleClient() // example helper function
key := "key-" + uuid.NewString()
client.Set(context.Background(), key, "hello")
response, err := client.LastSave(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(response > 0)
Output: true
func (*Client) Lolwut ¶
Displays a piece of generative computer art of the specific Valkey version and it's optional arguments.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
A piece of generative computer art of that specific valkey version along with the Valkey version.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.Lolwut(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error:", err)
} else {
fmt.Printf("LOLWUT result is of type %T\n", result)
}
Output: LOLWUT result is of type string
func (*Client) LolwutWithOptions ¶
func (client *Client) LolwutWithOptions(ctx context.Context, opts options.LolwutOptions) (string, error)
Displays a piece of generative computer art of the specific Valkey version and it's optional arguments.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. opts - The [LolwutOptions] type.
Return value:
A piece of generative computer art of that specific valkey version along with the Valkey version.
Example ¶
var client *Client = getExampleClient() // example helper function
// Test with only version
opts := options.NewLolwutOptions(6)
result, err := client.LolwutWithOptions(context.Background(), *opts)
if err != nil {
fmt.Println("Glide example failed with an error:", err)
} else {
fmt.Printf("LOLWUT version result is of type %T\n", result)
}
// Test with version and arguments
opts = options.NewLolwutOptions(6).SetArgs([]int{10, 20})
result, err = client.LolwutWithOptions(context.Background(), *opts)
if err != nil {
fmt.Println("Glide example failed with an error:", err)
} else {
fmt.Printf("LOLWUT version with args result is of type %T\n", result)
}
Output: LOLWUT version result is of type string LOLWUT version with args result is of type string
func (*Client) MGet ¶
Retrieves the values of multiple keys.
Note:
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.
Parameters:
ctx - The context for controlling the command execution. keys - A list of keys to retrieve values for.
Return value:
An array of [models.Result[string]] values corresponding to the provided keys. If a key is not found, its corresponding value in the list will be a [models.CreateNilStringResult()].
Example ¶
var client *Client = getExampleClient() // example helper function
client.MSet(
context.Background(),
map[string]string{"my_key1": "my_value1", "my_key2": "my_value2", "my_key3": "my_value3"},
)
keys := []string{"my_key1", "my_key2", "my_key3"}
result, err := client.MGet(context.Background(), keys)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
for _, res := range result {
fmt.Println(res.Value())
}
Output: my_value1 my_value2 my_value3
func (*Client) MSet ¶
Sets multiple keys to multiple values in a single operation.
Note:
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.
Parameters:
ctx - The context for controlling the command execution. keyValueMap - A key-value map consisting of keys and their respective values to set.
Return value:
`"OK"` on success.
Example ¶
var client *Client = getExampleClient() // example helper function
keyValueMap := map[string]string{
"key1": "value1",
"key2": "value2",
}
result, err := client.MSet(context.Background(), keyValueMap)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*Client) MSetNX ¶
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.
Note:
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.
Parameters:
ctx - The context for controlling the command execution. keyValueMap - A key-value map consisting of keys and their respective values to set.
Return value:
A bool containing true, if all keys were set. false, if no key was set.
Example ¶
var client *Client = getExampleClient() // example helper function
keyValueMap := map[string]string{"my_key1": "my_value1", "my_key2": "my_value2"}
result, err := client.MSetNX(context.Background(), keyValueMap)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
client.Set(context.Background(), "my_key3", "my_value3")
result, _ = client.MSetNX(context.Background(), map[string]string{"my_key3": "my_value3"})
fmt.Println(result)
Output: true false
func (*Client) Move ¶
Move key from the currently selected database to the database specified by `dbIndex`.
Note:
In cluster mode move is available since Valkey 9.0.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to move. dbIndex - The index of the database to move key to.
Return value:
`true` if `key` was moved, or `false` if the `key` already exists in the destination database or does not exist in the source database.
Example ¶
var client *Client = getExampleClient() // example helper function
key := uuid.New().String()
_, err := client.Set(context.Background(), key, "hello")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
result, err := client.Move(context.Background(), key, 2)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: true
func (*Client) ObjectEncoding ¶
func (client *Client) ObjectEncoding(ctx context.Context, key string) (models.Result[string], error)
Returns the internal encoding for the Valkey object stored at key.
Parameters:
ctx - The context for controlling the command execution. key - The key of the object to get the internal encoding of.
Return value:
If key exists, returns the internal encoding of the object stored at key as a String. Otherwise, returns `null`.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.Set(context.Background(), "key1", "someValue")
result1, err := client.ObjectEncoding(context.Background(), "key1")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK {embstr false}
func (*Client) ObjectFreq ¶
Returns the logarithmic access frequency counter of a Valkey object stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the object to get the logarithmic access frequency counter of.
Return value:
If key exists, returns the logarithmic access frequency counter of the object stored at key as a long. Otherwise, returns `nil`.
Example ¶
var client *Client = getExampleClient() // example helper function
client.ConfigSet(context.Background(), map[string]string{"maxmemory-policy": "allkeys-lfu"}) // example configuration
client.Set(context.Background(), "key1", "someValue")
client.Set(context.Background(), "key1", "someOtherValue")
result, err := client.ObjectFreq(context.Background(), "key1")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: {6 false}
func (*Client) ObjectIdleTime ¶
Returns the logarithmic access frequency counter of a Valkey object stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the object to get the logarithmic access frequency counter of.
Return value:
If key exists, returns the idle time in seconds. Otherwise, returns `nil`.
Example ¶
var client *Client = getExampleClient() // example helper function
client.ConfigSet(context.Background(), map[string]string{"maxmemory-policy": "allkeys-lru"}) // example configuration
result, err := client.Set(context.Background(), "key1", "someValue")
result1, err := client.ObjectIdleTime(context.Background(), "key1")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK {0 false}
func (*Client) ObjectRefCount ¶
Returns the reference count of the object stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the object to get the reference count of.
Return value:
If key exists, returns the reference count of the object stored at key. Otherwise, returns `nil`.
Example ¶
var client *Client = getExampleClient() // example helper function
_, err := client.ConfigSet(
context.Background(),
map[string]string{"maxmemory-policy": "allkeys-lru"},
) // example configuration
result, err := client.Set(context.Background(), "key1", "someValue")
result1, err := client.ObjectRefCount(context.Background(), "key1")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK {1 false}
func (*Client) PExpire ¶
func (client *Client) PExpire(ctx context.Context, key string, expireTime time.Duration) (bool, error)
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 expireTime is a 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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to set timeout on it. expireTime - Duration for the key to expire.
Return value:
`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 ¶
var client *Client = getExampleClient() // example helper function
result, err := client.Set(context.Background(), "key", "someValue")
result1, err := client.PExpire(context.Background(), "key", 5000*time.Millisecond)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK true
func (*Client) PExpireAt ¶
func (client *Client) PExpireAt(ctx context.Context, key string, expireTime time.Time) (bool, error)
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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to set timeout on it. expireTime - The timestamp for expiry.
Return value:
`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 ¶
var client *Client = getExampleClient() // example helper function
result, err := client.Set(context.Background(), "key", "someValue")
result1, err := client.PExpireAt(context.Background(), "key", time.Now().Add(10000*time.Millisecond))
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK true
func (*Client) PExpireAtWithOptions ¶
func (client *Client) PExpireAtWithOptions( ctx context.Context, key string, expireTime time.Time, expireCondition constants.ExpireCondition, ) (bool, error)
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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to set timeout on it. expireTime - The timestamp for expiry. expireCondition - The option to set expiry, see [options.ExpireCondition].
Return value:
`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 ¶
var client *Client = getExampleClient() // example helper function
result, err := client.Set(context.Background(), "key", "someValue")
result1, err := client.PExpireAtWithOptions(
context.Background(),
"key",
time.Now().Add(10000*time.Millisecond),
constants.HasNoExpiry,
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK true
func (*Client) PExpireTime ¶
PExpire Time returns the absolute Unix timestamp (since January 1, 1970) at which the given key will expire, in milliseconds.
Parameters:
ctx - The context for controlling the command execution. key - The key to determine the expiration value of.
Return value:
The expiration Unix timestamp in milliseconds. `-2` if key does not exist or `-1` is key exists but has no associated expiration.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.Set(context.Background(), "key", "someValue")
result1, err := client.PExpireTime(context.Background(), "key")
_, err = client.PExpireAt(
context.Background(),
"key",
time.Now().Add(10000*time.Millisecond),
) // PExpireTime("key") returns proper unix time in milliseconds
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK -1
func (*Client) PExpireWithOptions ¶
func (client *Client) PExpireWithOptions( ctx context.Context, key string, expireTime time.Duration, expireCondition constants.ExpireCondition, ) (bool, error)
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 expireTime is a 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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to set timeout on it. expireTime - Duration for the key to expire option - The option to set expiry, see [options.ExpireCondition].
Return value:
`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 ¶
var client *Client = getExampleClient() // example helper function
result, err := client.Set(context.Background(), "key", "someValue")
result1, err := client.PExpireWithOptions(context.Background(), "key", 5000*time.Millisecond, constants.HasNoExpiry)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK true
func (*Client) PSubscribe ¶ added in v2.3.0
PSubscribe subscribes the client to the specified patterns (blocking). This command updates the client's internal desired subscription state and waits for server confirmation.
Parameters:
ctx - The context for the operation.
patterns - A slice of patterns to subscribe to (e.g., []string{"news.*"}).
timeoutMs - Maximum time in milliseconds to wait for server confirmation.
A value of 0 blocks indefinitely until confirmation.
Return value:
An error if the operation fails or times out.
Example:
err := client.PSubscribe(ctx, []string{"news.*"}, 5000)
func (*Client) PSubscribeBlocking ¶ added in v2.3.0
func (client *Client) PSubscribeBlocking(ctx context.Context, patterns []string, timeoutMs int) error
PSubscribeBlocking subscribes the client to the specified patterns (blocking). This command updates the client's internal desired subscription state and waits for server confirmation.
Parameters:
ctx - The context for the operation.
patterns - A slice of patterns to subscribe to.
timeoutMs - Maximum time in milliseconds to wait for server confirmation.
A value of 0 blocks indefinitely until confirmation.
Return value:
An error if the operation fails or times out.
Example:
err := client.PSubscribeBlocking(ctx, []string{"news.*"}, 5000)
func (*Client) PSubscribeLazy ¶ added in v2.3.0
PSubscribeLazy subscribes the client to the specified patterns (non-blocking). This command updates the client's internal desired subscription state without waiting for server confirmation. It returns immediately after updating the local state.
Parameters:
ctx - The context for the operation.
patterns - A slice of patterns to subscribe to (e.g., []string{"news.*"}).
Return value:
An error if the operation fails.
Example:
err := client.PSubscribeLazy(ctx, []string{"news.*", "updates.*"})
PSubscribeLazy subscribes the client to the specified patterns (non-blocking). This command updates the client's internal desired subscription state without waiting for server confirmation. It returns immediately after updating the local state. The client will attempt to subscribe asynchronously in the background.
Note: Use GetSubscriptions() to verify the actual server-side subscription state.
Parameters:
ctx - The context for the operation.
patterns - A slice of patterns to subscribe to (e.g., []string{"news.*"}).
Return value:
An error if the operation fails.
Example:
err := client.PSubscribeLazy(ctx, []string{"news.*", "updates.*"})
func (*Client) PTTL ¶
PTTL returns the remaining time to live of key that has a timeout, in milliseconds.
Parameters:
ctx - The context for controlling the command execution. key - The key to return its timeout.
Return value:
Returns TTL in milliseconds, `-2` if key does not exist, or `-1` if key exists but has no associated expiration.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.Set(context.Background(), "key", "someValue")
result1, err := client.PTTL(context.Background(), "key")
_, err = client.PExpireAt(
context.Background(),
"key",
time.Now().Add(10000*time.Millisecond),
) // PTTL("key") returns proper TTL in milliseconds
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK -1
func (*Client) PUnsubscribe ¶ added in v2.3.0
PUnsubscribe unsubscribes the client from the specified patterns (blocking). This command updates the client's internal desired subscription state and waits for server confirmation. If no patterns are specified (nil or empty slice), unsubscribes from all patterns.
Parameters:
ctx - The context for the operation.
patterns - A slice of patterns to unsubscribe from. Pass nil to unsubscribe from all.
timeoutMs - Maximum time in milliseconds to wait for server confirmation.
A value of 0 blocks indefinitely until confirmation.
Return value:
An error if the operation fails or times out.
Example:
err := client.PUnsubscribe(ctx, []string{"news.*"}, 5000)
err := client.PUnsubscribe(ctx, nil, 5000) // Unsubscribe from all
func (*Client) PUnsubscribeLazy ¶ added in v2.3.0
PUnsubscribeLazy unsubscribes the client from the specified patterns (non-blocking). This command updates the client's internal desired subscription state without waiting for server confirmation. It returns immediately after updating the local state. If no patterns are specified (nil), unsubscribes from all patterns.
Parameters:
ctx - The context for the operation. patterns - A slice of patterns to unsubscribe from. Pass nil to unsubscribe from all.
Return value:
An error if the operation fails.
Example:
err := client.PUnsubscribeLazy(ctx, []string{"news.*"})
err := client.PUnsubscribeLazy(ctx, nil) // Unsubscribe from all
func (*Client) Persist ¶
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:
ctx - The context for controlling the command execution. key - The key to remove the existing timeout on.
Return value:
`false` if key does not exist or does not have an associated timeout, `true` if the timeout has been removed.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.Set(context.Background(), "key1", "someValue")
result1, err := client.ExpireAt(context.Background(), "key1", time.Now().Add(10*time.Second))
result2, err := client.Persist(context.Background(), "key1")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: OK true true
func (*Client) PfAdd ¶
PfAdd 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. If key does not exist, then the HyperLogLog structure is created.
Parameters:
ctx - The context for controlling the command execution. key - The key of the HyperLogLog data structure to add elements into. elements - An array of members to add to the HyperLogLog stored at key.
Return value:
If the HyperLogLog is newly created, or if the HyperLogLog approximated cardinality is altered, then returns `true`. Otherwise, returns `false`.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.PfAdd(context.Background(), uuid.New().String(), []string{"value1", "value2", "value3"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: true
func (*Client) PfCount ¶
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.
Note:
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.
Parameters:
ctx - The context for controlling the command execution. key - The keys of the HyperLogLog data structures to be analyzed.
Return value:
The approximated cardinality of given HyperLogLog data structures. The cardinality of a key that does not exist is `0`.
Example ¶
var client *Client = getExampleClient() // example helper function
key := uuid.New().String()
result, err := client.PfAdd(context.Background(), key, []string{"value1", "value2", "value3"})
result1, err := client.PfCount(context.Background(), []string{key})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: true 3
func (*Client) PfMerge ¶
func (client *Client) PfMerge(ctx context.Context, destination string, sourceKeys []string) (string, error)
PfMerge 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.
Note:
When in cluster mode, `sourceKeys` and `destination` must map to the same hash slot.
Parameters:
ctx - The context for controlling the command execution. destination - The key of the destination HyperLogLog where the merged data sets will be stored. sourceKeys - An array of sourceKeys of the HyperLogLog structures to be merged.
Return value:
If the HyperLogLog values is successfully merged it returns "OK".
Example ¶
var client *Client = getExampleClient() // example helper function
// Create source keys with some values
sourceKey1 := uuid.New().String() + "{group}"
sourceKey2 := uuid.New().String() + "{group}"
// Add values to source keys
_, err := client.PfAdd(context.Background(), sourceKey1, []string{"value1", "value2"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
_, err = client.PfAdd(context.Background(), sourceKey2, []string{"value2", "value3", "value4"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
// Merge the source keys into a destination key
destKey := uuid.New().String() + "{group}"
result, err := client.PfMerge(context.Background(), destKey, []string{sourceKey1, sourceKey2})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
fmt.Println(result)
Output: OK
func (*Client) Ping ¶
Pings the server.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
Returns "PONG".
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.Ping(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: PONG
func (*Client) PingWithOptions ¶
func (client *Client) PingWithOptions(ctx context.Context, pingOptions options.PingOptions) (string, error)
Pings the server.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. pingOptions - The PingOptions type.
Return value:
Returns the copy of message.
Example ¶
var client *Client = getExampleClient() // example helper function
options := options.PingOptions{Message: "hello"}
result, err := client.PingWithOptions(context.Background(), options)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: hello
func (*Client) PubSubChannels ¶
Lists the currently active channels.
When used in cluster mode, the command is routed to all nodes and aggregates the responses into a single array.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
An array of active channel names.
Example ¶
var publisher *Client = getExampleClient() // example helper function
defer closeAllClients()
// Create subscribers with subscriptions
getExampleClientWithSubscription(config.ExactChannelMode, "channel1")
// Allow subscriptions to establish
time.Sleep(100 * time.Millisecond)
result, err := publisher.PubSubChannels(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [channel1]
func (*Client) PubSubChannelsWithPattern ¶
func (client *Client) PubSubChannelsWithPattern(ctx context.Context, pattern string) ([]string, error)
Lists the currently active channels matching the specified pattern.
Pattern can be any glob-style pattern: - h?llo matches hello, hallo and hxllo - h*llo matches hllo and heeeello - h[ae]llo matches hello and hallo, but not hillo
When used in cluster mode, the command is routed to all nodes and aggregates the responses into a single array.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. pattern - The pattern to match channel names against.
Return value:
An array of active channel names matching the pattern.
Example ¶
var publisher *Client = getExampleClient() // example helper function
defer closeAllClients()
// Create subscribers with subscriptions to different channels
getExampleClientWithSubscription(config.ExactChannelMode, "news.sports")
getExampleClientWithSubscription(config.ExactChannelMode, "news.weather")
getExampleClientWithSubscription(config.ExactChannelMode, "events.local")
// Allow subscriptions to establish
time.Sleep(100 * time.Millisecond)
// Get channels matching the "news.*" pattern
result, err := publisher.PubSubChannelsWithPattern(context.Background(), "news.*")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
sort.Strings(result)
fmt.Println(result)
Output: [news.sports news.weather]
func (*Client) PubSubNumPat ¶
Returns the number of patterns that are subscribed to by clients.
This returns the total number of unique patterns that all clients are subscribed to, not the count of clients subscribed to patterns.
When used in cluster mode, the command is routed to all nodes and aggregates the responses.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
The number of patterns that are subscribed to by clients.
Example ¶
var publisher *Client = getExampleClient() // example helper function
defer closeAllClients()
// Create subscribers with subscriptions
getExampleClientWithSubscription(config.PatternChannelMode, "news.*")
getExampleClientWithSubscription(config.PatternChannelMode, "events.*")
// Allow subscriptions to establish
time.Sleep(100 * time.Millisecond)
result, err := publisher.PubSubNumPat(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 2
func (*Client) PubSubNumSub ¶
func (client *Client) PubSubNumSub(ctx context.Context, channels ...string) (map[string]int64, error)
Returns the number of subscribers for the specified channels.
The count only includes clients subscribed to exact channels, not pattern subscriptions. If no channels are specified, an empty map is returned.
When used in cluster mode, the command is routed to all nodes and aggregates the responses into a single map.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. channels - The channel names to get subscriber counts for.
Return value:
A map of channel names to their subscriber counts.
Example ¶
var publisher *Client = getExampleClient() // example helper function
defer closeAllClients()
// Create subscribers with subscriptions to different channels
getExampleClientWithSubscription(config.ExactChannelMode, "news.sports")
getExampleClientWithSubscription(config.ExactChannelMode, "news.weather")
// Second subscriber to same channel
getExampleClientWithSubscription(config.ExactChannelMode, "news.weather")
getExampleClientWithSubscription(config.ExactChannelMode, "events.local")
// Allow subscriptions to establish
time.Sleep(100 * time.Millisecond)
// Get subscriber counts for specific channels
result, err := publisher.PubSubNumSub(context.Background(), "news.sports", "news.weather", "events.local")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Sort the channels for consistent output
channels := make([]string, 0, len(result))
for channel := range result {
channels = append(channels, channel)
}
sort.Strings(channels)
// Print results in sorted order
for _, channel := range channels {
fmt.Printf("%s: %d\n", channel, result[channel])
}
Output: events.local: 1 news.sports: 1 news.weather: 2
func (*Client) Publish ¶
Publish posts a message to the specified channel. Returns the number of clients that received the message.
Channel can be any string, but common patterns include using "." to create namespaces like "news.sports" or "news.weather".
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. channel - The channel to publish the message to. message - The message to publish.
Return value:
The number of clients that received the message.
Example ¶
var publisher *Client = getExampleClient() // example helper function
defer closeAllClients()
// Create a subscriber with subscription
subscriber := getExampleClientWithSubscription(config.ExactChannelMode, "my_channel")
queue, err := subscriber.GetQueue()
if err != nil {
fmt.Println("Failed to get queue: ", err)
return
}
// Allow subscription to establish
time.Sleep(100 * time.Millisecond)
// Publish a message
result, err := publisher.Publish(context.Background(), "my_channel", "Hello, World!")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
// Wait for and print the received message
msg := <-queue.WaitForMessage()
fmt.Println(msg.Message)
Output: 1 Hello, World!
func (*Client) RPop ¶
Removes and returns the last elements of the list stored at key. The command pops a single element from the end of the list.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list.
Return value:
The models.Result[string] containing the value of the last element. If key does not exist, [models.CreateNilStringResult()] will be returned.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.RPush(context.Background(), "my_list", []string{"a", "b", "c", "d", "e", "e", "e"})
result1, err := client.RPop(context.Background(), "my_list")
result2, err := client.RPop(context.Background(), "non_existing_key")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2.IsNil())
Output: 7 {e false} true
func (*Client) RPopCount ¶
Removes and returns up to count elements from the list stored at key, depending on the list's length.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list. count - The count of the elements to pop from the list.
Return value:
An array of popped elements as strings will be returned depending on the list's length. If key does not exist, nil will be returned.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.RPush(context.Background(), "my_list", []string{"a", "b", "c", "d", "e", "e", "e"})
result1, err := client.RPopCount(context.Background(), "my_list", 4)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 7 [e e e d]
func (*Client) RPush ¶
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 an empty list before performing the push operation.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list. elements - The elements to insert at the tail of the list stored at key.
Return value:
The length of the list after the push operation.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.RPush(context.Background(), "my_list", []string{"a", "b", "c", "d", "e", "e", "e"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 7
func (*Client) RPushX ¶
Inserts all the specified values at the tail of the list stored at key, only if key exists and holds a list. If key is not a list, this performs no operation.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list. elements - The elements to insert at the tail of the list stored at key.
Return value:
The length of the list after the push operation.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.RPush(context.Background(), "my_list", []string{"value1"})
result1, err := client.RPushX(context.Background(), "my_list", []string{"value2", "value3"})
result2, err := client.LRange(context.Background(), "my_list", 0, -1)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: 1 3 [value1 value2 value3]
func (*Client) RandomKey ¶
Returns a random existing key name from the currently selected database.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
A random existing key name from the currently selected database.
Example ¶
var client *Client = getExampleClient() // example helper function
key := uuid.New().String()
client.Set(context.Background(), key, "Hello")
result, err := client.RandomKey(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(len(result.Value()) > 0)
Output: true
func (*Client) RefreshIamToken ¶ added in v2.2.0
RefreshIamToken manually refreshes the IAM authentication token for the current connection.
This method is only available if the client was created with IAM authentication (using [ServerCredentials] with [IamAuthConfig]). It triggers an immediate refresh of the IAM token and updates the connection with the new token.
Normally, IAM tokens are refreshed automatically based on the refresh interval configured in [IamAuthConfig]. Use this method when you need to force an immediate token refresh, such as when credentials have been rotated or when troubleshooting authentication issues.
Parameters:
ctx - The context for controlling the command execution and cancellation.
Return value:
Returns "OK" on successful token refresh.
Errors:
Returns an error if: - The client was not configured with IAM authentication - The token refresh operation fails - The context is cancelled - The client is closed
Example:
// Create client with IAM authentication
iamConfig := config.NewIamAuthConfig("my-cluster", config.ElastiCache, "us-east-1")
creds, _ := config.NewServerCredentialsWithIam("myuser", iamConfig)
clientConfig := config.NewClientConfiguration().WithCredentials(creds)
client, _ := glide.NewClient(clientConfig)
// Manually refresh the token
result, err := client.RefreshIamToken(context.Background())
if err != nil {
log.Printf("Token refresh failed: %v", err)
return
}
log.Printf("Token refreshed: %s", result) // "OK"
See also: [IamAuthConfig], [ServerCredentials], [NewServerCredentialsWithIam]
func (*Client) Rename ¶
Renames `key` to `newKey`. If `newKey` already exists it is overwritten.
Note:
When in cluster mode, both `key` and `newKey` must map to the same hash slot.
Parameters:
ctx - The context for controlling the command execution. key - The key to rename. newKey - The new name of the key.
Return value:
If the key was successfully renamed, return "OK". If key does not exist, an error is thrown.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.Set(context.Background(), "key1", "someValue")
result1, err := client.Rename(context.Background(), "key1", "key2")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK OK
func (*Client) RenameNX ¶
Renames `key` to `newkey` if `newKey` does not yet exist.
Note:
When in cluster mode, both `key` and `newkey` must map to the same hash slot.
Parameters:
ctx - The context for controlling the command execution. key - The key to rename. newKey - The new name of the key.
Return value:
`true` if key was renamed to `newKey`, `false` if `newKey` already exists.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.Set(context.Background(), "key1", "someValue")
result1, err := client.RenameNX(context.Background(), "key1", "key2")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK true
func (*Client) ResetConnectionPassword ¶
Update the current connection by removing the 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.
Note:
This method updates the client's internal password configuration and does not perform password rotation on the server side.
Parameters:
ctx - The context for controlling the command execution.
Return value:
`"OK"` response on success.
Example ¶
var client *Client = getExampleClient() // example helper function
response, err := client.ResetConnectionPassword(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(response)
Output: OK
func (*Client) Restore ¶
func (client *Client) Restore(ctx context.Context, key string, ttl time.Duration, value string) (string, error)
Creates a key associated with a value that is obtained by deserializing the provided serialized value (obtained via Client.Dump or ClusterClient.Dump).
Parameters:
ctx - The context for controlling the command execution. key - The key to create. ttl - The expiry time. If 0, the key will persist. value - The serialized value to deserialize and assign to key.
Return value:
Return OK if successfully create a key with a value.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.Set(context.Background(), "key1", "someValue")
dump, err := client.Dump(context.Background(), "key1")
result1, err := client.Del(context.Background(), []string{"key1"})
result2, err := client.Restore(context.Background(), "key1", 0, dump.Value())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: OK 1 OK
func (*Client) RestoreWithOptions ¶
func (client *Client) RestoreWithOptions(ctx context.Context, key string, ttl time.Duration, value string, options options.RestoreOptions, ) (string, error)
Creates a key associated with a value that is obtained by deserializing the provided serialized value (obtained via Client.Dump or ClusterClient.Dump).
Parameters:
ctx - The context for controlling the command execution. key - The key to create. ttl - The expiry time. If 0, the key will persist. value - The serialized value to deserialize and assign to key. restoreOptions - Set restore options with replace and absolute TTL modifiers, object idletime and frequency.
Return value:
Return OK if successfully create a key with a value.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.Set(context.Background(), "key1", "someValue")
dump, err := client.Dump(context.Background(), "key1")
result1, err := client.Del(context.Background(), []string{"key1"})
opts := options.NewRestoreOptions().SetReplace().SetABSTTL().SetEviction(constants.FREQ, 10)
result2, err := client.RestoreWithOptions(context.Background(), "key1", 0, dump.Value(), *opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: OK 1 OK
func (*Client) SAdd ¶
SAdd adds specified members to the set stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key where members will be added to its set. members - A list of members to add to the set stored at key.
Return value:
The number of members that were added to the set, excluding members already present.
Example ¶
var client *Client = getExampleClient() // example helper function
key := "my_set"
result, err := client.SAdd(context.Background(), key, []string{"member1", "member2"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 2
func (*Client) SCard ¶
SCard retrieves the set cardinality (number of elements) of the set stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key from which to retrieve the number of set members.
Return value:
The cardinality (number of elements) of the set, or `0` if the key does not exist.
Example ¶
var client *Client = getExampleClient() // example helper function
key := "my_set"
client.SAdd(context.Background(), key, []string{"member1", "member2"})
result, err := client.SCard(context.Background(), key)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 2
func (*Client) SDiff ¶
SDiff computes the difference between the first set and all the successive sets in keys.
Note:
When in cluster mode, all keys must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - The keys of the sets to diff.
Return value:
A `map[string]struct{}` representing the difference between the sets.
If a key does not exist, it is treated as an empty set.
Example ¶
var client *Client = getExampleClient() // example helper function
key1 := "my_set_1"
key2 := "my_set_2"
client.SAdd(context.Background(), key1, []string{"member1", "member2"})
client.SAdd(context.Background(), key2, []string{"member2"})
result, err := client.SDiff(context.Background(), []string{key1, key2})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: map[member1:{}]
func (*Client) SDiffStore ¶
func (client *Client) SDiffStore(ctx context.Context, destination string, keys []string) (int64, error)
SDiffStore stores the difference between the first set and all the successive sets in `keys` into a new set at `destination`.
Note:
When in cluster mode, `destination` and all keys must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. destination - The key of the destination set. keys - The keys of the sets to diff.
Return value:
The number of elements in the resulting set.
Example ¶
var client *Client = getExampleClient() // example helper function
key1 := "my_set_1"
key2 := "my_set_2"
destination := "my_set_diff"
client.SAdd(context.Background(), key1, []string{"member1", "member2"})
client.SAdd(context.Background(), key2, []string{"member2"})
result, err := client.SDiffStore(context.Background(), destination, []string{key1, key2})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 1
func (*Client) SInter ¶
SInter gets the intersection of all the given sets.
Note:
When in cluster mode, all keys must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - The keys of the sets to intersect.
Return value:
A `map[string]struct{}` containing members which are present in all given sets.
If one or more sets do not exist, an empty collection will be returned.
Example ¶
var client *Client = getExampleClient() // example helper function
key1 := "my_set_1"
key2 := "my_set_2"
client.SAdd(context.Background(), key1, []string{"member1", "member2"})
client.SAdd(context.Background(), key2, []string{"member2"})
result, err := client.SInter(context.Background(), []string{key1, key2})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: map[member2:{}]
func (*Client) SInterCard ¶
SInterCard gets the cardinality of the intersection of all the given sets.
Since:
Valkey 7.0 and above.
Note:
When in cluster mode, all keys must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - The keys of the sets to intersect.
Return value:
The cardinality of the intersection result. If one or more sets do not exist, `0` is returned.
Example ¶
var client *Client = getExampleClient() // example helper function
key1 := "my_set_1"
key2 := "my_set_2"
client.SAdd(context.Background(), key1, []string{"member1", "member2"})
client.SAdd(context.Background(), key2, []string{"member2"})
result, err := client.SInterCard(context.Background(), []string{key1, key2})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 1
func (*Client) SInterCardLimit ¶
func (client *Client) SInterCardLimit(ctx context.Context, keys []string, limit int64) (int64, error)
SInterCardLimit gets the cardinality of the intersection of all the given sets, up to the specified limit.
Since:
Valkey 7.0 and above.
Note:
When in cluster mode, all keys must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - The keys of the sets to intersect. limit - The limit for the intersection cardinality value.
Return value:
The cardinality of the intersection result, or the limit if reached. If one or more sets do not exist, `0` is returned. If the intersection cardinality reaches 'limit' partway through the computation, returns 'limit' as the cardinality.
Example ¶
var client *Client = getExampleClient() // example helper function
key1 := "my_set_1"
key2 := "my_set_2"
limit := int64(1)
client.SAdd(context.Background(), key1, []string{"member1", "member2", "member3"})
client.SAdd(context.Background(), key2, []string{"member2", "member3"})
result, err := client.SInterCardLimit(context.Background(), []string{key1, key2}, limit)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 1
func (*Client) SInterStore ¶
func (client *Client) SInterStore(ctx context.Context, destination string, keys []string) (int64, error)
Stores the members of the intersection of all given sets specified by `keys` into a new set at `destination`
Note:
When in cluster mode, `destination` and all keys must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. destination - The key of the destination set. keys - The keys from which to retrieve the set members.
Return value:
The number of elements in the resulting set.
Example ¶
var client *Client = getExampleClient() // example helper function
key1 := "my_set_1"
key2 := "my_set_2"
destination := "my_set_inter"
client.SAdd(context.Background(), key1, []string{"member1", "member2"})
client.SAdd(context.Background(), key2, []string{"member2"})
result, err := client.SInterStore(context.Background(), destination, []string{key1, key2})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 1
func (*Client) SIsMember ¶
SIsMember returns if member is a member of the set stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the set. member - The member to check for existence in the set.
Return value:
A bool containing true if the member exists in the set, false otherwise. If key doesn't exist, it is treated as an empty set and the method returns false.
Example ¶
var client *Client = getExampleClient() // example helper function
key := "my_set"
client.SAdd(context.Background(), key, []string{"member1", "member2"})
result, err := client.SIsMember(context.Background(), key, "member1")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: true
func (*Client) SMIsMember ¶
SMIsMember returns whether each member is a member of the set stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the set. members - The members to check.
Return value:
A []bool containing whether each member is a member of the set stored at key.
Example ¶
var client *Client = getExampleClient() // example helper function
key := "my_set"
members := []string{"member1", "member2"}
client.SAdd(context.Background(), key, members)
memberTest := []string{"member1", "member2", "member3"}
result, err := client.SMIsMember(context.Background(), key, memberTest)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [true true false]
func (*Client) SMembers ¶
SMembers retrieves all the members of the set value stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key from which to retrieve the set members.
Return value:
A `map[string]struct{}` containing all members of the set.
Returns an empty collection if key does not exist.
Example ¶
var client *Client = getExampleClient() // example helper function
key := "my_set"
client.SAdd(context.Background(), key, []string{"member1", "member2"})
result, err := client.SMembers(context.Background(), key)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: map[member1:{} member2:{}]
func (*Client) SMove ¶
func (client *Client) SMove(ctx context.Context, source string, destination string, member string) (bool, error)
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.
Note: When in cluster mode, `source` and `destination` must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. source - The key of the set to remove the element from. destination - The key of the set to add the element to. member - The set element to move.
Return value:
`true` on success, or `false` if the `source` set does not exist or the element is not a member of the source set.
Example ¶
var client *Client = getExampleClient() // example helper function
source := "my_set_1"
destination := "my_set_2"
member := "member1"
client.SAdd(context.Background(), source, []string{member})
result, err := client.SMove(context.Background(), source, destination, member)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: true
func (*Client) SPop ¶
SPop removes and returns one random member from the set stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the set.
Return value:
A models.Result[string] containing the value of the popped member. Returns a NilResult if key does not exist.
Example ¶
var client *Client = getExampleClient() // example helper function
key := "my_set"
client.SAdd(context.Background(), key, []string{"member1", "member2"})
result, err := client.SPop(context.Background(), key)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.IsNil())
Output: false
func (*Client) SPopCount ¶
func (client *Client) SPopCount(ctx context.Context, key string, count int64) (map[string]struct{}, error)
SpopCount removes and returns up to count random members from the set stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the set. count - The number of members to return. If count is positive, returns unique elements. If count is larger than the set's cardinality, returns the entire set.
Return value:
A `map[string]struct{}` of popped elements.
If key does not exist, an empty collection will be returned.
Example ¶
var client *Client = getExampleClient() // example helper function
key := "my_set"
client.SAdd(context.Background(), key, []string{"member1", "member2", "member3", "member4"})
result, err := client.SPopCount(context.Background(), key, 2)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(len(result))
Output: 2
func (*Client) SRandMember ¶
SRandMember returns a random element from the set value stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key from which to retrieve the set member.
Return value:
A models.Result[string] containing a random element from the set. Returns models.CreateNilStringResult() if key does not exist.
Example ¶
var client *Client = getExampleClient() // example helper function
key := "my_set"
client.SAdd(context.Background(), key, []string{"member1", "member2"})
result, err := client.SRandMember(context.Background(), key)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.IsNil()) // Unable to test for a random value so just check if it is not nil
Output: false
func (*Client) SRandMemberCount ¶
func (client *Client) SRandMemberCount(ctx context.Context, key string, count int64) ([]string, error)
SRandMemberCount returns multiple random members from the set value stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
key - The key from which to retrieve the set members.
count - The number of members to return.
If count is positive, returns unique elements (no repetition) up to count or the set size, whichever is smaller.
If count is negative, returns elements with possible repetition (the same element may be returned multiple times),
and the number of returned elements is the absolute value of count.
Return value:
An array of random elements from the set. When count is positive, the returned elements are unique (no repetitions). When count is negative, the returned elements may contain duplicates. If the set does not exist or is empty, an empty array is returned.
Example ¶
var client *Client = getExampleClient() // example helper function
key := "my_set"
client.SAdd(context.Background(), key, []string{"member1", "member2", "member3"})
// Get 2 unique random members
result, err := client.SRandMemberCount(context.Background(), key, 2)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(len(result)) // Cannot test exact values as they are random
Output: 2
func (*Client) SRem ¶
SRem removes specified members from the set stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key from which members will be removed. members - A list of members to remove from the set stored at key.
Return value:
The number of members that were removed from the set, excluding non-existing members.
Example ¶
var client *Client = getExampleClient() // example helper function
key := "my_set"
client.SAdd(context.Background(), key, []string{"member1", "member2"})
result, err := client.SRem(context.Background(), key, []string{"member1", "member2"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 2
func (*Client) SScan ¶
func (client *Client) SScan(ctx context.Context, key string, cursor models.Cursor) (models.ScanResult, error)
Iterates incrementally over a set.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the set. cursor - The cursor that points to the next iteration of results.
Return value:
An object which holds the next cursor and the subset of the hash held by `key`. The cursor will return `false` from `IsFinished()` method on the last iteration of the subset. The data array in the result is always an array of the subset of the set held in `key`.
Example ¶
var client *Client = getExampleClient() // example helper function
key := "my_set"
client.SAdd(context.Background(), key, []string{"member1", "member2"})
result, err := client.SScan(context.Background(), key, models.NewCursor())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
sort.Strings(result.Data) // Sort for consistent comparison
fmt.Println("Cursor:", result.Cursor)
fmt.Println("Collection:", result.Data)
Output: Cursor: 0 Collection: [member1 member2]
func (*Client) SScanWithOptions ¶
func (client *Client) SScanWithOptions( ctx context.Context, key string, cursor models.Cursor, options options.BaseScanOptions, ) (models.ScanResult, error)
Iterates incrementally over a set.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the set. cursor - The cursor that points to the next iteration of results. options - [options.BaseScanOptions]
Return value:
An object which holds the next cursor and the subset of the hash held by `key`. The cursor will return `false` from `IsFinished()` method on the last iteration of the subset. The data array in the result is always an array of the subset of the set held in `key`.
Example ¶
var client *Client = getExampleClient() // example helper function
key := "my_set"
client.SAdd(context.Background(), key, []string{"member1", "member2", "item3"})
options := options.NewBaseScanOptions().SetMatch("mem*")
result, err := client.SScanWithOptions(context.Background(), key, models.NewCursor(), *options)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
sort.Strings(result.Data) // Sort for consistent comparison
fmt.Println("Cursor:", result.Cursor)
fmt.Println("Collection:", result.Data)
Output: Cursor: 0 Collection: [member1 member2]
func (*Client) SUnion ¶
SUnion gets the union of all the given sets.
Note:
When in cluster mode, all keys must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - The keys of the sets.
Return value:
A `map[string]struct{}` of members which are present in at least one of the given sets.
If none of the sets exist, an empty collection will be returned.
Example ¶
var client *Client = getExampleClient() // example helper function
key1 := "my_set_1"
key2 := "my_set_2"
client.SAdd(context.Background(), key1, []string{"member1", "member2"})
client.SAdd(context.Background(), key2, []string{"member2", "member3"})
result, err := client.SUnion(context.Background(), []string{key1, key2})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: map[member1:{} member2:{} member3:{}]
func (*Client) SUnionStore ¶
func (client *Client) SUnionStore(ctx context.Context, destination string, keys []string) (int64, error)
SUnionStore stores the members of the union of all given sets specified by `keys` into a new set at `destination`.
Note:
When in cluster mode, `destination` and all `keys` must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. destination - The key of the destination set. keys - The keys from which to retrieve the set members.
Return value:
The number of elements in the resulting set.
Example ¶
var client *Client = getExampleClient() // example helper function
key1 := "my_set_1"
key2 := "my_set_2"
destination := "my_set_union"
client.SAdd(context.Background(), key1, []string{"member1", "member2"})
client.SAdd(context.Background(), key2, []string{"member2", "member3"})
result, err := client.SUnionStore(context.Background(), destination, []string{key1, key2})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 3
func (*Client) Scan ¶
Iterates incrementally over a database for matching keys.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. cursor - The cursor that points to the next iteration of results.
Return value:
An object which holds the next cursor and the subset of the hash held by `key`. The cursor will return `false` from `IsFinished()` method on the last iteration of the subset. The data array in the result is always an array of matched keys from the database.
Example ¶
var client *Client = getExampleClient() // example helper function
client.CustomCommand(context.Background(), []string{"FLUSHALL"})
client.Set(context.Background(), "key1", "hello")
result, err := client.Scan(context.Background(), models.NewCursor())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println("Cursor:", result.Cursor)
fmt.Println("Collection:", result.Data)
Output: Cursor: 0 Collection: [key1]
func (*Client) ScanWithOptions ¶
func (client *Client) ScanWithOptions( ctx context.Context, cursor models.Cursor, scanOptions options.ScanOptions, ) (models.ScanResult, error)
Iterates incrementally over a database for matching keys.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. cursor - The cursor that points to the next iteration of results. scanOptions - Additional command parameters, see [ScanOptions] for more details.
Return value:
An object which holds the next cursor and the subset of the hash held by `key`. The cursor will return `false` from `IsFinished()` method on the last iteration of the subset. The data array in the result is always an array of matched keys from the database.
Example ¶
var client *Client = getExampleClient() // example helper function
opts := options.NewScanOptions().SetCount(10).SetType(constants.ObjectTypeList)
client.CustomCommand(context.Background(), []string{"FLUSHALL"})
client.LPush(context.Background(), "key1", []string{"1", "3", "2", "4"})
result, err := client.ScanWithOptions(context.Background(), models.NewCursor(), *opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println("Cursor:", result.Cursor)
fmt.Println("Collection:", result.Data)
Output: Cursor: 0 Collection: [key1]
func (*Client) ScriptExists ¶
Checks existence of scripts in the script cache by their SHA1 digest.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. sha1s - SHA1 digests of Lua scripts to be checked.
Return value:
An array of boolean values indicating the existence of each script.
Example ¶
client := getExampleClient()
// Invoke a script
script := options.NewScript("return 'Hello World!'")
client.InvokeScript(context.Background(), *script)
response, err := client.ScriptExists(context.Background(), []string{script.GetHash()})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
fmt.Println(response)
// Cleanup
script.Close()
Output: [true]
func (*Client) ScriptFlush ¶
Removes all the scripts from the script cache.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
OK on success.
Example ¶
client := getExampleClient()
// First, load a script
script := options.NewScript("return 'Hello World!'")
_, err := client.InvokeScript(context.Background(), *script)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
// Verify script exists
exists, err := client.ScriptExists(context.Background(), []string{script.GetHash()})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
fmt.Println("Script exists before flush:", exists[0])
// Flush all scripts
result, err := client.ScriptFlush(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
fmt.Println("Flush result:", result)
// Verify script no longer exists
exists, err = client.ScriptExists(context.Background(), []string{script.GetHash()})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
fmt.Println("Script exists after flush:", exists[0])
// Cleanup
script.Close()
Output: Script exists before flush: true Flush result: OK Script exists after flush: false
func (*Client) ScriptFlushWithMode ¶
func (client *Client) ScriptFlushWithMode(ctx context.Context, mode options.FlushMode) (string, error)
Removes all the scripts from the script cache with the specified flush mode. The mode can be either SYNC or ASYNC.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. mode - The flush mode (SYNC or ASYNC).
Return value:
OK on success.
Example ¶
client := getExampleClient()
// First, load a script
script := options.NewScript("return 'Hello World!'")
_, err := client.InvokeScript(context.Background(), *script)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
// Verify script exists
exists, err := client.ScriptExists(context.Background(), []string{script.GetHash()})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
fmt.Println("Script exists before flush:", exists[0])
// Flush all scripts with ASYNC mode
result, err := client.ScriptFlushWithMode(context.Background(), options.ASYNC)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
fmt.Println("Flush result:", result)
// Verify script no longer exists
exists, err = client.ScriptExists(context.Background(), []string{script.GetHash()})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
fmt.Println("Script exists after flush:", exists[0])
// Cleanup
script.Close()
Output: Script exists before flush: true Flush result: OK Script exists after flush: false
func (*Client) ScriptKill ¶
Kills the currently executing Lua script, assuming no write operation was yet performed by the script.
Note:
When in cluster mode, this command will be routed to all nodes.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
`OK` if script is terminated. Otherwise, throws an error.
Example ¶
client := getExampleClient()
// Try to kill scripts when no scripts are running
_, err := client.ScriptKill(context.Background())
if err != nil {
fmt.Println("Expected error:", err)
}
Output: Expected error: An error was signalled by the server: - NotBusy: No scripts in execution right now.
func (*Client) ScriptShow ¶
ScriptShow returns the original source code of a script in the script cache.
Since:
Valkey 8.0.0
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. sha1 - The SHA1 digest of the script.
Return value:
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.
Example ¶
ScriptShow Examples
client := getExampleClient()
// First, create and invoke a script
scriptText := "return 'Hello, World!'"
script := options.NewScript(scriptText)
_, err := client.InvokeScript(context.Background(), *script)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
// Now show the script source using ScriptShow
scriptSource, err := client.ScriptShow(context.Background(), script.GetHash())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
fmt.Println(scriptSource)
Output: return 'Hello, World!'
func (*Client) Select ¶
Select changes the currently selected database.
WARNING: This command is NOT RECOMMENDED for production use. Upon reconnection, the client will revert to the database_id specified in the client configuration (default: 0), NOT the database selected via this command.
RECOMMENDED APPROACH: Use the database_id parameter in client configuration instead:
config := &config.ClientConfiguration{
Addresses: []config.NodeAddress{{Host: "localhost", Port: 6379}},
DatabaseId: &databaseId, // Recommended: persists across reconnections
}
client, err := NewClient(config)
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. index - The index of the database to select.
Return value:
A simple `"OK"` response.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.Select(context.Background(), 2)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*Client) Set ¶
Set the given key with the given value. The return value is a response from Valkey containing the string "OK".
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to store. value - The value to store with the given key.
Return value:
`"OK"` response on success.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.Set(context.Background(), "my_key", "my_value")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*Client) SetBit ¶
func (client *Client) SetBit(ctx context.Context, key string, offset int64, value int64) (int64, error)
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`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the string. offset - The index of the bit to be set. value - The bit value to set at offset The value must be `0` or `1`.
Return value:
The bit value that was previously stored at offset.
Example ¶
var client *Client = getExampleClient() // example helper function
client.SetBit(context.Background(), "my_key", 1, 1) // initialize bit 1 with a value of 1
result, err := client.SetBit(context.Background(), "my_key", 1, 1) // set bit should return the previous value of bit 1
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 1
func (*Client) SetRange ¶
func (client *Client) SetRange(ctx context.Context, key string, offset int, value string) (int64, error)
Overwrites part of the string stored at key, starting at the specified byte's 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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the string to update. offset - The position in the string where value should be written. value - The string written with offset.
Return value:
The length of the string stored at `key` after it was modified.
Example (One) ¶
var client *Client = getExampleClient() // example helper function
client.Set(context.Background(), "my_key", "my_value")
result, err := client.SetRange(context.Background(), "my_key", 3, "example")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
value, _ := client.Get(context.Background(), "my_key")
fmt.Println(value.Value())
Output: 10 my_example
Example (Two) ¶
var client *Client = getExampleClient() // example helper function
client.Set(context.Background(), "my_key", "愛") // "愛" is a single character in UTF-8, but 3 bytes long
result, err := client.SetRange(context.Background(), "my_key", 1, "a")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 3
func (*Client) SetWithOptions ¶
func (client *Client) SetWithOptions( ctx context.Context, key string, value string, options options.SetOptions, ) (models.Result[string], error)
SetWithOptions sets the given key with the given value using the given options. The return value is dependent on the passed options. If the value is successfully set, "OK" is returned. If value isn't set because of constants.OnlyIfExists or constants.OnlyIfDoesNotExist conditions, models.CreateNilStringResult() is returned. If constants.ReturnOldValue is set, the old value is returned.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to store. value - The value to store with the given key. options - The [options.SetOptions].
Return value:
If the value is successfully set, return models.Result[string] containing "OK". If value isn't set because of ConditionalSet.OnlyIfExists or ConditionalSet.OnlyIfDoesNotExist or ConditionalSet.OnlyIfEquals conditions, return models.CreateNilStringResult(). If SetOptions.returnOldValue is set, return the old value as a String.
Example ¶
var client *Client = getExampleClient() // example helper function
options := options.NewSetOptions().
SetExpiry(options.NewExpiryIn(5 * time.Second))
result, err := client.SetWithOptions(context.Background(), "my_key", "my_value", *options)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.Value())
Output: OK
func (*Client) Sort ¶
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 the Client.SortStore or ClusterClient.SortStore function.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list, set, or sorted set to be sorted.
Return value:
An Array of sorted elements.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.LPush(context.Background(), "key1", []string{"1", "3", "2", "4"})
result1, err := client.Sort(context.Background(), "key1")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 4 [{1 false} {2 false} {3 false} {4 false}]
func (*Client) SortReadOnly ¶
func (client *Client) SortReadOnly(ctx context.Context, key string) ([]models.Result[string], error)
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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list, set, or sorted set to be sorted.
Return value:
An Array of sorted elements.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.LPush(context.Background(), "key1", []string{"1", "3", "2", "4"})
result1, err := client.SortReadOnly(context.Background(), "key1")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 4 [{1 false} {2 false} {3 false} {4 false}]
func (*Client) SortReadOnlyWithOptions ¶
func (client *Client) SortReadOnlyWithOptions( ctx context.Context, key string, options options.SortOptions, ) ([]models.Result[string], error)
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.
Note:
In cluster mode, if `key` 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. The use of SortOptions.byPattern and SortOptions.getPatterns in cluster mode is supported since Valkey version 8.0.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list, set, or sorted set to be sorted. sortOptions - The SortOptions type.
Return value:
An Array of sorted elements.
Example ¶
var client *Client = getExampleClient() // example helper function
opts := options.NewSortOptions().SetByPattern("weight_*").SetIsAlpha(false).SetOrderBy(options.ASC)
client.Set(context.Background(), "weight_item1", "3")
client.Set(context.Background(), "weight_item2", "1")
client.Set(context.Background(), "weight_item3", "2")
result, err := client.LPush(context.Background(), "key1", []string{"item1", "item2", "item3"})
result1, err := client.SortReadOnlyWithOptions(context.Background(), "key1", *opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 3 [{item2 false} {item3 false} {item1 false}]
func (*Client) SortStore ¶
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, apply transformations on sorted elements, and store the result in a new key. The SortStore command can be used to sort elements based on different criteria and apply transformations on sorted elements. To get the sort result without storing it into a key, see the Client.Sort and ClusterClient.Sort or Client.SortReadOnly and ClusterClient.SortReadOnly function.
Note:
In cluster mode, if `key` and `destination` 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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list, set, or sorted set to be sorted. destination - The key where the sorted result will be stored.
Return value:
The number of elements in the sorted key stored at destination.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.LPush(context.Background(), "key1", []string{"1", "3", "2", "4"})
result1, err := client.SortStore(context.Background(), "key1", "key1_store")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 4 4
func (*Client) SortStoreWithOptions ¶
func (client *Client) SortStoreWithOptions( ctx context.Context, key string, destination string, opts options.SortOptions, ) (int64, error)
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, apply transformations on sorted elements, and store the result in a new key. The SortStore command can be used to sort elements based on different criteria and apply transformations on sorted elements. To get the sort result without storing it into a key, see the Client.SortWithOptions and ClusterClient.SortWithOptions or Client.SortReadOnlyWithOptions and ClusterClient.SortReadOnlyWithOptions function.
Note:
In cluster mode, if `key` and `destination` 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. The use of SortOptions.byPattern and SortOptions.getPatterns in cluster mode is supported since Valkey version 8.0.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list, set, or sorted set to be sorted. destination - The key where the sorted result will be stored.
opts - The options.SortOptions type.
Return value:
The number of elements in the sorted key stored at destination.
Example ¶
var client *Client = getExampleClient() // example helper function
opts := options.NewSortOptions().SetByPattern("weight_*").SetIsAlpha(false).SetOrderBy(options.ASC)
client.Set(context.Background(), "weight_item1", "3")
client.Set(context.Background(), "weight_item2", "1")
client.Set(context.Background(), "weight_item3", "2")
result, err := client.LPush(context.Background(), "key1", []string{"item1", "item2", "item3"})
result1, err := client.SortStoreWithOptions(context.Background(), "key1", "key1_store", *opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 3 3
func (*Client) SortWithOptions ¶
func (client *Client) SortWithOptions( ctx context.Context, key string, options options.SortOptions, ) ([]models.Result[string], error)
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 the Client.SortStoreWithOptions or ClusterClient.SortStoreWithOptions function.
Note:
In cluster mode, if `key` 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. The use of SortOptions.byPattern and SortOptions.getPatterns in cluster mode is supported since Valkey version 8.0.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list, set, or sorted set to be sorted. sortOptions - The SortOptions type.
Return value:
An Array of sorted elements.
Example ¶
var client *Client = getExampleClient() // example helper function
opts := options.NewSortOptions().SetByPattern("weight_*").SetIsAlpha(false).SetOrderBy(options.ASC)
client.Set(context.Background(), "weight_item1", "3")
client.Set(context.Background(), "weight_item2", "1")
client.Set(context.Background(), "weight_item3", "2")
result, err := client.LPush(context.Background(), "key1", []string{"item1", "item2", "item3"})
result1, err := client.SortWithOptions(context.Background(), "key1", *opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 3 [{item2 false} {item3 false} {item1 false}]
func (*Client) Strlen ¶
Returns the length of the string value stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to check its length.
Return value:
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 ¶
var client *Client = getExampleClient() // example helper function
client.Set(context.Background(), "my_key", "my_value")
result, err := client.Strlen(context.Background(), "my_key")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 8
func (*Client) Subscribe ¶ added in v2.3.0
Subscribe subscribes the client to the specified channels (blocking). This command updates the client's internal desired subscription state and waits for server confirmation.
Parameters:
ctx - The context for the operation.
channels - A slice of channel names to subscribe to.
timeoutMs - Maximum time in milliseconds to wait for server confirmation.
A value of 0 blocks indefinitely until confirmation.
Return value:
An error if the operation fails or times out.
Example:
err := client.Subscribe(ctx, []string{"channel1"}, 5000)
Subscribe subscribes the client to the specified channels (blocking). This command updates the client's internal desired subscription state and waits for server confirmation.
Parameters:
ctx - The context for the operation.
channels - A slice of channel names to subscribe to.
timeoutMs - Maximum time in milliseconds to wait for server confirmation.
A value of 0 blocks indefinitely until confirmation.
Return value:
An error if the operation fails or times out.
Example:
err := client.Subscribe(ctx, []string{"channel1", "channel2"}, 0)
func (*Client) SubscribeLazy ¶ added in v2.3.0
SubscribeLazy subscribes the client to the specified channels (non-blocking). This command updates the client's internal desired subscription state without waiting for server confirmation. It returns immediately after updating the local state. The client will attempt to subscribe asynchronously in the background.
Note: Use GetSubscriptions() to verify the actual server-side subscription state.
Parameters:
ctx - The context for the operation. channels - A slice of channel names to subscribe to.
Return value:
An error if the operation fails.
Example:
err := client.SubscribeLazy(ctx, []string{"channel1", "channel2"})
func (*Client) TTL ¶
TTL returns the remaining time to live of key that has a timeout, in seconds.
Parameters:
ctx - The context for controlling the command execution. key - The key to return its timeout.
Return value:
Returns TTL in seconds, `-2` if key does not exist, or `-1` if key exists but has no associated expiration.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.Set(context.Background(), "key", "someValue")
result1, err := client.TTL(context.Background(), "key")
_, err = client.ExpireAt(
context.Background(),
"key",
time.Now().Add(10*time.Second),
) // TTL("key") returns proper TTL in seconds
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK -1
func (*Client) Time ¶
Returns the server time.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
The current server time as a String array with two elements: A UNIX TIME and the amount of microseconds already elapsed in the current second. The returned array is in a [UNIX TIME, Microseconds already elapsed] format.
Example ¶
var client *Client = getExampleClient() // example helper function
timeMargin := int64(5)
clientTime := time.Now().Unix()
result, err := client.Time(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
serverTime, _ := strconv.ParseInt(result[0], 10, 64)
fmt.Println((serverTime - clientTime) < timeMargin)
Output: true
func (*Client) Touch ¶
Alters the last access time of a key(s). A key is ignored if it does not exist.
Note:
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.
Parameters:
ctx - The context for controlling the command execution. keys - The keys to update last access time.
Return value:
The number of keys that were updated.
[valkey.io]: Https://valkey.io/commands/touch/
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.Set(context.Background(), "key1", "someValue")
result1, err := client.Set(context.Background(), "key2", "someValue")
result2, err := client.Touch(context.Background(), []string{"key1", "key2", "key3"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: OK OK 2
func (*Client) Type ¶
Type returns the string representation of the type of the value stored at key. The different types that can be returned are: `"string"`, `"list"`, `"set"`, `"zset"`, `"hash"` and `"stream"`.
Parameters:
ctx - The context for controlling the command execution. key - The `key` to check its data type.
Return value:
If the `key` exists, the type of the stored value is returned. Otherwise, a `"none"` string is returned.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.Set(context.Background(), "key1", "someValue")
result1, err := client.Type(context.Background(), "key1")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK string
func (*Client) Unlink ¶
Unlink (delete) multiple keys from the database. A key is ignored if it does not exist. This command, similar to Client.Del and ClusterClient.Del, however, this command does not block the server.
Note:
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.
Parameters:
ctx - The context for controlling the command execution. keys - One or more keys to unlink.
Return value:
Return the number of keys that were unlinked.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.Set(context.Background(), "key1", "someValue")
result1, err := client.Set(context.Background(), "key2", "someValue")
result2, err := client.Unlink(context.Background(), []string{"key1", "key2", "key3"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: OK OK 2
func (*Client) Unsubscribe ¶ added in v2.3.0
Unsubscribe unsubscribes the client from the specified channels (blocking). This command updates the client's internal desired subscription state and waits for server confirmation. If no channels are specified (nil or empty slice), unsubscribes from all exact channels.
Parameters:
ctx - The context for the operation.
channels - A slice of channel names to unsubscribe from. Pass nil to unsubscribe from all.
timeoutMs - Maximum time in milliseconds to wait for server confirmation.
A value of 0 blocks indefinitely until confirmation.
Return value:
An error if the operation fails or times out.
Example:
err := client.Unsubscribe(ctx, []string{"channel1"}, 5000)
err := client.Unsubscribe(ctx, nil, 5000) // Unsubscribe from all
func (*Client) UnsubscribeLazy ¶ added in v2.3.0
UnsubscribeLazy unsubscribes the client from the specified channels (non-blocking). This command updates the client's internal desired subscription state without waiting for server confirmation. It returns immediately after updating the local state. If no channels are specified (nil), unsubscribes from all exact channels.
Parameters:
ctx - The context for the operation. channels - A slice of channel names to unsubscribe from. Pass nil to unsubscribe from all.
Return value:
An error if the operation fails.
Example:
err := client.UnsubscribeLazy(ctx, []string{"channel1"})
err := client.UnsubscribeLazy(ctx, nil) // Unsubscribe from all
func (*Client) Unwatch ¶
Flushes all the previously watched keys for a transaction. Executing a transaction will automatically flush all previously watched keys.
See valkey.io and Valkey GLIDE Documentation for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
A simple "OK" response.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.Unwatch(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*Client) UpdateConnectionPassword ¶
func (client *Client) UpdateConnectionPassword(ctx context.Context, password string, immediateAuth bool) (string, error)
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.
Note:
This method updates the client's internal password configuration and does not perform password rotation on the server side.
Parameters:
ctx - The context for controlling the command execution. password - The new password to update the connection with. immediateAuth - immediateAuth A boolean flag. If true, the client will authenticate immediately with the new password against all connections, Using AUTH command. If password supplied is an empty string, the client will not perform auth and a warning will be returned. The default is `false`.
Return value:
`"OK"` response on success.
Example ¶
var client *Client = getExampleClient() // example helper function
response, err := client.UpdateConnectionPassword(context.Background(), "", false)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(response)
Output: OK
func (*Client) Wait ¶
func (client *Client) Wait(ctx context.Context, numberOfReplicas int64, timeout time.Duration) (int64, error)
Wait blocks the current client until all the previous write commands are successfully transferred and acknowledged by at least the specified number of replicas or if the timeout is reached, whichever is earlier.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. numberOfReplicas - The number of replicas to reach. timeout - The timeout value. A value of `0` will block indefinitely.
Return value:
The number of replicas reached by all the writes performed in the context of the current connection.
Example ¶
var client *Client = getExampleClient() // example helper function
client.Set(context.Background(), "key1", "someValue")
result, err := client.Wait(context.Background(), 2, 1*time.Second)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Wait returns different results each time. Check it is the proper return type instead
fmt.Println(result < 10)
Output: true
func (*Client) Watch ¶
Marks the given keys to be watched for conditional execution of an atomic batch (Transaction). Transactions will only execute commands if the watched keys are not modified before execution of the transaction.
See valkey.io and Valkey GLIDE Documentation for details.
Note:
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.
Parameters:
ctx - The context for controlling the command execution. keys - The keys to watch.
Return value:
A simple "OK" response.
Example (ChangedKey) ¶
var client *Client = getExampleClient() // example helper function
// Example 1: key is changed before transaction and transaction didn't execute
result, err := client.Watch(context.Background(), []string{"sampleKey"})
fmt.Println("Watch result: ", result)
result, err = client.Set(context.Background(), "sampleKey", "foobar")
fmt.Println("Set result: ", result)
transaction := pipeline.NewStandaloneBatch(true)
transaction.Set("sampleKey", "value")
// Set command retry parameters
result1, err := client.Exec(context.Background(), *transaction, false)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Transaction result is `nil`, it is not executed at all
fmt.Printf("Transation result: %#v", result1)
Output: Watch result: OK Set result: OK Transation result: []interface {}(nil)
Example (UnchangedKey) ¶
var client *Client = getExampleClient() // example helper function
// Example 2: key is unchanged before transaction
result, err := client.Watch(context.Background(), []string{"sampleKey"})
fmt.Println("Watch result: ", result)
transaction := pipeline.NewStandaloneBatch(true)
transaction.Set("sampleKey", "value")
// Set command retry parameters
result1, err := client.Exec(context.Background(), *transaction, false)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println("Transation result: ", result1)
Output: Watch result: OK Transation result: [OK]
func (*Client) XAck ¶
func (client *Client) XAck(ctx context.Context, key string, group string, ids []string) (int64, error)
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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. group - he consumer group name. ids - Stream entry IDs to acknowledge and purge messages.
Return value:
The number of messages that were successfully acknowledged.
Example ¶
var client *Client = getExampleClient() // example helper function
key := "12345"
group := "g12345"
consumer := "c12345"
streamId, _ := client.XAdd(
context.Background(),
key,
[]models.FieldValue{
{Field: "entry1_field1", Value: "entry1_value1"},
{Field: "entry1_field2", Value: "entry1_value2"},
},
)
client.XGroupCreate(context.Background(), key, group, "0")
client.XGroupCreateConsumer(context.Background(), key, group, consumer)
client.XReadGroup(context.Background(), group, consumer, map[string]string{key: ">"})
count, err := client.XAck(
context.Background(),
key,
group,
[]string{streamId},
) // ack the message and remove it from the pending list
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(count)
Output: 1
func (*Client) XAdd ¶
func (client *Client) XAdd(ctx context.Context, key string, values []models.FieldValue) (string, error)
Adds an entry to the specified stream stored at `key`. If the `key` doesn't exist, the stream is created.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. values - Field-value pairs to be added to the entry.
Return value:
The id of the added entry.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.XAdd(context.Background(), "mystream", []models.FieldValue{
{Field: "key1", Value: "value1"},
{Field: "key2", Value: "value2"},
})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
matches, _ := regexp.Match(
`^\d{13}-0$`,
[]byte(result),
) // matches a number that is 13 digits long followed by "-0"
fmt.Println(matches)
Output: true
func (*Client) XAddWithOptions ¶
func (client *Client) XAddWithOptions( ctx context.Context, key string, values []models.FieldValue, options options.XAddOptions, ) (models.Result[string], error)
Adds an entry to the specified stream stored at `key`. If the `key` doesn't exist, the stream is created.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. values - Field-value pairs to be added to the entry. options - Stream add options.
Return value:
The id of the added entry, or `nil` if [options.XAddOptions.MakeStream] is set to `false` and no stream with the matching `key` exists.
Example ¶
var client *Client = getExampleClient() // example helper function
options := options.NewXAddOptions().SetId("1000-50")
values := []models.FieldValue{
{Field: "key1", Value: "value1"},
{Field: "key2", Value: "value2"},
}
result, err := client.XAddWithOptions(context.Background(), "mystream", values, *options)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.Value())
Output: 1000-50
func (*Client) XAutoClaim ¶
func (client *Client) XAutoClaim( ctx context.Context, key string, group string, consumer string, minIdleTime time.Duration, start string, ) (models.XAutoClaimResponse, error)
Transfers ownership of pending stream entries that match the specified criteria.
Since:
Valkey 6.2.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. group - The consumer group name. consumer - The group consumer. minIdleTime - The minimum idle time for the message to be claimed. start - Filters the claimed entries to those that have an ID equal or greater than the specified value.
Return value:
An object 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 array of the claimed entries as `[]models.StreamEntry`.
- If you are using Valkey 7.0.0 or above, the response will also include an array 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.
Example ¶
var client *Client = getExampleClient() // example helper function
key := uuid.NewString()
group := uuid.NewString()
consumer := uuid.NewString()
client.XGroupCreateWithOptions(context.Background(), key, group, "0", *options.NewXGroupCreateOptions().SetMakeStream())
client.XGroupCreateConsumer(context.Background(), key, group, consumer)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{
{Field: "entry1_field1", Value: "entry1_value1"},
{Field: "entry1_field2", Value: "entry1_value2"},
},
*options.NewXAddOptions().SetId("0-1"),
)
client.XAddWithOptions(context.Background(),
key,
[]models.FieldValue{{Field: "entry2_field1", Value: "entry2_value1"}},
*options.NewXAddOptions().SetId("0-2"),
)
client.XReadGroup(context.Background(), group, consumer, map[string]string{key: ">"})
response, err := client.XAutoClaim(context.Background(), key, group, consumer, 0, "0-1")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(response)
Output: {0-0 [{0-1 [{entry1_field1 entry1_value1} {entry1_field2 entry1_value2}]} {0-2 [{entry2_field1 entry2_value1}]}] []}
func (*Client) XAutoClaimJustId ¶
func (client *Client) XAutoClaimJustId( ctx context.Context, key string, group string, consumer string, minIdleTime time.Duration, start string, ) (models.XAutoClaimJustIdResponse, error)
Transfers ownership of pending stream entries that match the specified criteria.
Since:
Valkey 6.2.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. group - The consumer group name. consumer - The group consumer. minIdleTime - The minimum idle time for the message to be claimed. start - Filters the claimed entries to those that have an ID equal or greater than the specified value.
Return value:
An object 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.
- An array of IDs for the claimed entries.
- If you are using Valkey 7.0.0 or above, the response will also include an array 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.
Example ¶
var client *Client = getExampleClient() // example helper function
key := uuid.NewString()
group := uuid.NewString()
consumer := uuid.NewString()
client.XGroupCreateWithOptions(context.Background(), key, group, "0", *options.NewXGroupCreateOptions().SetMakeStream())
client.XGroupCreateConsumer(context.Background(), key, group, consumer)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{
{Field: "entry1_field1", Value: "entry1_value1"},
{Field: "entry1_field2", Value: "entry1_value2"},
},
*options.NewXAddOptions().SetId("0-1"),
)
client.XAddWithOptions(context.Background(),
key,
[]models.FieldValue{{Field: "entry2_field1", Value: "entry2_value1"}},
*options.NewXAddOptions().SetId("0-2"),
)
client.XReadGroup(context.Background(), group, consumer, map[string]string{key: ">"})
response, err := client.XAutoClaimJustId(context.Background(), key, group, consumer, 0, "0-0")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(response)
Output: {0-0 [0-1 0-2] []}
func (*Client) XAutoClaimJustIdWithOptions ¶
func (client *Client) XAutoClaimJustIdWithOptions( ctx context.Context, key string, group string, consumer string, minIdleTime time.Duration, start string, opts options.XAutoClaimOptions, ) (models.XAutoClaimJustIdResponse, error)
Transfers ownership of pending stream entries that match the specified criteria.
Since:
Valkey 6.2.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. group - The consumer group name. consumer - The group consumer. minIdleTime - The minimum idle time for the message to be claimed. start - Filters the claimed entries to those that have an ID equal or greater than the specified value. opts - Options detailing how to read the stream. Count has a default value of 100.
Return value:
An object 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.
- An array of IDs for the claimed entries.
- If you are using Valkey 7.0.0 or above, the response will also include an array 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.
Example ¶
var client *Client = getExampleClient() // example helper function
key := uuid.NewString()
group := uuid.NewString()
consumer := uuid.NewString()
client.XGroupCreateWithOptions(context.Background(), key, group, "0", *options.NewXGroupCreateOptions().SetMakeStream())
client.XGroupCreateConsumer(context.Background(), key, group, consumer)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{
{Field: "entry1_field1", Value: "entry1_value1"},
{Field: "entry1_field2", Value: "entry1_value2"},
},
*options.NewXAddOptions().SetId("0-1"),
)
client.XAddWithOptions(context.Background(),
key,
[]models.FieldValue{{Field: "entry2_field1", Value: "entry2_value1"}},
*options.NewXAddOptions().SetId("0-2"),
)
client.XReadGroup(context.Background(), group, consumer, map[string]string{key: ">"})
options := options.NewXAutoClaimOptions().SetCount(1)
response, err := client.XAutoClaimJustIdWithOptions(context.Background(), key, group, consumer, 0, "0-1", *options)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(response)
Output: {0-2 [0-1] []}
func (*Client) XAutoClaimWithOptions ¶
func (client *Client) XAutoClaimWithOptions( ctx context.Context, key string, group string, consumer string, minIdleTime time.Duration, start string, options options.XAutoClaimOptions, ) (models.XAutoClaimResponse, error)
Transfers ownership of pending stream entries that match the specified criteria.
Since:
Valkey 6.2.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. group - The consumer group name. consumer - The group consumer. minIdleTime - The minimum idle time for the message to be claimed. start - Filters the claimed entries to those that have an ID equal or greater than the specified value. options - Options detailing how to read the stream. Count has a default value of 100.
Return value:
An object 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 array of the claimed entries as `[]models.StreamEntry`.
- If you are using Valkey 7.0.0 or above, the response will also include an array 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.
Example ¶
var client *Client = getExampleClient() // example helper function
key := uuid.NewString()
group := uuid.NewString()
consumer := uuid.NewString()
client.XGroupCreateWithOptions(context.Background(), key, group, "0", *options.NewXGroupCreateOptions().SetMakeStream())
client.XGroupCreateConsumer(context.Background(), key, group, consumer)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{
{Field: "entry1_field1", Value: "entry1_value1"},
{Field: "entry1_field2", Value: "entry1_value2"},
},
*options.NewXAddOptions().SetId("0-1"),
)
client.XAddWithOptions(context.Background(),
key,
[]models.FieldValue{{Field: "entry2_field1", Value: "entry2_value1"}},
*options.NewXAddOptions().SetId("0-2"),
)
client.XReadGroup(context.Background(), group, consumer, map[string]string{key: ">"})
options := options.NewXAutoClaimOptions().SetCount(1)
response, err := client.XAutoClaimWithOptions(context.Background(), key, group, consumer, 0, "0-1", *options)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(response)
Output: {0-2 [{0-1 [{entry1_field1 entry1_value1} {entry1_field2 entry1_value2}]}] []}
func (*Client) XClaim ¶
func (client *Client) XClaim( ctx context.Context, key string, group string, consumer string, minIdleTime time.Duration, ids []string, ) (map[string]models.XClaimResponse, error)
Changes the ownership of a pending message.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. group - The name of the consumer group. consumer - The name of the consumer. minIdleTime - The minimum idle time. ids - The ids of the entries to claim.
Return value:
A map[string]models.XClaimResponse where: - Each key is a message/entry ID - Each value is an XClaimResponse containing: - Fields: []FieldValue array of field-value pairs for the claimed entry
Example ¶
var client *Client = getExampleClient() // example helper function
key := "12345"
streamId := "12345-1"
group := "g12345"
consumer1 := "c12345-1"
consumer2 := "c12345-2"
client.XGroupCreateWithOptions(context.Background(), key, group, "0", *options.NewXGroupCreateOptions().SetMakeStream())
client.XGroupCreateConsumer(context.Background(), key, group, consumer1)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{
{Field: "entry1_field1", Value: "entry1_value1"},
{Field: "entry1_field2", Value: "entry1_value2"},
},
*options.NewXAddOptions().SetId(streamId),
)
client.XReadGroup(context.Background(), group, consumer1, map[string]string{key: ">"})
result, err := client.XPendingWithOptions(context.Background(),
key,
group,
*options.NewXPendingOptions("-", "+", 10).SetConsumer(consumer1),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
if len(result) == 0 {
fmt.Println("No pending messages")
return
}
response, err := client.XClaim(
context.Background(),
key,
group,
consumer2,
time.Duration(result[0].IdleTime)*time.Millisecond,
[]string{result[0].Id},
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Printf("Claimed %d message\n", len(response))
// Access fields from the claimed message
for id, claimResponse := range response {
fmt.Printf("Message ID: %s has %d fields\n", id, len(claimResponse.Fields))
}
Output: Claimed 1 message Message ID: 12345-1 has 2 fields
func (*Client) XClaimJustId ¶
func (client *Client) XClaimJustId( ctx context.Context, key string, group string, consumer string, minIdleTime time.Duration, ids []string, ) ([]string, error)
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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. group - The name of the consumer group. consumer - The name of the consumer. minIdleTime - The minimum idle time. ids - The ids of the entries to claim. options - Stream claim options.
Return value:
An array of the ids of the entries that were claimed by the consumer.
Example ¶
var client *Client = getExampleClient() // example helper function
key := "12345"
streamId := "12345-1"
group := "g12345"
consumer1 := "c12345-1"
consumer2 := "c12345-2"
client.XGroupCreateWithOptions(context.Background(), key, group, "0", *options.NewXGroupCreateOptions().SetMakeStream())
client.XGroupCreateConsumer(context.Background(), key, group, consumer1)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{
{Field: "entry1_field1", Value: "entry1_value1"},
{Field: "entry1_field2", Value: "entry1_value2"},
},
*options.NewXAddOptions().SetId(streamId),
)
client.XReadGroup(context.Background(), group, consumer1, map[string]string{key: ">"})
result, err := client.XPendingWithOptions(context.Background(),
key,
group,
*options.NewXPendingOptions("-", "+", 10).SetConsumer(consumer1),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
if len(result) == 0 {
fmt.Println("No pending messages")
return
}
response, err := client.XClaimJustId(
context.Background(),
key,
group,
consumer2,
time.Duration(result[0].IdleTime)*time.Millisecond,
[]string{result[0].Id},
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(response)
Output: [12345-1]
func (*Client) XClaimJustIdWithOptions ¶
func (client *Client) XClaimJustIdWithOptions( ctx context.Context, key string, group string, consumer string, minIdleTime time.Duration, ids []string, opts options.XClaimOptions, ) ([]string, error)
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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. group - The name of the consumer group. consumer - The name of the consumer. minIdleTime - The minimum idle time. ids - The ids of the entries to claim. options - Stream claim options.
Return value:
An array of the ids of the entries that were claimed by the consumer.
Example ¶
var client *Client = getExampleClient() // example helper function
key := "12345"
streamId := "12345-1"
group := "g12345"
consumer1 := "c12345-1"
consumer2 := "c12345-2"
client.XGroupCreateWithOptions(context.Background(), key, group, "0", *options.NewXGroupCreateOptions().SetMakeStream())
client.XGroupCreateConsumer(context.Background(), key, group, consumer1)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{
{Field: "entry1_field1", Value: "entry1_value1"},
{Field: "entry1_field2", Value: "entry1_value2"},
},
*options.NewXAddOptions().SetId(streamId),
)
client.XReadGroup(context.Background(), group, consumer1, map[string]string{key: ">"})
result, err := client.XPendingWithOptions(context.Background(),
key,
group,
*options.NewXPendingOptions("-", "+", 10).SetConsumer(consumer1),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
if len(result) == 0 {
fmt.Println("No pending messages")
return
}
opts := options.NewXClaimOptions().SetRetryCount(3)
response, err := client.XClaimJustIdWithOptions(
context.Background(),
key,
group,
consumer2,
time.Duration(result[0].IdleTime)*time.Millisecond,
[]string{result[0].Id},
*opts,
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(response)
Output: [12345-1]
func (*Client) XClaimWithOptions ¶
func (client *Client) XClaimWithOptions( ctx context.Context, key string, group string, consumer string, minIdleTime time.Duration, ids []string, opts options.XClaimOptions, ) (map[string]models.XClaimResponse, error)
Changes the ownership of a pending message.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. group - The name of the consumer group. consumer - The name of the consumer. minIdleTime - The minimum idle time. ids - The ids of the entries to claim. options - Stream claim options.
Return value:
A map[string]models.XClaimResponse where: - Each key is a message/entry ID - Each value is an XClaimResponse containing: - Fields: []FieldValue array of field-value pairs for the claimed entry
Example ¶
var client *Client = getExampleClient() // example helper function
key := "12345"
streamId := "12345-1"
group := "g12345"
consumer1 := "c12345-1"
consumer2 := "c12345-2"
client.XGroupCreateWithOptions(context.Background(), key, group, "0", *options.NewXGroupCreateOptions().SetMakeStream())
client.XGroupCreateConsumer(context.Background(), key, group, consumer1)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{
{Field: "entry1_field1", Value: "entry1_value1"},
{Field: "entry1_field2", Value: "entry1_value2"},
},
*options.NewXAddOptions().SetId(streamId),
)
client.XReadGroup(context.Background(), group, consumer1, map[string]string{key: ">"})
result, err := client.XPendingWithOptions(context.Background(),
key,
group,
*options.NewXPendingOptions("-", "+", 10).SetConsumer(consumer1),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
if len(result) == 0 {
fmt.Println("No pending messages")
return
}
opts := options.NewXClaimOptions().SetRetryCount(3)
response, err := client.XClaimWithOptions(
context.Background(),
key,
group,
consumer2,
time.Duration(result[0].IdleTime)*time.Millisecond,
[]string{result[0].Id},
*opts,
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Printf("Claimed %d message\n", len(response))
// Access fields from the claimed message
for id, claimResponse := range response {
fmt.Printf("Message ID: %s with retry count: %d\n", id, 3)
// Print a sample field if available
if len(claimResponse.Fields) > 0 {
for _, pair := range claimResponse.Fields {
fmt.Printf("Field: %s, Value: %s\n", pair.Field, pair.Value)
break // Just print the first field as an example
}
}
}
Output: Claimed 1 message Message ID: 12345-1 with retry count: 3 Field: entry1_field1, Value: entry1_value1
func (*Client) XDel ¶
Removes the specified entries by id from a stream, and returns the number of entries deleted.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. ids - An array of entry ids.
Return value:
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.
Example ¶
var client *Client = getExampleClient() // example helper function
key := "12345"
client.XAddWithOptions(context.Background(),
key,
[]models.FieldValue{{Field: "field1", Value: "value1"}, {Field: "field2", Value: "value2"}},
*options.NewXAddOptions().SetId("0-1"),
)
count, err := client.XDel(context.Background(), key, []string{"0-1", "0-2", "0-3"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(count)
Output: 1
func (*Client) XGroupCreate ¶
func (client *Client) XGroupCreate(ctx context.Context, key string, group string, id string) (string, error)
Creates a new consumer group uniquely identified by `group` for the stream stored at `key`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
key - The key of the stream.
group - The newly created consumer group name.
id - 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.
Return value:
`"OK"`.
Example ¶
var client *Client = getExampleClient() // example helper function
key := "12345"
streamId := "12345-1"
group := "g12345"
client.XAddWithOptions(context.Background(),
key,
[]models.FieldValue{{Field: "field1", Value: "value1"}, {Field: "field2", Value: "value2"}},
*options.NewXAddOptions().SetId(streamId),
) // This will create the stream if it does not exist
response, err := client.XGroupCreate(context.Background(), key, group, "0") // create the group (no MKSTREAM needed)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(response)
Output: OK
func (*Client) XGroupCreateConsumer ¶
func (client *Client) XGroupCreateConsumer( ctx context.Context, key string, group string, consumer string, ) (bool, error)
XGroupCreateConsumer creates a consumer named `consumer` in the consumer group `group` for the stream stored at `key`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. group - The consumer group name. consumer - The newly created consumer.
Return value:
Returns `true` if the consumer is created. Otherwise, returns `false`.
Example ¶
var client *Client = getExampleClient() // example helper function
key := "12345"
group := "g12345"
consumer := "c12345"
opts := options.NewXGroupCreateOptions().SetMakeStream()
client.XGroupCreateWithOptions(context.Background(), key, group, "0", *opts) // create the group (no MKSTREAM needed)
success, err := client.XGroupCreateConsumer(context.Background(), key, group, consumer)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(success)
Output: true
func (*Client) XGroupCreateWithOptions ¶
func (client *Client) XGroupCreateWithOptions( ctx context.Context, key string, group string, id string, opts options.XGroupCreateOptions, ) (string, error)
Creates a new consumer group uniquely identified by `group` for the stream stored at `key`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
key - The key of the stream.
group - The newly created consumer group name.
id - 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.
opts - The options for the command. See [options.XGroupCreateOptions] for details.
Return value:
`"OK"`.
Example ¶
var client *Client = getExampleClient() // example helper function
key := "12345"
group := "g12345"
opts := options.NewXGroupCreateOptions().SetMakeStream()
response, err := client.XGroupCreateWithOptions(
context.Background(),
key,
group,
"0",
*opts,
) // create the group (no MKSTREAM needed)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(response)
Output: OK
func (*Client) XGroupDelConsumer ¶
func (client *Client) XGroupDelConsumer( ctx context.Context, key string, group string, consumer string, ) (int64, error)
XGroupDelConsumer deletes a consumer named `consumer` in the consumer group `group`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. group - The consumer group name. consumer - The consumer to delete.
Return value:
The number of pending messages the `consumer` had before it was deleted.
Example ¶
var client *Client = getExampleClient() // example helper function
key := "12345"
group := "g12345"
consumer := "c12345"
streamId := "12345-1"
client.XAddWithOptions(context.Background(),
key,
[]models.FieldValue{{Field: "field1", Value: "value1"}, {Field: "field2", Value: "value2"}},
*options.NewXAddOptions().SetId(streamId),
)
client.XGroupCreate(context.Background(), key, group, "0")
client.XGroupCreateConsumer(context.Background(), key, group, consumer)
client.XReadGroup(context.Background(), group, consumer, map[string]string{key: ">"})
count, err := client.XGroupDelConsumer(context.Background(), key, group, consumer)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println("Consumer deleted. Messages pending:", count)
Output: Consumer deleted. Messages pending: 1
func (*Client) XGroupDestroy ¶
Destroys the consumer group `group` for the stream stored at `key`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. group - The consumer group name to delete.
Return value:
`true` if the consumer group is destroyed. Otherwise, `false`.
Example ¶
var client *Client = getExampleClient() // example helper function
key := "12345"
group := "g12345"
opts := options.NewXGroupCreateOptions().SetMakeStream()
client.XGroupCreateWithOptions(context.Background(), key, group, "0", *opts) // create the group (no MKSTREAM needed)
success, err := client.XGroupDestroy(context.Background(), key, group) // destroy the group
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(success)
Output: true
func (*Client) XGroupSetId ¶
func (client *Client) XGroupSetId(ctx context.Context, key string, group string, id string) (string, error)
Sets the last delivered ID for a consumer group.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. group - The consumer group name. id - The stream entry ID that should be set as the last delivered ID for the consumer group.
Return value:
`"OK"`.
Example ¶
var client *Client = getExampleClient() // example helper function
key := "12345"
streamId := "12345-1"
group := "g12345"
consumer := "c12345"
client.XGroupCreateWithOptions(context.Background(), key, group, "0", *options.NewXGroupCreateOptions().SetMakeStream())
client.XGroupCreateConsumer(context.Background(), key, group, consumer)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{
{Field: "entry1_field1", Value: "entry1_value1"},
{Field: "entry1_field2", Value: "entry1_value2"},
},
*options.NewXAddOptions().SetId(streamId),
)
client.XReadGroup(context.Background(), group, consumer, map[string]string{key: ">"})
client.XAck(context.Background(), key, group, []string{streamId}) // ack the message and remove it from the pending list
client.XGroupSetId(
context.Background(),
key,
group,
"0-0",
) // reset the last acknowledged message to 0-0
client.XReadGroup(context.Background(), group, consumer, map[string]string{key: ">"}) // read the group again
summary, err := client.XPending(
context.Background(),
key,
group,
) // get the pending messages, which should include the entry we previously acked
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
jsonSummary, _ := json.Marshal(summary)
fmt.Println(string(jsonSummary))
Output: {"NumOfMessages":1,"StartId":{},"EndId":{},"ConsumerMessages":[{"ConsumerName":"c12345","MessageCount":1}]}
func (*Client) XGroupSetIdWithOptions ¶
func (client *Client) XGroupSetIdWithOptions( ctx context.Context, key string, group string, id string, opts options.XGroupSetIdOptions, ) (string, error)
Sets the last delivered ID for a consumer group.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. group - The consumer group name. id - The stream entry ID that should be set as the last delivered ID for the consumer group. opts - The options for the command. See [options.XGroupSetIdOptions] for details.
Return value:
`"OK"`.
Example ¶
var client *Client = getExampleClient() // example helper function
key := "12345"
streamId1 := "12345-1"
streamId2 := "12345-2"
group := "g12345"
consumer := "c12345"
client.XGroupCreateWithOptions(context.Background(), key, group, "0", *options.NewXGroupCreateOptions().SetMakeStream())
client.XGroupCreateConsumer(context.Background(), key, group, consumer)
client.XAddWithOptions(context.Background(),
key,
[]models.FieldValue{{Field: "field1", Value: "value1"}, {Field: "field2", Value: "value2"}},
*options.NewXAddOptions().SetId(streamId1),
)
client.XAddWithOptions(context.Background(),
key,
[]models.FieldValue{{Field: "field3", Value: "value3"}, {Field: "field4", Value: "value4"}},
*options.NewXAddOptions().SetId(streamId2),
)
client.XReadGroup(context.Background(), group, consumer, map[string]string{key: ">"})
client.XAck(
context.Background(),
key,
group,
[]string{streamId1, streamId2},
) // ack the message and remove it from the pending list
opts := options.NewXGroupSetIdOptionsOptions().SetEntriesRead(1)
client.XGroupSetIdWithOptions(
context.Background(),
key,
group,
"0-0",
*opts,
) // reset the last acknowledged message to 0-0
client.XReadGroup(context.Background(), group, consumer, map[string]string{key: ">"}) // read the group again
summary, err := client.XPending(
context.Background(),
key,
group,
) // get the pending messages, which should include the entry we previously acked
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
jsonSummary, _ := json.Marshal(summary)
fmt.Println(string(jsonSummary))
Output: {"NumOfMessages":2,"StartId":{},"EndId":{},"ConsumerMessages":[{"ConsumerName":"c12345","MessageCount":2}]}
func (*Client) XInfoConsumers ¶
func (client *Client) XInfoConsumers(ctx context.Context, key string, group string) ([]models.XInfoConsumerInfo, error)
Returns the list of all consumers and their attributes for the given consumer group of the stream stored at `key`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. group - The consumer group name.
Return value:
An array of [models.XInfoConsumerInfo], where each element contains the attributes of a consumer for the given consumer group of the stream at `key`.
Example ¶
var client *Client = getExampleClient() // example helper function
key := uuid.NewString()
group := "myGroup"
// create an empty stream with a group
client.XGroupCreateWithOptions(context.Background(), key, group, "0-0", *options.NewXGroupCreateOptions().SetMakeStream())
// add couple of entries
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{{Field: "e1_f1", Value: "e1_v1"}, {Field: "e1_f2", Value: "e1_v2"}},
*options.NewXAddOptions().SetId("0-1"),
)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{{Field: "e2_f1", Value: "e2_v1"}, {Field: "e2_f2", Value: "e2_v2"}},
*options.NewXAddOptions().SetId("0-2"),
)
// read them
client.XReadGroup(context.Background(), group, "myConsumer", map[string]string{key: ">"})
// get the info
time.Sleep(100 * time.Millisecond)
response, err := client.XInfoConsumers(context.Background(), key, group)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Expanded:
fmt.Printf("Consumer name: %s\n", response[0].Name)
fmt.Printf("PEL count: %d\n", response[0].Pending)
// exact values of `Idle` and `Inactive` depend on timing
fmt.Printf("Idle > 0: %t\n", response[0].Idle > 0)
fmt.Printf("Inactive > 0: %t\n", response[0].Inactive.Value() > 0) // Added in version 7.0.0
Output: Consumer name: myConsumer PEL count: 2 Idle > 0: true Inactive > 0: true
func (*Client) XInfoGroups ¶
Returns the list of all consumer groups and their attributes for the stream stored at `key`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream.
Return value:
An array of [models.XInfoGroupInfo], where each element represents the attributes of a consumer group for the stream at `key`.
Example ¶
var client *Client = getExampleClient() // example helper function
key := uuid.NewString()
group := "myGroup"
// create an empty stream with a group
client.XGroupCreateWithOptions(context.Background(), key, group, "0-0", *options.NewXGroupCreateOptions().SetMakeStream())
// add couple of entries
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{{Field: "e1_f1", Value: "e1_v1"}, {Field: "e1_f2", Value: "e1_v2"}},
*options.NewXAddOptions().SetId("0-1"),
)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{{Field: "e2_f1", Value: "e2_v1"}, {Field: "e2_f2", Value: "e2_v2"}},
*options.NewXAddOptions().SetId("0-2"),
)
// read them
client.XReadGroup(context.Background(), group, "myConsumer", map[string]string{key: ">"})
// get the info
response, err := client.XInfoGroups(context.Background(), key)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(response)
// Expanded:
fmt.Printf("Group name: %s\n", response[0].Name)
fmt.Printf("Consumers count: %d\n", response[0].Consumers)
fmt.Printf("PEL count: %d\n", response[0].Pending)
fmt.Printf("Last delivered message: %s\n", response[0].LastDeliveredId)
fmt.Printf("Entries read: %d\n", response[0].EntriesRead.Value()) // Added in version 7.0.0
fmt.Printf("Lag: %d\n", response[0].Lag.Value()) // Added in version 7.0.0
Output: [{myGroup 1 2 0-2 {2 false} {0 false}}] Group name: myGroup Consumers count: 1 PEL count: 2 Last delivered message: 0-2 Entries read: 2 Lag: 0
func (*Client) XInfoStream ¶
func (client *Client) XInfoStream(ctx context.Context, key string) (models.XInfoStreamResponse, error)
Returns information about the stream stored at `key`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream.
Return value:
A [models.XInfoStreamResponse] containing information about the stream stored at key: - Length: the number of entries in the stream - RadixTreeKeys: the number of keys in the underlying radix data structure - RadixTreeNodes: the number of nodes in the underlying radix data structure - Groups: the number of consumer groups defined for the stream - LastGeneratedID: the ID of the least-recently entry that was added to the stream - MaxDeletedEntryID: the maximal entry ID that was deleted from the stream - EntriesAdded: the count of all entries added to the stream during its lifetime - FirstEntry: the ID and field-value tuples of the first entry in the stream - LastEntry: the ID and field-value tuples of the last entry in the stream
Example ¶
var client *Client = getExampleClient() // example helper function
key := "12345"
streamId1 := "12345-1"
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{{Field: "field1", Value: "value1"}},
*options.NewXAddOptions().SetId(streamId1),
)
response, err := client.XInfoStream(context.Background(), key)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Response Structure is as follows:
// {
// "entries-added": 1,
// "first-entry": [
// "12345-1",
// [
// "field1",
// "value1"
// ]
// ],
// "groups": 0,
// "last-entry": [
// "12345-1",
// [
// "field1",
// "value1"
// ]
// ],
// "last-generated-id": "12345-1",
// "length": 1,
// "max-deleted-entry-id": "0-0",
// "radix-tree-keys": 1,
// "radix-tree-nodes": 2,
// "recorded-first-entry-id": "12345-1"
// }
// Output a few entries from the return object.
fmt.Printf("Entries Added: %d\n", response.EntriesAdded.Value())
fmt.Printf("Groups: %d\n", response.Groups)
fmt.Printf("Last generated Id: %s\n", response.LastGeneratedID)
fmt.Printf("Length: %d\n", response.Length)
Output: Entries Added: 1 Groups: 0 Last generated Id: 12345-1 Length: 1
func (*Client) XInfoStreamFullWithOptions ¶
func (client *Client) XInfoStreamFullWithOptions( ctx context.Context, key string, opts options.XInfoStreamOptions, ) (models.XInfoStreamFullOptionsResponse, error)
Returns detailed information about the stream stored at `key`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. opts - Stream info options.
Return value:
A detailed stream information for the given `key`. See the example for a sample response.
Example ¶
var client *Client = getExampleClient() // example helper function
key := "12345"
for i := 1; i <= 5; i++ {
field := fmt.Sprintf("field%d", i)
value := fmt.Sprintf("value%d", i)
streamId := fmt.Sprintf("%s-%d", key, i)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{{Field: field, Value: value}},
*options.NewXAddOptions().SetId(streamId),
)
}
options := options.NewXInfoStreamOptions().SetCount(2)
response, err := client.XInfoStreamFullWithOptions(context.Background(), key, *options)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Print some of response values
fmt.Printf("Total entries: %d\n", len(response.Entries))
fmt.Printf("Entry 1 ID: %s\n", response.Entries[0].ID)
fmt.Printf("Entry 1 Field: %s\n", response.Entries[0].Fields[0])
fmt.Printf("Entry 2 ID: %s\n", response.Entries[1].ID)
fmt.Printf("Entry 2 Field: %s\n", response.Entries[1].Fields[0])
fmt.Printf("Last Generated Id: %s\n", response.LastGeneratedID)
fmt.Printf("Entries Added: %d\n", response.EntriesAdded.Value())
fmt.Printf("Length: %d\n", response.Length)
fmt.Printf("Max Deleted Entry id: %s\n", response.MaxDeletedEntryID.Value())
fmt.Printf("Radix Tree Keys: %d\n", response.RadixTreeKeys)
fmt.Printf("Radix Tree Nodes: %d\n", response.RadixTreeNodes)
fmt.Printf("Recorded First Entry Id: %s\n", response.RecordedFirstEntryId.Value())
Output: Total entries: 2 Entry 1 ID: 12345-1 Entry 1 Field: {field1 value1} Entry 2 ID: 12345-2 Entry 2 Field: {field2 value2} Last Generated Id: 12345-5 Entries Added: 5 Length: 5 Max Deleted Entry id: 0-0 Radix Tree Keys: 1 Radix Tree Nodes: 2 Recorded First Entry Id: 12345-1
func (*Client) XLen ¶
Returns the number of entries in the stream stored at `key`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream.
Return value:
The number of entries in the stream. If `key` does not exist, return 0.
Example ¶
var client *Client = getExampleClient() // example helper function
client.XAdd(
context.Background(),
"mystream",
[]models.FieldValue{{Field: "field1", Value: "foo4"}, {Field: "field2", Value: "bar4"}},
)
count, err := client.XLen(context.Background(), "mystream")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(count)
Output: 1
func (*Client) XPending ¶
func (client *Client) XPending(ctx context.Context, key string, group string) (models.XPendingSummary, error)
Returns stream message summary information for pending messages matching a stream and group.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. group - The consumer group name.
Return value:
An models.XPendingSummary struct that includes a summary with the following fields:
NumOfMessages - The total number of pending messages for this consumer group. StartId - The smallest ID among the pending messages or nil if no pending messages exist. EndId - The greatest ID among the pending messages or nil if no pending messages exists. GroupConsumers - An array of ConsumerPendingMessages with the following fields: ConsumerName - The name of the consumer. MessageCount - The number of pending messages for this consumer.
Example ¶
var client *Client = getExampleClient() // example helper function
key := "12345"
streamId := "12345-1"
group := "g12345"
consumer := "c12345"
client.XGroupCreateWithOptions(context.Background(), key, group, "0", *options.NewXGroupCreateOptions().SetMakeStream())
client.XGroupCreateConsumer(context.Background(), key, group, consumer)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{
{Field: "entry1_field1", Value: "entry1_value1"},
{Field: "entry1_field2", Value: "entry1_value2"},
},
*options.NewXAddOptions().SetId(streamId),
)
client.XReadGroup(context.Background(), group, consumer, map[string]string{key: ">"})
summary, err := client.XPending(context.Background(), key, group)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
jsonSummary, _ := json.Marshal(summary)
fmt.Println(string(jsonSummary))
Output: {"NumOfMessages":1,"StartId":{},"EndId":{},"ConsumerMessages":[{"ConsumerName":"c12345","MessageCount":1}]}
func (*Client) XPendingWithOptions ¶
func (client *Client) XPendingWithOptions( ctx context.Context, key string, group string, opts options.XPendingOptions, ) ([]models.XPendingDetail, error)
Returns stream message summary information for pending messages matching a given range of IDs.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. group - The consumer group name. opts - The options for the command. See [options.XPendingOptions] for details.
Return value:
A slice of models.XPendingDetail structs, where each detail struct includes the following fields:
Id - The ID of the pending message. ConsumerName - The name of the consumer that fetched the message and has still to acknowledge it. IdleTime - The time in milliseconds since the last time the message was delivered to the consumer. DeliveryCount - The number of times this message was delivered.
Example ¶
var client *Client = getExampleClient() // example helper function
key := "12345"
streamId := "12345-1"
group := "g12345"
consumer := "c12345"
client.XGroupCreateWithOptions(context.Background(), key, group, "0", *options.NewXGroupCreateOptions().SetMakeStream())
client.XGroupCreateConsumer(context.Background(), key, group, consumer)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{
{Field: "entry1_field1", Value: "entry1_value1"},
{Field: "entry1_field2", Value: "entry1_value2"},
},
*options.NewXAddOptions().SetId(streamId),
)
client.XReadGroup(context.Background(), group, consumer, map[string]string{key: ">"})
details, err := client.XPendingWithOptions(context.Background(),
key,
group,
*options.NewXPendingOptions("-", "+", 10).SetConsumer(consumer),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
jsonDetails, _ := json.Marshal(details)
// Since IdleTime can vary, check that output has all fields
fields := []string{"\"Id\"", "\"ConsumerName\"", "\"IdleTime\"", "\"DeliveryCount\""}
hasFields := true
jsonStr := string(jsonDetails)
for _, field := range fields {
hasFields = strings.Contains(jsonStr, field)
if !hasFields {
break
}
}
fmt.Println(hasFields)
Output: true
func (*Client) XRange ¶
func (client *Client) XRange( ctx context.Context, key string, start options.StreamBoundary, end options.StreamBoundary, ) ([]models.StreamEntry, error)
Returns stream entries matching a given range of IDs.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
key - The key of the stream.
start - The start position.
Use `options.NewStreamBoundary()` to specify a stream entry ID and its inclusive/exclusive status.
Use `options.NewInfiniteStreamBoundary()` to specify an infinite stream boundary.
end - The end position.
Use `options.NewStreamBoundary()` to specify a stream entry ID and its inclusive/exclusive status.
Use `options.NewInfiniteStreamBoundary()` to specify an infinite stream boundary.
Return value:
An `array` of [models.StreamEntry], where entry data stores an array of pairings with format `[[field, entry], [field, entry], ...]`.
Example ¶
var client *Client = getExampleClient() // example helper function
key := "12345"
streamId1 := "12345-1"
streamId2 := "12345-2"
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{{Field: "field1", Value: "value1"}},
*options.NewXAddOptions().SetId(streamId1),
)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{{Field: "field2", Value: "value2"}},
*options.NewXAddOptions().SetId(streamId2),
)
response, err := client.XRange(context.Background(), key,
options.NewInfiniteStreamBoundary(constants.NegativeInfinity),
options.NewInfiniteStreamBoundary(constants.PositiveInfinity))
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(response)
Output: [{12345-1 [{field1 value1}]} {12345-2 [{field2 value2}]}]
func (*Client) XRangeWithOptions ¶
func (client *Client) XRangeWithOptions( ctx context.Context, key string, start options.StreamBoundary, end options.StreamBoundary, opts options.XRangeOptions, ) ([]models.StreamEntry, error)
Returns stream entries matching a given range of IDs.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
key - The key of the stream.
start - The start position.
Use `options.NewStreamBoundary()` to specify a stream entry ID and its inclusive/exclusive status.
Use `options.NewInfiniteStreamBoundary()` to specify an infinite stream boundary.
end - The end position.
Use `options.NewStreamBoundary()` to specify a stream entry ID and its inclusive/exclusive status.
Use `options.NewInfiniteStreamBoundary()` to specify an infinite stream boundary.
opts - Stream range options.
Return value:
An `array` of [models.StreamEntry], where entry data stores an array of pairings with format `[[field, entry], [field, entry], ...]`. Returns `nil` if `count` is non-positive.
Example ¶
var client *Client = getExampleClient() // example helper function
key := "12345"
streamId1, _ := client.XAdd(context.Background(), key, []models.FieldValue{{Field: "field1", Value: "value1"}})
streamId2, _ := client.XAdd(context.Background(), key, []models.FieldValue{{Field: "field2", Value: "value2"}})
response, err := client.XRangeWithOptions(context.Background(), key,
options.NewStreamBoundary(streamId1, true),
options.NewStreamBoundary(streamId2, true),
*options.NewXRangeOptions().SetCount(1))
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(len(response))
Output: 1
func (*Client) XRead ¶
func (client *Client) XRead(ctx context.Context, keysAndIds map[string]string) (map[string]models.StreamResponse, error)
Reads entries from the given streams.
Note:
When in cluster mode, all keys in `keysAndIds` must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keysAndIds - A map of keys and entry IDs to read from.
Return value:
A map[string]models.StreamResponse where:
- Each key is a stream name
- Each value is a StreamResponse containing:
- Entries: []StreamEntry, where each StreamEntry has:
- ID: The unique identifier of the entry
- Fields: []FieldValue array of field-value pairs for the entry.
Example ¶
var client *Client = getExampleClient() // example helper function
key := "12345"
streamId := "12345-1"
client.XAddWithOptions(context.Background(),
key,
[]models.FieldValue{{Field: "field1", Value: "value1"}, {Field: "field2", Value: "value2"}},
*options.NewXAddOptions().SetId(streamId),
)
response, err := client.XRead(context.Background(), map[string]string{key: "0-0"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Check that we have the stream with the correct name in the map
streamResponse, exists := response[key]
if exists {
fmt.Printf("Stream exists: %v\n", exists)
fmt.Printf("Number of entries: %d\n", len(streamResponse.Entries))
if len(streamResponse.Entries) > 0 {
entry := streamResponse.Entries[0]
fmt.Printf("Entry ID: %s\n", entry.ID)
fmt.Printf("Entry fields: %v\n", entry.Fields)
}
} else {
fmt.Println("Stream does not exist")
}
Output: Stream exists: true Number of entries: 1 Entry ID: 12345-1 Entry fields: [{field1 value1} {field2 value2}]
func (*Client) XReadGroup ¶
func (client *Client) XReadGroup( ctx context.Context, group string, consumer string, keysAndIds map[string]string, ) (map[string]models.StreamResponse, error)
Reads entries from the given streams owned by a consumer group.
Note:
When in cluster mode, all keys in `keysAndIds` must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. group - The consumer group name. consumer - The group consumer. keysAndIds - A map of keys and entry IDs to read from.
Return value:
A map[string]models.StreamResponse where:
- Each key is a stream name
- Each value is a StreamResponse containing:
- Entries: []StreamEntry, where each StreamEntry has:
- ID: The unique identifier of the entry
- Fields: map[string]string of field-value pairs for the entry
Example ¶
var client *Client = getExampleClient() // example helper function
key := "12345"
streamId := "12345-1"
group := uuid.NewString()
consumer := uuid.NewString()
client.XGroupCreateWithOptions(context.Background(), key, group, "0", *options.NewXGroupCreateOptions().SetMakeStream())
client.XGroupCreateConsumer(context.Background(), key, group, consumer)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{
{Field: "entry1_field1", Value: "entry1_value1"},
{Field: "entry1_field2", Value: "entry1_value2"},
},
*options.NewXAddOptions().SetId(streamId),
)
response, err := client.XReadGroup(context.Background(), group, consumer, map[string]string{key: "0"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Check that we have the stream with the correct name in the map
streamResponse, exists := response[key]
if exists {
fmt.Printf("Stream exists: %v\n", exists)
fmt.Printf("Number of entries: %d\n", len(streamResponse.Entries))
} else {
fmt.Println("Stream does not exist")
}
Output: Stream exists: true Number of entries: 0
func (*Client) XReadGroupWithOptions ¶
func (client *Client) XReadGroupWithOptions( ctx context.Context, group string, consumer string, keysAndIds map[string]string, opts options.XReadGroupOptions, ) (map[string]models.StreamResponse, error)
Reads entries from the given streams owned by a consumer group.
Note:
When in cluster mode, all keys in `keysAndIds` must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. group - The consumer group name. consumer - The group consumer. keysAndIds - A map of keys and entry IDs to read from. opts - Options detailing how to read the stream.
Return value:
A map[string]models.StreamResponse where:
- Each key is a stream name
- Each value is a StreamResponse containing:
- Entries: []StreamEntry, where each StreamEntry has:
- ID: The unique identifier of the entry
- Fields: map[string]string of field-value pairs for the entry
Example ¶
var client *Client = getExampleClient() // example helper function
key := "12345"
streamId := "12345-1"
group := uuid.NewString()
consumer := uuid.NewString()
client.XGroupCreateWithOptions(context.Background(), key, group, "0", *options.NewXGroupCreateOptions().SetMakeStream())
client.XGroupCreateConsumer(context.Background(), key, group, consumer)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{
{Field: "entry1_field1", Value: "entry1_value1"},
{Field: "entry1_field2", Value: "entry1_value2"},
},
*options.NewXAddOptions().SetId(streamId),
)
options := options.NewXReadGroupOptions().SetNoAck()
response, err := client.XReadGroupWithOptions(context.Background(), group, consumer, map[string]string{key: ">"}, *options)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Check that we have the stream with the correct name in the map
streamResponse, exists := response[key]
if exists {
fmt.Printf("Stream exists: %v\n", exists)
fmt.Printf("Number of entries: %d\n", len(streamResponse.Entries))
if len(streamResponse.Entries) > 0 {
entry := streamResponse.Entries[0]
fmt.Printf("Entry ID: %s\n", entry.ID)
fmt.Printf("Entry fields: %v\n", entry.Fields)
}
} else {
fmt.Println("Stream does not exist")
}
Output: Stream exists: true Number of entries: 1 Entry ID: 12345-1 Entry fields: [{entry1_field1 entry1_value1} {entry1_field2 entry1_value2}]
func (*Client) XReadWithOptions ¶
func (client *Client) XReadWithOptions( ctx context.Context, keysAndIds map[string]string, opts options.XReadOptions, ) (map[string]models.StreamResponse, error)
Reads entries from the given streams.
Note:
When in cluster mode, all keys in `keysAndIds` must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keysAndIds - A map of keys and entry IDs to read from. opts - Options detailing how to read the stream.
Return value:
A map[string]models.StreamResponse where:
- Each key is a stream name
- Each value is a StreamResponse containing:
- Entries: []StreamEntry, where each StreamEntry has:
- ID: The unique identifier of the entry
- Fields: []FieldValue array of field-value pairs for the entry
Example ¶
var client *Client = getExampleClient() // example helper function
key := "12345"
streambase := 1
genStreamId := func(key string, base int, offset int) string { return fmt.Sprintf("%s-%d", key, base+offset) } // helper function to generate stream ids
client.XAddWithOptions(context.Background(),
key,
[]models.FieldValue{{Field: "field1", Value: "value1"}, {Field: "field2", Value: "value2"}},
*options.NewXAddOptions().SetId(genStreamId(key, streambase, 0)),
)
client.XAddWithOptions(context.Background(),
key,
[]models.FieldValue{{Field: "field3", Value: "value3"}, {Field: "field4", Value: "value4"}},
*options.NewXAddOptions().SetId(genStreamId(key, streambase, 1)),
)
response, err := client.XReadWithOptions(context.Background(),
map[string]string{key: genStreamId(key, streambase, 0)},
*options.NewXReadOptions().SetCount(1),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Check that we have the stream with the correct name in the map
streamResponse, exists := response[key]
if exists {
fmt.Printf("Stream exists: %v\n", exists)
fmt.Printf("Number of entries: %d\n", len(streamResponse.Entries))
if len(streamResponse.Entries) > 0 {
entry := streamResponse.Entries[0]
fmt.Printf("Entry ID: %s\n", entry.ID)
fmt.Printf("Entry fields: %v\n", entry.Fields)
}
} else {
fmt.Println("Stream does not exist")
}
Output: Stream exists: true Number of entries: 1 Entry ID: 12345-2 Entry fields: [{field3 value3} {field4 value4}]
func (*Client) XRevRange ¶
func (client *Client) XRevRange( ctx context.Context, key string, start options.StreamBoundary, end options.StreamBoundary, ) ([]models.StreamEntry, error)
Returns stream entries matching a given range of IDs in reverse order. Equivalent to `XRange` but returns entries in reverse order.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
key - The key of the stream.
start - The start position.
Use `options.NewStreamBoundary()` to specify a stream entry ID and its inclusive/exclusive status.
Use `options.NewInfiniteStreamBoundary()` to specify an infinite stream boundary.
end - The end position.
Use `options.NewStreamBoundary()` to specify a stream entry ID and its inclusive/exclusive status.
Use `options.NewInfiniteStreamBoundary()` to specify an infinite stream boundary.
Return value:
An `array` of [models.StreamEntry], where entry data stores an array of pairings with format `[[field, entry], [field, entry], ...]`.
Example ¶
var client *Client = getExampleClient() // example helper function
key := "12345"
streamId1 := "12345-1"
streamId2 := "12345-2"
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{{Field: "field1", Value: "value1"}},
*options.NewXAddOptions().SetId(streamId1),
)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{{Field: "field2", Value: "value2"}},
*options.NewXAddOptions().SetId(streamId2),
)
response, err := client.XRevRange(context.Background(), key,
options.NewStreamBoundary(streamId2, true),
options.NewStreamBoundary(streamId1, true))
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(response)
Output: [{12345-2 [{field2 value2}]} {12345-1 [{field1 value1}]}]
func (*Client) XRevRangeWithOptions ¶
func (client *Client) XRevRangeWithOptions( ctx context.Context, key string, start options.StreamBoundary, end options.StreamBoundary, opts options.XRangeOptions, ) ([]models.StreamEntry, error)
Returns stream entries matching a given range of IDs in reverse order. Equivalent to `XRange` but returns entries in reverse order.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
key - The key of the stream.
start - The start position.
Use `options.NewStreamBoundary()` to specify a stream entry ID and its inclusive/exclusive status.
Use `options.NewInfiniteStreamBoundary()` to specify an infinite stream boundary.
end - The end position.
Use `options.NewStreamBoundary()` to specify a stream entry ID and its inclusive/exclusive status.
Use `options.NewInfiniteStreamBoundary()` to specify an infinite stream boundary.
opts - Stream range options.
Return value:
An `array` of [models.StreamEntry], where entry data stores an array of pairings with format `[[field, entry], [field, entry], ...]`. Returns `nil` if `count` is non-positive.
Example ¶
var client *Client = getExampleClient() // example helper function
key := "12345"
streamId1 := "12345-1"
streamId2 := "12345-2"
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{{Field: "field1", Value: "value1"}},
*options.NewXAddOptions().SetId(streamId1),
)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{{Field: "field2", Value: "value2"}},
*options.NewXAddOptions().SetId(streamId2),
)
response, err := client.XRevRangeWithOptions(context.Background(), key,
options.NewStreamBoundary(streamId2, true),
options.NewStreamBoundary(streamId1, true),
*options.NewXRangeOptions().SetCount(2))
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(response)
Output: [{12345-2 [{field2 value2}]} {12345-1 [{field1 value1}]}]
func (*Client) XTrim ¶
func (client *Client) XTrim(ctx context.Context, key string, options options.XTrimOptions) (int64, error)
Trims the stream by evicting older entries.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. options - Stream trim options
Return value:
The number of entries deleted from the stream.
Example ¶
var client *Client = getExampleClient() // example helper function
client.XAdd(
context.Background(),
"mystream",
[]models.FieldValue{{Field: "field1", Value: "foo4"}, {Field: "field2", Value: "bar4"}},
)
client.XAdd(
context.Background(),
"mystream",
[]models.FieldValue{{Field: "field3", Value: "foo4"}, {Field: "field4", Value: "bar4"}},
)
count, err := client.XTrim(context.Background(), "mystream", *options.NewXTrimOptionsWithMaxLen(0).SetExactTrimming())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(count)
Output: 2
func (*Client) ZAdd ¶
func (client *Client) ZAdd( ctx context.Context, key string, membersScoreMap map[string]float64, ) (int64, error)
Adds one or more members to a sorted set, or updates their scores. Creates the key if it doesn't exist.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the set. membersScoreMap - A map of members to their scores.
Return value:
The number of members added to the set.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.ZAdd(context.Background(), "key1", map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 3
func (*Client) ZAddIncr ¶
func (client *Client) ZAddIncr( ctx context.Context, key string, member string, increment float64, ) (float64, error)
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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. member - A member in the sorted set to increment. increment - The score to increment the member.
Return value:
The new score of the member.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.ZAddIncr(context.Background(), "key1", "one", 1.0)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 1
func (*Client) ZAddIncrWithOptions ¶
func (client *Client) ZAddIncrWithOptions( ctx context.Context, key string, member string, increment float64, opts options.ZAddOptions, ) (models.Result[float64], error)
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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. member - A member in the sorted set to increment. increment - The score to increment the member. opts - The options for the command. See [ZAddOptions] for details.
Return value:
The new score of the member. If there was a conflict with the options, the operation aborts and `nil` is returned.
Example ¶
var client *Client = getExampleClient() // example helper function
opts, err := options.NewZAddOptions().SetChanged(true) // should return an error
result, err := client.ZAddIncrWithOptions(context.Background(), "key1", "one", 1.0, *opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: Glide example failed with an error: incr cannot be set when changed is true {0 true}
func (*Client) ZAddWithOptions ¶
func (client *Client) ZAddWithOptions( ctx context.Context, key string, membersScoreMap map[string]float64, opts options.ZAddOptions, ) (int64, error)
Adds one or more members to a sorted set, or updates their scores. Creates the key if it doesn't exist.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the set. membersScoreMap - A map of members to their scores. opts - The options for the command. See [Client.ZAddOptions] [ClusterClient.ZAddOptions] for details.
Return value:
The number of members added to the set. If `CHANGED` is set, the number of members that were updated.
Example ¶
var client *Client = getExampleClient() // example helper function
opts, err := options.NewZAddOptions().SetChanged(true)
result, err := client.ZAddWithOptions(context.Background(),
"key1",
map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0},
*opts,
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 3
func (*Client) ZCard ¶
Returns the cardinality (number of elements) of the sorted set stored at `key`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the set.
Return value:
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`. If `key` holds a value that is not a sorted set, an error is returned.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.ZAdd(context.Background(), "key1", map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0})
result1, err := client.ZCard(context.Background(), "key1")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 3 3
func (*Client) ZCount ¶
func (client *Client) ZCount(ctx context.Context, key string, rangeOptions options.ZCountRange) (int64, error)
Returns the number of members in the sorted set stored at `key` with scores between `min` and `max` score.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the set. rangeOptions - Contains `min` and `max` score. `min` contains the minimum score to count from. `max` contains the maximum score to count up to. Can be positive/negative infinity, or specific score and inclusivity.
Return value:
The number of members in the specified score range.
Example ¶
var client *Client = getExampleClient() // example helper function
zCountRange := options.NewZCountRange(
options.NewInclusiveScoreBoundary(2.0),
options.NewInfiniteScoreBoundary(constants.PositiveInfinity),
)
result, err := client.ZAdd(
context.Background(),
"key1",
map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0, "four": 4.0},
)
result1, err := client.ZCount(context.Background(), "key1", *zCountRange)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 4 3
func (*Client) ZDiff ¶
Returns the difference between the first sorted set and all the successive sorted sets. To get the elements with their scores, see Client.ZDiffWithScores or ClusterClient.ZDiffWithScores.
Note:
When in cluster mode, all `keys` must map to the same hash slot.
Since:
Valkey 6.2.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - The keys of the sorted sets.
Return value:
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.
Example ¶
var client *Client = getExampleClient() // example helper function
client.ZAdd(context.Background(), "key1", map[string]float64{"a": 1.0, "b": 2.5, "c": 3.0, "d": 4.0})
client.ZAdd(context.Background(), "key2", map[string]float64{"b": 1.0, "c": 2.5, "d": 3.0, "e": 4.0})
result, err := client.ZDiff(context.Background(), []string{"key1", "key2"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [a]
func (*Client) ZDiffStore ¶
func (client *Client) ZDiffStore(ctx context.Context, destination string, keys []string) (int64, error)
Calculates the difference between the first sorted set and all the successive sorted sets at `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.
Note:
When in cluster mode, `destination` and all `keys` must map to the same hash slot.
Since:
Valkey 6.2.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. destination - The key for the resulting sorted set. keys - The keys of the sorted sets to compare.
Return value:
The number of members in the resulting sorted set stored at `destination`.
Example ¶
var client *Client = getExampleClient() // example helper function
client.ZAdd(context.Background(), "key1", map[string]float64{"a": 1.0, "b": 2.5, "c": 3.0, "d": 4.0})
client.ZAdd(context.Background(), "key2", map[string]float64{"b": 1.0, "c": 2.5, "d": 3.0, "e": 4.0})
result, err := client.ZDiffStore(context.Background(), "dest", []string{"key1", "key2"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 1
func (*Client) ZDiffWithScores ¶
func (client *Client) ZDiffWithScores(ctx context.Context, keys []string) ([]models.MemberAndScore, error)
Returns the difference between the first sorted set and all the successive sorted sets.
Note:
When in cluster mode, all `keys` must map to the same hash slot.
Since:
Valkey 6.2.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - The keys of the sorted sets.
Return value:
An array 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.
Example ¶
var client *Client = getExampleClient() // example helper function
client.ZAdd(context.Background(), "key1", map[string]float64{"a": 1.0, "b": 2.5, "c": 3.0, "d": 4.0})
client.ZAdd(context.Background(), "key2", map[string]float64{"b": 1.0, "c": 2.5, "d": 3.0, "e": 4.0})
result, err := client.ZDiffWithScores(context.Background(), []string{"key1", "key2"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [{a 1}]
func (*Client) ZIncrBy ¶
func (client *Client) ZIncrBy(ctx context.Context, key string, increment float64, member string) (float64, error)
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 with the specified member as its sole member is created.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. increment - The score increment. member - A member of the sorted set.
Return value:
The new score of member.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.ZAdd(context.Background(), "key1", map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0})
result1, err := client.ZIncrBy(context.Background(), "key1", 3.0, "two")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 3 5
func (*Client) ZInter ¶
Returns the intersection of members from sorted sets specified by the given `keys`. To get the elements with their scores, see Client.ZInterWithScores or ClusterClient.ZInterWithScores.
Note:
When in cluster mode, all keys must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - The keys of the sorted sets, see - [options.KeyArray].
Return value:
The resulting sorted set from the intersection.
Example ¶
var client *Client = getExampleClient() // example helper function
client.ZAdd(context.Background(), "key1", map[string]float64{"a": 1.0, "b": 2.5, "c": 3.0, "d": 4.0})
client.ZAdd(context.Background(), "key2", map[string]float64{"b": 1.0, "c": 2.5, "d": 3.0, "e": 4.0})
result, err := client.ZInter(context.Background(), options.KeyArray{
Keys: []string{"key1", "key2"},
})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [b c d]
func (*Client) ZInterCard ¶
Returns the cardinality of the intersection of the sorted sets specified by `keys`.
Note:
When in cluster mode, all keys must map to the same hash slot.
Since:
Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - The keys of the sorted sets.
Return value:
The cardinality of the intersection of the sorted sets.
Example ¶
var client *Client = getExampleClient() // example helper function
key1 := "{testkey}-1"
key2 := "{testkey}-2"
client.ZAdd(context.Background(), key1, map[string]float64{"a": 1.0, "b": 2.0, "c": 3.0, "d": 4.0})
client.ZAdd(context.Background(), key2, map[string]float64{"a": 1.0, "b": 2.0, "c": 3.0, "e": 4.0})
res, err := client.ZInterCard(context.Background(), []string{key1, key2})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(res)
Output: 3
func (*Client) ZInterCardWithOptions ¶
func (client *Client) ZInterCardWithOptions( ctx context.Context, keys []string, options options.ZInterCardOptions, ) (int64, error)
Returns the cardinality of the intersection of the sorted sets specified by `keys`. If the intersection cardinality reaches `options.limit` partway through the computation, the algorithm will exit early and yield `options.limit` as the cardinality.
Note:
When in cluster mode, all keys must map to the same hash slot.
Since:
Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - The keys of the sorted sets. options - The options for the ZInterCard command, see - [options.ZInterCardOptions].
Return value:
The cardinality of the intersection of the sorted sets.
Example ¶
var client *Client = getExampleClient() // example helper function
key1 := "{testkey}-1"
key2 := "{testkey}-2"
client.ZAdd(context.Background(), key1, map[string]float64{"a": 1.0, "b": 2.0, "c": 3.0, "d": 4.0})
client.ZAdd(context.Background(), key2, map[string]float64{"a": 1.0, "b": 2.0, "c": 3.0, "e": 4.0})
res, err := client.ZInterCardWithOptions(context.Background(),
[]string{key1, key2},
*options.NewZInterCardOptions().SetLimit(5),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(res)
Output: 3
func (*Client) ZInterStore ¶
func (client *Client) ZInterStore( ctx context.Context, destination string, keysOrWeightedKeys options.KeysOrWeightedKeys, ) (int64, error)
Computes the intersection of sorted sets given by the specified `keysOrWeightedKeys` and stores the result in `destination`. If `destination` already exists, it is overwritten. Otherwise, a new sorted set will be created.
Note:
When in cluster mode, `destination` and all keys in `keysOrWeightedKeys` must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
destination - The destination key for the result.
keysOrWeightedKeys - The keys or weighted keys of the sorted sets, see - [options.KeysOrWeightedKeys].
- Use `options.NewKeyArray()` for keys only.
- Use `options.NewWeightedKeys()` for weighted keys with score multipliers.
Return value:
The number of elements in the resulting sorted set stored at `destination`.
Example ¶
var client *Client = getExampleClient() // example helper function
client.ZAdd(context.Background(), "key1", map[string]float64{"a": 1.0, "b": 2.5, "c": 3.0, "d": 4.0})
client.ZAdd(context.Background(), "key2", map[string]float64{"b": 1.0, "c": 2.5, "d": 3.0, "e": 4.0})
result, err := client.ZInterStore(context.Background(), "dest", options.KeyArray{
Keys: []string{"key1", "key2"},
})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 3
func (*Client) ZInterStoreWithOptions ¶
func (client *Client) ZInterStoreWithOptions( ctx context.Context, destination string, keysOrWeightedKeys options.KeysOrWeightedKeys, zInterOptions options.ZInterOptions, ) (int64, error)
Computes the intersection of sorted sets given by the specified `keysOrWeightedKeys` and stores the result in `destination`. If `destination` already exists, it is overwritten. Otherwise, a new sorted set will be created.
Note:
When in cluster mode, `destination` and all keys in `keysOrWeightedKeys` must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
destination - The destination key for the result.
keysOrWeightedKeys - The keys or weighted keys of the sorted sets, see - [options.KeysOrWeightedKeys].
- Use `options.NewKeyArray()` for keys only.
- Use `options.NewWeightedKeys()` for weighted keys with score multipliers.
options - The options for the ZInterStore command, see - [options.ZInterOptions].
Optional `aggregate` option specifies the aggregation strategy to apply when combining the scores of
elements.
Return value:
The number of elements in the resulting sorted set stored at `destination`.
Example ¶
var client *Client = getExampleClient() // example helper function
client.ZAdd(context.Background(), "key1", map[string]float64{"a": 1.0, "b": 2.5, "c": 3.0, "d": 4.0})
client.ZAdd(context.Background(), "key2", map[string]float64{"b": 1.0, "c": 2.5, "d": 3.0, "e": 4.0})
result, err := client.ZInterStoreWithOptions(context.Background(),
"dest",
options.KeyArray{
Keys: []string{"key1", "key2"},
},
*options.NewZInterOptions().SetAggregate(options.AggregateSum),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 3
func (*Client) ZInterWithScores ¶
func (client *Client) ZInterWithScores( ctx context.Context, keysOrWeightedKeys options.KeysOrWeightedKeys, zInterOptions options.ZInterOptions, ) ([]models.MemberAndScore, error)
Returns the intersection of members and their scores from sorted sets specified by the given `keysOrWeightedKeys`.
Note:
When in cluster mode, all keys in `keysOrWeightedKeys` must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
keysOrWeightedKeys - The keys or weighted keys of the sorted sets, see - [options.KeysOrWeightedKeys].
- Use `options.NewKeyArray()` for keys only.
- Use `options.NewWeightedKeys()` for weighted keys with score multipliers.
options - The options for the ZInter command, see - [options.ZInterOptions].
Optional `aggregate` option specifies the aggregation strategy to apply when combining the scores of
elements.
Return value:
An array of `models.MemberAndScore` objects, 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.
Example ¶
var client *Client = getExampleClient() // example helper function
client.ZAdd(context.Background(), "key1", map[string]float64{"a": 1.0, "b": 2.5, "c": 3.0, "d": 4.0})
client.ZAdd(context.Background(), "key2", map[string]float64{"b": 1.0, "c": 2.5, "d": 3.0, "e": 4.0})
result, err := client.ZInterWithScores(context.Background(),
options.KeyArray{
Keys: []string{"key1", "key2"},
},
*options.NewZInterOptions().SetAggregate(options.AggregateSum),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [{b 3.5} {c 5.5} {d 7}]
func (*Client) ZLexCount ¶
func (client *Client) ZLexCount(ctx context.Context, key string, rangeQuery options.RangeByLex) (int64, error)
Returns the number of elements in the sorted set at key with a value between min and max.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. rangeQuery - The range query to apply to the sorted set.
Return value:
The number of elements in the sorted set at key with a value between min and max.
Example ¶
var client *Client = getExampleClient() // example helper function
client.ZAdd(context.Background(), "key1", map[string]float64{"a": 1.0, "b": 2.0, "c": 3.0, "d": 4.0})
result, err := client.ZLexCount(context.Background(), "key1",
*options.NewRangeByLexQuery(
options.NewLexBoundary("a", false),
options.NewLexBoundary("c", true),
),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 2
func (*Client) ZMPop ¶
func (client *Client) ZMPop( ctx context.Context, keys []string, scoreFilter constants.ScoreFilter, ) (models.Result[models.KeyWithArrayOfMembersAndScores], error)
Pops one or more member-score pairs from the first non-empty sorted set, with the given keys being checked in the order provided.
Note:
When in cluster mode, all keys must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - An array of keys to check for elements. scoreFilter - Pop criteria - either [constants.MIN] or [constants.MAX] to pop members with the lowest/highest scores.
Return value:
A `models.KeyWithArrayOfMembersAndScores` struct containing: - The key from which the elements were popped. - An array of member-score pairs of the popped elements. Returns `nil` if no member could be popped.
Example ¶
var client *Client = getExampleClient() // example helper function
// Add members to a sorted set
client.ZAdd(context.Background(), "mySortedSet", map[string]float64{"a": 1.0, "b": 2.0, "c": 3.0})
// Pop the lowest-score member
res, err := client.ZMPop(context.Background(), []string{"mySortedSet"}, constants.MIN)
if err != nil {
fmt.Println("Glide example failed with an error:", err)
return
}
value := res.Value()
fmt.Printf("{Key: %q, MembersAndScores: [", value.Key)
for i, member := range value.MembersAndScores {
if i > 0 {
fmt.Print(", ")
}
fmt.Printf("{Member: %q, Score: %.1f}", member.Member, member.Score)
}
fmt.Println("]}")
Output: {Key: "mySortedSet", MembersAndScores: [{Member: "a", Score: 1.0}]}
func (*Client) ZMPopWithOptions ¶
func (client *Client) ZMPopWithOptions( ctx context.Context, keys []string, scoreFilter constants.ScoreFilter, opts options.ZMPopOptions, ) (models.Result[models.KeyWithArrayOfMembersAndScores], error)
Removes and returns up to `count` members from the first non-empty sorted set among the provided `keys`, based on the specified `scoreFilter` criteria.
Note:
When in cluster mode, all keys must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - A list of keys representing sorted sets to check for elements. scoreFilter - Pop criteria - either [constants.MIN] or [constants.MAX] to pop members with the lowest/highest scores. opts - Additional options, such as specifying the maximum number of elements to pop.
Return value:
A `Result` containing a `models.KeyWithArrayOfMembersAndScores` object. If no elements could be popped from the provided keys, returns `nil`.
Example ¶
var client *Client = getExampleClient() // example helper function
client.ZAdd(context.Background(), "mySortedSet", map[string]float64{"a": 1.0, "b": 2.0, "c": 3.0, "d": 4.0})
opts := *options.NewZMPopOptions().SetCount(2)
res, err := client.ZMPopWithOptions(context.Background(), []string{"mySortedSet"}, constants.MAX, opts)
if err != nil {
fmt.Println("Glide example failed with an error:", err)
return
}
value := res.Value()
sort.Slice(value.MembersAndScores, func(i, j int) bool {
return value.MembersAndScores[i].Score > value.MembersAndScores[j].Score
})
fmt.Printf("{Key: %q, MembersAndScores: [", value.Key)
for i, member := range value.MembersAndScores {
if i > 0 {
fmt.Print(", ")
}
fmt.Printf("{Member: %q, Score: %.1f}", member.Member, member.Score)
}
fmt.Println("]}")
Output: {Key: "mySortedSet", MembersAndScores: [{Member: "d", Score: 4.0}, {Member: "c", Score: 3.0}]}
func (*Client) ZMScore ¶
func (client *Client) ZMScore(ctx context.Context, key string, members []string) ([]models.Result[float64], error)
Returns the scores associated with the specified `members` in the sorted set stored at `key`.
Since:
Valkey 6.2.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. members - A list of members in the sorted set.
Return value:
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 `nil`.
Example ¶
var client *Client = getExampleClient() // example helper function
client.ZAdd(context.Background(), "key1", map[string]float64{"a": 1.0, "b": 2.5, "c": 3.0, "d": 4.0})
result, err := client.ZMScore(context.Background(), "key1", []string{"c", "b", "e"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// If the key does not exist, an empty string is returned
fmt.Println(result)
Output: [{3 false} {2.5 false} {0 true}]
func (*Client) ZPopMax ¶
Removes and returns the member with the highest score from the sorted set stored at the specified `key`.
see valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set.
Return value:
A map containing the removed member and its corresponding score. If `key` doesn't exist, it will be treated as an empty sorted set and the command returns an empty map.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.ZAdd(context.Background(), "key1", map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0})
result1, err := client.ZPopMax(context.Background(), "key1")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 3 map[three:3]
func (*Client) ZPopMaxWithOptions ¶
func (client *Client) ZPopMaxWithOptions( ctx context.Context, key string, options options.ZPopOptions, ) (map[string]float64, error)
Removes and returns up to `count` members with the highest scores from the sorted set stored at the specified `key`.
see valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. count - The number of members to remove.
Return value:
A map containing the removed members and their corresponding scores. If `key` doesn't exist, it will be treated as an empty sorted set and the command returns an empty map.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.ZAdd(context.Background(), "key1", map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0})
opts := options.NewZPopOptions().SetCount(2)
result1, err := client.ZPopMaxWithOptions(context.Background(), "key1", *opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 3 map[three:3 two:2]
func (*Client) ZPopMin ¶
Removes and returns the member with the lowest score from the sorted set stored at the specified `key`.
see valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set.
Return value:
A map containing the removed member and its corresponding score. If `key` doesn't exist, it will be treated as an empty sorted set and the command returns an empty map.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.ZAdd(context.Background(), "key1", map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0})
result1, err := client.ZPopMin(context.Background(), "key1")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 3 map[one:1]
func (*Client) ZPopMinWithOptions ¶
func (client *Client) ZPopMinWithOptions( ctx context.Context, key string, options options.ZPopOptions, ) (map[string]float64, error)
Removes and returns multiple members with the lowest scores from the sorted set stored at the specified `key`.
see valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. options - Pop options, see [options.ZPopOptions].
Return value:
A map containing the removed members and their corresponding scores. If `key` doesn't exist, it will be treated as an empty sorted set and the command returns an empty map.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.ZAdd(context.Background(), "key1", map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0})
opts := options.NewZPopOptions().SetCount(2)
result1, err := client.ZPopMinWithOptions(context.Background(), "key1", *opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 3 map[one:1 two:2]
func (*Client) ZRandMember ¶
Returns a random member from the sorted set stored at `key`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set.
Return value:
A string representing a random member from the sorted set. If the sorted set does not exist or is empty, the response will be `nil`.
Example ¶
var client *Client = getExampleClient() // example helper function
client.ZAdd(context.Background(), "key1", map[string]float64{"a": 1.0, "b": 2.0, "c": 3.0, "d": 4.0})
result, err := client.ZRandMember(context.Background(), "key2")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// If the key does not exist, an empty string is returned
fmt.Println(result.Value() == "")
Output: true
func (*Client) ZRandMemberWithCount ¶
func (client *Client) ZRandMemberWithCount(ctx context.Context, key string, count int64) ([]string, error)
Returns multiple random members from the sorted set stored at `key`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. count - The number of field names to return. If `count` is positive, returns unique elements. If negative, allows for duplicates.
Return value:
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.
Example ¶
var client *Client = getExampleClient() // example helper function
client.ZAdd(context.Background(), "key1", map[string]float64{"a": 1.0, "b": 2.0, "c": 3.0, "d": 4.0})
result, err := client.ZRandMemberWithCount(context.Background(), "key1", 4)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// If the key does not exist, an empty string is returned
fmt.Println(result)
Output: [d c b a]
func (*Client) ZRandMemberWithCountWithScores ¶
func (client *Client) ZRandMemberWithCountWithScores( ctx context.Context, key string, count int64, ) ([]models.MemberAndScore, error)
Returns random members with scores from the sorted set stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. count - The number of field names to return. If `count` is positive, returns unique elements. If negative, allows for duplicates.
Return value:
An array of `models.MemberAndScore` objects, 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.
Example ¶
var client *Client = getExampleClient() // example helper function
client.ZAdd(context.Background(), "key1", map[string]float64{"a": 1.0, "b": 2.0, "c": 3.0, "d": 4.0})
result, err := client.ZRandMemberWithCountWithScores(context.Background(), "key1", 4)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// If the key does not exist, an empty string is returned
fmt.Println(result)
Output: [{d 4} {c 3} {b 2} {a 1}]
func (*Client) ZRange ¶
func (client *Client) ZRange(ctx context.Context, key string, rangeQuery options.ZRangeQuery) ([]string, error)
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 Client.ZRangeWithScores and ClusterClient.ZRangeWithScores.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. rangeQuery - The range query object representing the type of range query to perform. - For range queries by index (rank), use [RangeByIndex]. - For range queries by lexicographical order, use [RangeByLex]. - For range queries by score, use [RangeByScore].
Return value:
An array 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 ¶
var client *Client = getExampleClient() // example helper function
result, err := client.ZAdd(context.Background(), "key1", map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0})
result1, err := client.ZRange(context.Background(), "key1", options.NewRangeByIndexQuery(0, -1)) // Ascending order
// Retrieve members within a score range in descending order
query := options.NewRangeByScoreQuery(
options.NewScoreBoundary(3, false),
options.NewInfiniteScoreBoundary(constants.NegativeInfinity)).SetReverse()
result2, err := client.ZRange(context.Background(), "key1", query)
// `result` contains members which have scores within the range of negative infinity to 3, in descending order
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: 3 [one two three] [two one]
func (*Client) ZRangeStore ¶
func (client *Client) ZRangeStore( ctx context.Context, destination string, key string, rangeQuery options.ZRangeQuery, ) (int64, error)
Stores a specified range of elements from the sorted set at `key`, into a new sorted set at `destination`. If `destination` doesn't exist, a new sorted set is created; if it exists, it's overwritten.
Note:
When in cluster mode, all keys must map to the same hash slot.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. destination - The key for the destination sorted set. key - The key of the source sorted set. rangeQuery - The range query object representing the type of range query to perform. - For range queries by index (rank), use [RangeByIndex]. - For range queries by lexicographical order, use [RangeByLex]. - For range queries by score, use [RangeByScore].
Return value:
The number of elements in the resulting sorted set.
Example ¶
var client *Client = getExampleClient() // example helper function
client.ZAdd(context.Background(), "key1", map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0})
query := options.NewRangeByScoreQuery(
options.NewScoreBoundary(3, false),
options.NewInfiniteScoreBoundary(constants.NegativeInfinity)).SetReverse()
result, err := client.ZRangeStore(context.Background(), "dest", "key1", query)
// `result` contains members which have scores within the range of negative infinity to 3, in descending order
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 2
func (*Client) ZRangeWithScores ¶
func (client *Client) ZRangeWithScores( ctx context.Context, key string, rangeQuery options.ZRangeQueryWithScores, ) ([]models.MemberAndScore, error)
Returns the specified range of elements with their scores 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.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. rangeQuery - The range query object representing the type of range query to perform. - For range queries by index (rank), use [RangeByIndex]. - For range queries by score, use [RangeByScore].
Return value:
An array 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 array.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.ZAdd(context.Background(), "key1", map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0})
result1, err := client.ZRangeWithScores(context.Background(), "key1", options.NewRangeByIndexQuery(0, -1))
query := options.NewRangeByScoreQuery(
options.NewScoreBoundary(3, false),
options.NewInfiniteScoreBoundary(constants.NegativeInfinity)).SetReverse()
result2, err := client.ZRangeWithScores(context.Background(), "key1", query)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: 3 [{one 1} {two 2} {three 3}] [{two 2} {one 1}]
func (*Client) ZRank ¶
func (client *Client) ZRank(ctx context.Context, key string, member string) (models.Result[int64], error)
Returns the rank of `member` in the sorted set stored at `key`, with scores ordered from low to high, starting from `0`. To get the rank of `member` with its score, see Client.ZRankWithScore and ClusterClient.ZRankWithScore.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. member - The member to get the rank of.
Return value:
The rank of `member` in the sorted set. If `key` doesn't exist, or if `member` is not present in the set, an empty [models.Result] will be returned.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.ZAdd(context.Background(), "key1", map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0})
result1, err := client.ZRank(context.Background(), "key1", "two")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 3 {1 false}
func (*Client) ZRankWithScore ¶
func (client *Client) ZRankWithScore( ctx context.Context, key string, member string, ) (models.Result[models.RankAndScore], error)
Returns the rank of `member` in the sorted set stored at `key` with its score, where scores are ordered from the lowest to highest, starting from `0`.
Since:
Valkey 7.2.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. member - The member to get the rank of.
Return value:
A [models.Result[models.RankAndScore]] containing the rank of `member` and its score. If `key` doesn't exist, or if `member` is not present in the set, an empty [models.Result] will be returned.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.ZAdd(context.Background(), "key1", map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0})
res, err := client.ZRankWithScore(context.Background(), "key1", "two")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(res.Value().Rank)
fmt.Println(res.Value().Score)
Output: 3 1 2
func (*Client) ZRem ¶
Removes the specified members from the sorted set stored at `key`. Specified members that are not a member of this set are ignored.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. members - The members to remove.
Return value:
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 ¶
var client *Client = getExampleClient() // example helper function
result, err := client.ZAdd(context.Background(), "key1", map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0})
result1, err := client.ZRem(context.Background(), "key1", []string{"one", "two", "nonMember"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 3 2
func (*Client) ZRemRangeByLex ¶
func (client *Client) ZRemRangeByLex(ctx context.Context, key string, rangeQuery options.RangeByLex) (int64, error)
Removes all elements in the sorted set stored at `key` with a lexicographical order between `rangeQuery.Start` and `rangeQuery.End`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. rangeQuery - The range query object representing the minimum and maximum bound of the lexicographical range.
Return value:
The number of members removed from the sorted set. If `key` does not exist, it is treated as an empty sorted set, and the command returns `0`. If `rangeQuery.Start` is greater than `rangeQuery.End`, `0` is returned.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.ZAdd(context.Background(), "key1", map[string]float64{"a": 1.0, "b": 2.0, "c": 3.0, "d": 4.0})
result1, err := client.ZRemRangeByLex(context.Background(),
"key1",
*options.NewRangeByLexQuery(options.NewLexBoundary("a", false), options.NewLexBoundary("c", true)),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 4 2
func (*Client) ZRemRangeByRank ¶
func (client *Client) ZRemRangeByRank(ctx context.Context, key string, start int64, stop int64) (int64, error)
Removes all elements in the sorted set stored at `key` with a rank between `start` and `stop`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. start - The start rank. stop - The stop rank.
Return value:
The number of members removed from the sorted set. If `key` does not exist, it is treated as an empty sorted set, and the command returns `0`. If `start` is greater than `stop`, `0` is returned.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.ZAdd(context.Background(), "key1", map[string]float64{"a": 1.0, "b": 2.0, "c": 3.0, "d": 4.0})
result1, err := client.ZRemRangeByRank(context.Background(), "key1", 1, 3)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 4 3
func (*Client) ZRemRangeByScore ¶
func (client *Client) ZRemRangeByScore(ctx context.Context, key string, rangeQuery options.RangeByScore) (int64, error)
Removes all elements in the sorted set stored at `key` with a score between `rangeQuery.Start` and `rangeQuery.End`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. rangeQuery - The range query object representing the minimum and maximum bound of the score range. can be an implementation of [options.RangeByScore].
Return value:
The number of members removed from the sorted set. If `key` does not exist, it is treated as an empty sorted set, and the command returns `0`. If `rangeQuery.Start` is greater than `rangeQuery.End`, `0` is returned.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.ZAdd(context.Background(), "key1", map[string]float64{"a": 1.0, "b": 2.0, "c": 3.0, "d": 4.0})
result1, err := client.ZRemRangeByScore(context.Background(), "key1", *options.NewRangeByScoreQuery(
options.NewInfiniteScoreBoundary(constants.NegativeInfinity),
options.NewInfiniteScoreBoundary(constants.PositiveInfinity),
))
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 4 4
func (*Client) ZRevRank ¶
func (client *Client) ZRevRank(ctx context.Context, key string, member string) (models.Result[int64], error)
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 Client.ZRevRankWithScore and ClusterClient.ZRevRankWithScore.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. member - The member to get the rank of.
Return value:
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, an empty [models.Result] will be returned.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.ZAdd(
context.Background(),
"key1",
map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0, "four": 4.0},
)
result1, err := client.ZRevRank(context.Background(), "key1", "two")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 4 {2 false}
func (*Client) ZRevRankWithScore ¶
func (client *Client) ZRevRankWithScore( ctx context.Context, key string, member string, ) (models.Result[models.RankAndScore], error)
Returns the rank of `member` in the sorted set stored at `key`, where scores are ordered from the highest to lowest, starting from `0`.
Since:
Valkey 7.2.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. member - The member to get the rank of.
Return value:
A [models.Result[models.RankAndScore]] containing the rank of `member` and its score. If `key` doesn't exist, or if `member` is not present in the set, an empty [models.Result] will be returned.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.ZAdd(
context.Background(),
"key1",
map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0, "four": 4.0},
)
res, err := client.ZRevRankWithScore(context.Background(), "key1", "two")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(res.Value().Rank)
fmt.Println(res.Value().Score)
Output: 4 2 2
func (*Client) ZScan ¶
func (client *Client) ZScan(ctx context.Context, key string, cursor models.Cursor) (models.ScanResult, error)
Iterates incrementally over a sorted set.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
key - The key of the sorted set.
cursor - The cursor that points to the next iteration of results.
A value of `"0"` indicates the start of the search.
For Valkey 8.0 and above, negative cursors are treated like the initial cursor("0").
Return value:
An object which holds the next cursor and the subset of the hash held by `key`. The cursor will return `false` from `IsFinished()` method on the last iteration of the subset. The data array in the result is always an array of the subset of the sorted set held in `key`. The array is a flattened series of `string` pairs, where the value is at even indices and the score is at odd indices.
Example ¶
var client *Client = getExampleClient() // example helper function
client.ZAdd(
context.Background(),
"key1",
map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0, "four": 4.0},
)
result, err := client.ZScan(context.Background(), "key1", models.NewCursor())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println("Cursor:", result.Cursor)
fmt.Println("Collection:", result.Data)
Output: Cursor: 0 Collection: [one 1 two 2 three 3 four 4]
func (*Client) ZScanWithOptions ¶
func (client *Client) ZScanWithOptions( ctx context.Context, key string, cursor models.Cursor, options options.ZScanOptions, ) (models.ScanResult, error)
Iterates incrementally over a sorted set.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. cursor - The cursor that points to the next iteration of results. options - The options for the command. See [options.ZScanOptions] for details.
Return value:
An object which holds the next cursor and the subset of the hash held by `key`. The cursor will return `false` from `IsFinished()` method on the last iteration of the subset. The data array in the result is always an array of the subset of the sorted set held in `key`. The array is a flattened series of `string` pairs, where the value is at even indices and the score is at odd indices.
Example ¶
var client *Client = getExampleClient() // example helper function
client.ZAdd(
context.Background(),
"key1",
map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0, "four": 4.0},
)
result, err := client.ZScanWithOptions(
context.Background(),
"key1",
models.NewCursor(),
*options.NewZScanOptions().SetMatch("*"),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println("Cursor:", result.Cursor)
fmt.Println("Collection:", result.Data)
Output: Cursor: 0 Collection: [one 1 two 2 three 3 four 4]
func (*Client) ZScore ¶
func (client *Client) ZScore(ctx context.Context, key string, member string) (models.Result[float64], error)
Returns the score of `member` in the sorted set stored at `key`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. member - The member whose score is to be retrieved.
Return value:
The score of the member. If `member` does not exist in the sorted set, `nil` is returned. If `key` does not exist, `nil` is returned.
Example ¶
var client *Client = getExampleClient() // example helper function
result, err := client.ZAdd(
context.Background(),
"key1",
map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0, "four": 4.0},
)
result1, err := client.ZScore(context.Background(), "key1", "three")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 4 {3 false}
func (*Client) ZUnion ¶
Returns the union of members from sorted sets specified by the given `keys`. To get the elements with their scores, see Client.ZUnionWithScores or ClusterClient.ZUnionWithScores.
Since:
Valkey 6.2.0 and above.
Note:
When in cluster mode, all keys must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - The keys of the sorted sets.
Return Value:
The resulting sorted set from the union.
Example ¶
var client *Client = getExampleClient() // example helper function
memberScoreMap1 := map[string]float64{
"one": 1.0,
"two": 2.0,
}
memberScoreMap2 := map[string]float64{
"two": 3.5,
"three": 3.0,
}
client.ZAdd(context.Background(), "key1", memberScoreMap1)
client.ZAdd(context.Background(), "key2", memberScoreMap2)
zUnionResult, _ := client.ZUnion(context.Background(), options.KeyArray{Keys: []string{"key1", "key2"}})
fmt.Println(zUnionResult)
Output: [one three two]
func (*Client) ZUnionStore ¶
func (client *Client) ZUnionStore( ctx context.Context, destination string, keysOrWeightedKeys options.KeysOrWeightedKeys, ) (int64, error)
Computes the union of sorted sets given by the specified `KeysOrWeightedKeys`, and stores the result in `destination`. If `destination` already exists, it is overwritten. Otherwise, a new sorted set will be created.
Note:
When in cluster mode, `destination` and all keys in `keysOrWeightedKeys` must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
destination - The key of the destination sorted set.
keysOrWeightedKeys - The keys or weighted keys of the sorted sets, see - [options.KeysOrWeightedKeys].
- Use `options.NewKeyArray()` for keys only.
- Use `options.NewWeightedKeys()` for weighted keys with score multipliers.
Return Value:
The number of elements in the resulting sorted set stored at `destination`.
Example ¶
var client *Client = getExampleClient() // example helper function
memberScoreMap1 := map[string]float64{
"one": 1.0,
"two": 2.0,
}
memberScoreMap2 := map[string]float64{
"two": 3.5,
"three": 3.0,
}
client.ZAdd(context.Background(), "key1", memberScoreMap1)
client.ZAdd(context.Background(), "key2", memberScoreMap2)
zUnionStoreResult, err := client.ZUnionStore(context.Background(),
"dest",
options.KeyArray{Keys: []string{"key1", "key2"}},
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(zUnionStoreResult)
Output: 3
func (*Client) ZUnionStoreWithOptions ¶
func (client *Client) ZUnionStoreWithOptions( ctx context.Context, destination string, keysOrWeightedKeys options.KeysOrWeightedKeys, zUnionOptions options.ZUnionOptions, ) (int64, error)
Computes the union of sorted sets given by the specified `KeysOrWeightedKeys`, and stores the result in `destination`. If `destination` already exists, it is overwritten. Otherwise, a new sorted set will be created.
Note:
When in cluster mode, `destination` and all keys in `keysOrWeightedKeys` must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
destination - The key of the destination sorted set.
keysOrWeightedKeys - The keys or weighted keys of the sorted sets, see - [options.KeysOrWeightedKeys].
- Use `options.NewKeyArray()` for keys only.
- Use `options.NewWeightedKeys()` for weighted keys with score multipliers.
zUnionOptions - The options for the ZUnionStore command, see - [options.ZUnionOptions].
Optional `aggregate` option specifies the aggregation strategy to apply when
combining the scores of elements.
Return Value:
The number of elements in the resulting sorted set stored at `destination`.
Example ¶
var client *Client = getExampleClient() // example helper function
memberScoreMap1 := map[string]float64{
"one": 1.0,
"two": 2.0,
}
memberScoreMap2 := map[string]float64{
"two": 3.5,
"three": 3.0,
}
client.ZAdd(context.Background(), "key1", memberScoreMap1)
client.ZAdd(context.Background(), "key2", memberScoreMap2)
zUnionStoreWithOptionsResult, err := client.ZUnionStoreWithOptions(context.Background(),
"dest",
options.KeyArray{Keys: []string{"key1", "key2"}},
*options.NewZUnionOptions().SetAggregate(options.AggregateSum),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(zUnionStoreWithOptionsResult)
Output: 3
func (*Client) ZUnionWithScores ¶
func (client *Client) ZUnionWithScores( ctx context.Context, keysOrWeightedKeys options.KeysOrWeightedKeys, zUnionOptions options.ZUnionOptions, ) ([]models.MemberAndScore, error)
Returns the union of members and their scores from sorted sets specified by the given `keysOrWeightedKeys`.
Since:
Valkey 6.2.0 and above.
Note:
When in cluster mode, all keys in `keysOrWeightedKeys` must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
keysOrWeightedKeys - The keys of the sorted sets with possible formats:
- Use `KeyArray` for keys only.
- Use `WeightedKeys` for weighted keys with score multipliers.
zUnionOptions - The options for the ZUnionStore command, see - [options.ZUnionOptions].
Optional `aggregate` option specifies the aggregation strategy to apply when
combining the scores of elements.
Return Value:
The resulting sorted set from the union.
Example ¶
var client *Client = getExampleClient() // example helper function
memberScoreMap1 := map[string]float64{
"one": 1.0,
"two": 2.0,
}
memberScoreMap2 := map[string]float64{
"two": 3.5,
"three": 3.0,
}
client.ZAdd(context.Background(), "key1", memberScoreMap1)
client.ZAdd(context.Background(), "key2", memberScoreMap2)
zUnionResult, _ := client.ZUnionWithScores(context.Background(),
options.KeyArray{Keys: []string{"key1", "key2"}},
*options.NewZUnionOptions().SetAggregate(options.AggregateSum),
)
fmt.Println(zUnionResult)
Output: [{one 1} {three 3} {two 5.5}]
type ClosingError ¶
type ClosingError struct {
// contains filtered or unexported fields
}
ClosingError is a client error that indicates that the client has closed and is no longer usable.
func NewClosingError ¶
func NewClosingError(message string) *ClosingError
func (*ClosingError) Error ¶
func (e *ClosingError) Error() string
type ClusterClient ¶
type ClusterClient struct {
// contains filtered or unexported fields
}
Client used for connection to cluster servers. Use NewClusterClient to request a client.
For full documentation refer to Valkey GLIDE Documentation.
Example (Compression) ¶
This example demonstrates creating a cluster client with compression enabled. It validates that compression actually reduces the data size using client statistics.
compressionConfig := config.NewCompressionConfiguration()
clientConfig := config.NewClusterClientConfiguration().
WithAddress(&getClusterAddresses()[0]).
WithCompressionConfiguration(compressionConfig)
client, err := NewClusterClient(clientConfig)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
defer client.Close()
// Capture statistics before the SET
statsBefore := client.GetStatistics()
originalBytesBefore := statsBefore["total_original_bytes"]
compressedBytesBefore := statsBefore["total_bytes_compressed"]
compressedCountBefore := statsBefore["total_values_compressed"]
value := strings.Repeat("cluster data ", 100)
result, err := client.Set(context.Background(), "cluster_compressed_key", value)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
fmt.Println(result)
// Validate compression using client statistics
statsAfter := client.GetStatistics()
originalBytes := statsAfter["total_original_bytes"] - originalBytesBefore
compressedBytes := statsAfter["total_bytes_compressed"] - compressedBytesBefore
compressedCount := statsAfter["total_values_compressed"] - compressedCountBefore
fmt.Println("Value was compressed:", compressedCount > 0)
fmt.Println("Compressed bytes < original bytes:", compressedBytes < originalBytes)
Output: OK Value was compressed: true Compressed bytes < original bytes: true
func NewClusterClient ¶
func NewClusterClient(config *config.ClusterClientConfiguration) (*ClusterClient, error)
Creates a new ClusterClient instance and establishes a connection to a Valkey Cluster.
Parameters:
ctx - The context for controlling the command execution. config - The configuration options for the client, including cluster addresses, authentication credentials, TLS settings, periodic checks, and Pub/Sub subscriptions.
Return value:
A connected [ClusterClient] instance.
Remarks:
Use this static method to create and connect a `GlideClusterClient` to a Valkey Cluster.
The client will automatically handle connection establishment, including cluster topology discovery and handling
of authentication and TLS configurations.
- **Cluster Topology Discovery**: The client will automatically discover the cluster topology
based on the seed addresses provided.
- **Authentication**: If `ServerCredentials` are provided, the client will attempt to authenticate
using the specified username and password.
- **TLS**: If `UseTLS` is set to `true`, the client will establish a secure connection using TLS.
- **Reconnection Strategy**: The `BackoffStrategy` settings define how the client will attempt to reconnect
in case of disconnections.
- **Pub/Sub Subscriptions**: Predefine Pub/Sub channels and patterns to subscribe to upon connection establishment.
Supports exact channels, patterns, and sharded channels (available since Valkey version 7.0).
Example ¶
clientConf := config.NewClusterClientConfiguration().
WithAddress(&getClusterAddresses()[0]).
WithRequestTimeout(5 * time.Second).
WithUseTLS(false).
WithSubscriptionConfig(
config.NewClusterSubscriptionConfig().
WithSubscription(config.PatternClusterChannelMode, "news.*").
WithCallback(func(message *models.PubSubMessage, ctx any) {
fmt.Printf("Received message on '%s': %s", message.Channel, message.Message)
}, nil),
)
client, err := NewClusterClient(clientConf)
if err != nil {
fmt.Println("Failed to create a client and connect: ", err)
}
fmt.Printf("Client created and connected: %T", client)
Output: Client created and connected: *glide.ClusterClient
Example (WithDatabaseId) ¶
// This WithDatabaseId for cluster requires Valkey 9.0+
clientConf := config.NewClusterClientConfiguration().
WithAddress(&getClusterAddresses()[0]).
WithRequestTimeout(5 * time.Second).
WithUseTLS(false).
WithDatabaseId(1).
WithSubscriptionConfig(
config.NewClusterSubscriptionConfig().
WithSubscription(config.PatternClusterChannelMode, "news.*").
WithCallback(func(message *models.PubSubMessage, ctx any) {
fmt.Printf("Received message on '%s': %s", message.Channel, message.Message)
}, nil),
)
client, err := NewClusterClient(clientConf)
if err != nil {
fmt.Println("Failed to create a client and connect: ", err)
}
fmt.Printf("Client created and connected: %T", client)
Output: Client created and connected: *glide.ClusterClient
func (*ClusterClient) AclCat ¶ added in v2.3.0
AclCat returns a list of all ACL categories.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
An array of ACL categories.
func (*ClusterClient) AclCatWithCategory ¶ added in v2.3.0
func (client *ClusterClient) AclCatWithCategory(ctx context.Context, category string) ([]string, error)
AclCatWithCategory returns a list of commands within the specified ACL category.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. category - The ACL category to list commands for.
Return value:
An array of commands within the specified category.
func (*ClusterClient) AclDelUser ¶ added in v2.3.0
AclDelUser deletes all specified ACL users and terminates their connections.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. usernames - An array of usernames to delete.
Return value:
The number of users deleted.
func (*ClusterClient) AclDryRun ¶ added in v2.3.0
func (client *ClusterClient) AclDryRun(ctx context.Context, username string, command string, args []string) (string, error)
AclDryRun simulates the execution of a command by a user without actually executing it.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. username - The username to simulate command execution for. command - The command to simulate. args - The command arguments.
Return value:
"OK" if the user can execute the command, otherwise a string describing why the command cannot be executed.
func (*ClusterClient) AclGenPass ¶ added in v2.3.0
AclGenPass generates a random password for ACL users.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
A randomly generated password string (64 hex characters by default).
func (*ClusterClient) AclGenPassWithBits ¶ added in v2.3.0
AclGenPassWithBits generates a random password with the specified number of bits.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. bits - The number of bits for the password (must be between 1 and 4096).
Return value:
A randomly generated password string.
func (*ClusterClient) AclGetUser ¶ added in v2.3.0
AclGetUser returns all ACL rules for the specified user.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. username - The username to get ACL rules for.
Return value:
A value describing the ACL rules for the user, or nil if user doesn't exist.
func (*ClusterClient) AclList ¶ added in v2.3.0
AclList returns a list of all ACL users and their rules in ACL configuration file format.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
An array of ACL rules for all users.
func (*ClusterClient) AclLoad ¶ added in v2.3.0
AclLoad reloads ACL rules from the configured ACL configuration file.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
"OK" on success.
func (*ClusterClient) AclLog ¶ added in v2.3.0
AclLog returns the ACL security events log.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
An array of ACL security events.
func (*ClusterClient) AclLogReset ¶ added in v2.3.0
AclLogReset resets the ACL log.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
"OK" on success.
func (*ClusterClient) AclLogWithCount ¶ added in v2.3.0
AclLogWithCount returns the specified number of ACL security events from the log.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. count - The number of entries to return.
Return value:
An array of ACL security events.
func (*ClusterClient) AclSave ¶ added in v2.3.0
AclSave saves the current ACL rules to the configured ACL configuration file.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
"OK" on success.
func (*ClusterClient) AclSetUser ¶ added in v2.3.0
func (client *ClusterClient) AclSetUser(ctx context.Context, username string, rules []string) (string, error)
AclSetUser creates or modifies an ACL user and its rules.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. username - The username for the ACL user. rules - An array of ACL rules to apply to the user.
Return value:
"OK" on success.
func (*ClusterClient) AclUsers ¶ added in v2.3.0
AclUsers returns a list of all ACL usernames.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
An array of ACL usernames.
func (*ClusterClient) AclWhoAmI ¶ added in v2.3.0
AclWhoAmI returns the username of the current connection.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
The username of the current connection.
func (*ClusterClient) Append ¶
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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the string. value - The value to append.
Return value:
The length of the string after appending the value.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.Set(context.Background(), "my_key", "my_valu")
result, err := client.Append(context.Background(), "my_key", "e")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
value, _ := client.Get(context.Background(), "my_key")
fmt.Println(value.Value())
Output: 8 my_value
func (*ClusterClient) BLMPop ¶
func (client *ClusterClient) BLMPop( ctx context.Context, keys []string, listDirection constants.ListDirection, timeout time.Duration, ) ([]models.KeyValues, error)
Blocks the connection until it pops one element from the first non-empty list from the provided keys. BLMPop is the blocking variant of Client.LMPop and ClusterClient.LMPop.
Note:
- When in cluster mode, all keys must map to the same hash slot.
- BLMPop is a client blocking command, see Blocking Commands for more details and best practices.
Since:
Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - An array of keys to lists. listDirection - The direction based on which elements are popped from - see [options.ListDirection]. timeout - The duration to wait for a blocking operation to complete. A value of 0 will block indefinitely.
Return value:
A slice of [models.KeyValues], each containing a key name and an array of popped elements. If no member could be popped and the timeout expired, returns `nil`.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.LPush(context.Background(), "my_list", []string{"one", "two", "three"})
result1, err := client.BLMPop(context.Background(), []string{"my_list"}, constants.Left, 100*time.Millisecond)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
jsonResult1, err := json.Marshal(result1)
fmt.Println(string(jsonResult1))
Output: 3 [{"Key":"my_list","Values":["three"]}]
func (*ClusterClient) BLMPopCount ¶
func (client *ClusterClient) BLMPopCount( ctx context.Context, keys []string, listDirection constants.ListDirection, count int64, timeout time.Duration, ) ([]models.KeyValues, error)
Blocks the connection until it pops one or more elements from the first non-empty list from the provided keys. BLMPopCount is the blocking variant of Client.LMPopCount ClusterClient.LMPopCount.
Note:
- When in cluster mode, all keys must map to the same hash slot.
- BLMPopCount is a client blocking command, see Blocking Commands for more details and best practices.
Since:
Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - An array of keys to lists. listDirection - The direction based on which elements are popped from - see [options.ListDirection]. count - The maximum number of popped elements. timeout - The duration to wait for a blocking operation to complete. A value of `0` will block
indefinitely.
Return value:
A slice of [models.KeyValues], each containing a key name and an array of popped elements. If no member could be popped and the timeout expired, returns `nil`.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.LPush(context.Background(), "my_list", []string{"one", "two", "three"})
result1, err := client.BLMPopCount(context.Background(), []string{"my_list"}, constants.Left, 2, 100*time.Millisecond)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
jsonResult1, err := json.Marshal(result1)
fmt.Println(string(jsonResult1))
Output: 3 [{"Key":"my_list","Values":["three","two"]}]
func (*ClusterClient) BLMove ¶
func (client *ClusterClient) BLMove( ctx context.Context, source string, destination string, whereFrom constants.ListDirection, whereTo constants.ListDirection, timeout time.Duration, ) (models.Result[string], error)
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 `whereFrom`. `BLMove` is the blocking variant of Client.LMove and ClusterClient.LMove.
Note:
- When in cluster mode, `source` and `destination` must map to the same hash slot.
- `BLMove` is a client blocking command, see Blocking Commands for more details and best practices.
Since:
Valkey 6.2.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. source - The key to the source list. destination - The key to the destination list. whereFrom - The ListDirection the element should be removed from. whereTo - The ListDirection the element should be added to. timeout - The duration to wait for a blocking operation to complete. A value of `0` will block indefinitely.
Return value:
A models.Result[string] containing the popped element or models.CreateNilStringResult() if `source` does not exist or if the operation timed-out.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.LPush(context.Background(), "{list}-1", []string{"two", "one"})
result1, err := client.LPush(context.Background(), "{list}-2", []string{"four", "three"})
result2, err := client.BLMove(
context.Background(),
"{list}-1",
"{list}-2",
constants.Left,
constants.Left,
100*time.Millisecond,
)
result3, err := client.LRange(context.Background(), "{list}-1", 0, -1)
result4, err := client.LRange(context.Background(), "{list}-2", 0, -1)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
Output: 2 2 {one false} [two] [one three four]
func (*ClusterClient) BLPop ¶
func (client *ClusterClient) BLPop(ctx context.Context, keys []string, timeout time.Duration) ([]string, error)
Pops 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.
Note:
- When in cluster mode, all keys must map to the same hash slot.
- BLPop is a client blocking command, see Blocking Commands for more details and best practices.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - The keys of the lists to pop from. timeout - The duration to wait for a blocking operation to complete. A value of 0 will block indefinitely.
Return value:
A two-element 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 `nil`.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.RPush(context.Background(), "{list}-a", []string{"a", "b", "c", "d", "e"})
result1, err := client.RPush(context.Background(), "{list}-b", []string{"f", "g", "h", "i", "j"})
result2, err := client.BLPop(context.Background(), []string{"{list}-a", "{list}-b"}, 500*time.Millisecond)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: 5 5 [{list}-a a]
func (*ClusterClient) BRPop ¶
func (client *ClusterClient) BRPop(ctx context.Context, keys []string, timeout time.Duration) ([]string, error)
Pops 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.
Note:
- When in cluster mode, all keys must map to the same hash slot.
- BRPop is a client blocking command, see Blocking Commands for more details and best practices.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - The keys of the lists to pop from. timeout - The duration to wait for a blocking operation to complete. A value of 0 will block indefinitely.
Return value:
A two-element 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 `nil`.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.Del(context.Background(), []string{"my_list", "{list}-a", "{list}-b"})
result, err := client.RPush(context.Background(), "{list}-a", []string{"a", "b", "c", "d", "e"})
result1, err := client.RPush(context.Background(), "{list}-b", []string{"f", "g", "h", "i", "j"})
result2, err := client.BRPop(context.Background(), []string{"{list}-a", "{list}-b"}, 500*time.Millisecond)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: 5 5 [{list}-a e]
func (*ClusterClient) BZMPop ¶
func (client *ClusterClient) BZMPop( ctx context.Context, keys []string, scoreFilter constants.ScoreFilter, timeout time.Duration, ) (models.Result[models.KeyWithArrayOfMembersAndScores], error)
Blocks the connection until it pops and returns a member-score pair from the first non-empty sorted set, with the given keys being checked in the order they are provided. BZMPop is the blocking variant of Client.ZMPop and ClusterClient.ZMPop.
Note:
- When in cluster mode, all keys must map to the same hash slot.
- BZMPop is a client blocking command, see Blocking Commands for more details and best practices.
Since:
Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - An array of keys to lists. scoreFilter - The element pop criteria - either [options.MIN] or [options.MAX] to pop members with the lowest/highest scores accordingly. timeout - The duration to wait for a blocking operation to complete. A value of `0` will block indefinitely.
Return value:
An object containing the following elements: - The key name of the set from which the element was popped. - An array of member scores of the popped elements. Returns `nil` if no member could be popped and the timeout expired.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.ZAdd(context.Background(), "key1", map[string]float64{"a": 1.0, "b": 2.0, "c": 3.0, "d": 4.0})
result, err := client.BZMPop(context.Background(), []string{"key1"}, constants.MAX, 500*time.Millisecond)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
jsonSummary, _ := json.Marshal(result.Value())
fmt.Println(string(jsonSummary))
Output: {"Key":"key1","MembersAndScores":[{"Member":"d","Score":4}]}
func (*ClusterClient) BZMPopWithOptions ¶
func (client *ClusterClient) BZMPopWithOptions( ctx context.Context, keys []string, scoreFilter constants.ScoreFilter, timeout time.Duration, opts options.ZMPopOptions, ) (models.Result[models.KeyWithArrayOfMembersAndScores], error)
Blocks the connection until it pops and returns a member-score pair from the first non-empty sorted set, with the given keys being checked in the order they are provided. BZMPop is the blocking variant of Client.ZMPop and ClusterClient.ZMPop.
Note:
- When in cluster mode, all keys must map to the same hash slot.
- BZMPop is a client blocking command, see Blocking Commands for more details and best practices.
Since:
Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - An array of keys to lists. scoreFilter - The element pop criteria - either [options.MIN] or [options.MAX] to pop members with the lowest/highest scores accordingly. count - The maximum number of popped elements. timeout - The duration to wait for a blocking operation to complete. A value of `0` will block indefinitely. opts - Pop options, see [options.ZMPopOptions].
Return value:
An object containing the following elements: - The key name of the set from which the element was popped. - An array of member scores of the popped elements. Returns `nil` if no member could be popped and the timeout expired.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.ZAdd(context.Background(), "key1", map[string]float64{"a": 1.0, "b": 2.0, "c": 3.0, "d": 4.0})
result, err := client.BZMPopWithOptions(
context.Background(),
[]string{"key1"},
constants.MAX,
100*time.Millisecond,
*options.NewZMPopOptions().SetCount(1),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
jsonSummary, _ := json.Marshal(result.Value())
fmt.Println(string(jsonSummary))
Output: {"Key":"key1","MembersAndScores":[{"Member":"d","Score":4}]}
func (*ClusterClient) BZPopMax ¶
func (client *ClusterClient) BZPopMax( ctx context.Context, keys []string, timeout time.Duration, ) (models.Result[models.KeyWithMemberAndScore], error)
Blocks the connection until it pops and returns a member-score pair with the highest score from the first non-empty sorted set. The given `keys` being checked in the order they are provided. `BZPopMax` is the blocking variant of Client.ZPopMax and ClusterClient.ZPopMax.
Note:
- When in cluster mode, all keys must map to the same hash slot.
- `BZPopMax` is a client blocking command, see Blocking Commands for more details and best practices.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - An array of keys to check for elements. timeout - The maximum number of seconds to block (0 blocks indefinitely).
Return value:
A `models.KeyWithMemberAndScore` struct containing the key from which the member was popped, the popped member, and its score. If no element could be popped and the timeout expired, returns `nil`.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.ZAdd(context.Background(), "{key}SortedSet", map[string]float64{"x": 5.0, "y": 6.0, "z": 7.0})
res, err := client.BZPopMax(context.Background(), []string{"{key}SortedSet"}, 1.0)
if err != nil {
fmt.Println("Glide example failed with an error:", err)
return
}
value := res.Value()
fmt.Printf("{Key: %q, Member: %q, Score: %.1f}\n", value.Key, value.Member, value.Score)
Output: {Key: "{key}SortedSet", Member: "z", Score: 7.0}
func (*ClusterClient) BZPopMin ¶
func (client *ClusterClient) BZPopMin( ctx context.Context, keys []string, timeout time.Duration, ) (models.Result[models.KeyWithMemberAndScore], error)
Blocks the connection until it removes and returns a member-score pair with the lowest score from the first non-empty sorted set. The given `keys` being checked in the order they are provided. `BZPopMin` is the blocking variant of Client.BZPopMin and ClusterClient.BZPopMin.
Note:
- When in cluster mode, all `keys` must map to the same hash slot.
- `BZPopMin` is a client blocking command, see [Blocking Commands] for more details and best practices.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. keys - The keys of the sorted sets. timeout - The duration to wait for a blocking operation to complete. A value of `0` will block indefinitely.
Return value:
A `models.KeyWithMemberAndScore` struct 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 `nil`.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
zaddResult1, err := client.ZAdd(context.Background(), "{key}1", map[string]float64{"a": 1.0, "b": 1.5})
zaddResult2, err := client.ZAdd(context.Background(), "{key}2", map[string]float64{"c": 2.0})
result1, err := client.BZPopMin(context.Background(), []string{"{key}1", "{key}2"}, 500*time.Millisecond)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(zaddResult1)
fmt.Println(zaddResult2)
fmt.Println(result1)
Output: 2 1 {{{key}1 a 1} false}
func (*ClusterClient) BitCount ¶
Counts the number of set bits (population counting) in a string stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key for the string to count the set bits of.
Return value:
The number of set bits in the string. Returns `0` if the key is missing as it is treated as an empty string.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.SetBit(context.Background(), "my_key", 1, 1)
client.SetBit(context.Background(), "my_key", 2, 1)
result, err := client.BitCount(context.Background(), "my_key")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 2
func (*ClusterClient) BitCountWithOptions ¶
func (client *ClusterClient) BitCountWithOptions(ctx context.Context, key string, opts options.BitCountOptions) (int64, error)
Counts the number of set bits (population counting) in a string 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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key for the string to count the set bits of. options - The offset options - see [options.BitCountOptions].
Return value:
The number of set bits in the string interval specified by start, end, and options. Returns zero if the key is missing as it is treated as an empty string.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
options := options.NewBitCountOptions().
SetStart(1).
SetEnd(1).
SetBitmapIndexType(options.BYTE)
result, err := client.BitCountWithOptions(context.Background(), "my_key", *options)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 0
func (*ClusterClient) BitField ¶
func (client *ClusterClient) BitField( ctx context.Context, key string, subCommands []options.BitFieldSubCommands, ) ([]models.Result[int64], error)
Reads or modifies the array of bits representing the string that is held at key based on the specified sub commands.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
key - The key of the string.
subCommands - The subCommands to be performed on the binary value of the string at
key, which could be any of the following:
- [BitFieldGet].
- [BitFieldSet].
- [BitFieldIncrby].
- [BitFieldOverflow].
Use `options.NewBitFieldGet()` to specify a BitField GET command.
Use `options.NewBitFieldSet()` to specify a BitField SET command.
Use `options.NewBitFieldIncrby()` to specify a BitField INCRYBY command.
Use `options.BitFieldOverflow()` to specify a BitField OVERFLOW command.
Return value:
Result from the executed subcommands.
- BitFieldGet returns the value in the binary representation of the string.
- BitFieldSet returns the previous value before setting the new value in the binary representation.
- BitFieldIncrBy returns the updated value after increasing or decreasing the bits.
- BitFieldOverflow controls the behavior of subsequent operations and returns
a result based on the specified overflow type (WRAP, SAT, FAIL).
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
commands := []options.BitFieldSubCommands{
options.NewBitFieldGet(options.SignedInt, 8, 16),
options.NewBitFieldOverflow(options.SAT),
options.NewBitFieldSet(options.UnsignedInt, 4, 0, 7),
options.NewBitFieldIncrBy(options.SignedInt, 5, 100, 1),
}
result, err := client.BitField(context.Background(), "mykey", commands)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [{0 false} {0 false} {1 false}]
func (*ClusterClient) BitFieldRO ¶
func (client *ClusterClient) BitFieldRO( ctx context.Context, key string, commands []options.BitFieldROCommands, ) ([]models.Result[int64], error)
Reads the array of bits representing the string that is held at key based on the specified sub commands.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
key - The key of the string.
subCommands - The read-only subCommands to be performed on the binary value
of the string at key, which could be:
- [BitFieldGet].
Use `options.NewBitFieldGet()` to specify a BitField GET command.
Return value:
Result from the executed GET subcommands. - BitFieldGet returns the value in the binary representation of the string.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "mykey"
bfcommands := []options.BitFieldSubCommands{
options.NewBitFieldSet(options.UnsignedInt, 8, 0, 24),
}
client.BitField(context.Background(), key, bfcommands)
commands := []options.BitFieldROCommands{
options.NewBitFieldGet(options.UnsignedInt, 8, 0),
}
result, err := client.BitFieldRO(context.Background(), key, commands)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [{24 false}]
func (*ClusterClient) BitOp ¶
func (client *ClusterClient) BitOp( ctx context.Context, bitwiseOperation options.BitOpType, destination string, keys []string, ) (int64, error)
Perform a bitwise operation between multiple keys (containing string values) and store the result in the destination.
Note:
When in cluster mode, `destination` and all `keys` must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. bitwiseOperation - The bitwise operation to perform. destination - The key that will store the resulting string. keys - The list of keys to perform the bitwise operation on.
Return value:
The size of the string stored in destination.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
bitopkey1 := "{bitop_test}key1"
bitopkey2 := "{bitop_test}key2"
destKey := "{bitop_test}dest"
// Set initial values
client.Set(context.Background(), bitopkey1, "foobar")
client.Set(context.Background(), bitopkey2, "abcdef")
// Perform BITOP AND
result, err := client.BitOp(context.Background(), options.AND, destKey, []string{bitopkey1, bitopkey2})
if err != nil {
fmt.Println("BitOp AND failed:", err)
} else {
fmt.Println("BitOp AND Result:", result)
}
// Perform BITOP OR
result, err = client.BitOp(context.Background(), options.OR, destKey, []string{bitopkey1, bitopkey2})
if err != nil {
fmt.Println("BitOp OR failed:", err)
} else {
fmt.Println("BitOp OR Result:", result)
}
// Perform BITOP XOR
result, err = client.BitOp(context.Background(), options.XOR, destKey, []string{bitopkey1, bitopkey2})
if err != nil {
fmt.Println("BitOp XOR failed:", err)
} else {
fmt.Println("BitOp XOR Result:", result)
}
// Perform BITOP NOT (only one source key allowed)
result, err = client.BitOp(context.Background(), options.NOT, destKey, []string{bitopkey1})
if err != nil {
fmt.Println("BitOp NOT failed:", err)
} else {
fmt.Println("BitOp NOT Result:", result)
}
Output: BitOp AND Result: 6 BitOp OR Result: 6 BitOp XOR Result: 6 BitOp NOT Result: 6
func (*ClusterClient) BitPos ¶
Returns the position of the first bit matching the given bit value.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the string. bit - The bit value to match. The value must be 0 or 1.
Return value:
The position of the first occurrence matching bit in the binary value of the string held at key. If bit is not found, a -1 is returned.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.SetBit(context.Background(), "my_key", 7, 1)
result, err := client.BitPos(context.Background(), "my_key", 1)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 7
func (*ClusterClient) BitPosWithOptions ¶
func (client *ClusterClient) BitPosWithOptions( ctx context.Context, key string, bit int64, bitposOptions options.BitPosOptions, ) (int64, error)
Returns the position of the first bit matching the given bit value.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the string. bit - The bit value to match. The value must be 0 or 1. bitposOptions - The [BitPosOptions] type.
Return value:
The position of the first occurrence matching bit in the binary value of the string held at key. If bit is not found, a -1 is returned.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.Set(context.Background(), "my_key", "\x00\x10\x00")
options := options.NewBitPosOptions().
SetStart(10).
SetEnd(14).
SetBitmapIndexType(options.BIT)
result, err := client.BitPosWithOptions(context.Background(), "my_key", 1, *options)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 11
func (*ClusterClient) ClientGetName ¶
Gets the name of the current connection. The command will be routed to a random node.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
If a name is set, returns the name of the client connection as a models.Result[string]. Otherwise, returns [models.CreateNilStringResult()] if no name is assigned.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
connectionName := "ConnectionName-" + uuid.NewString()
client.ClientSetName(context.Background(), connectionName)
result, err := client.ClientGetName(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.Value() == connectionName)
Output: true
func (*ClusterClient) ClientGetNameWithOptions ¶
func (client *ClusterClient) ClientGetNameWithOptions( ctx context.Context, opts options.RouteOption, ) (models.ClusterValue[models.Result[string]], error)
Gets the name of the current connection.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
opts - Specifies the routing configuration for the command. The client will route the
command to the nodes defined by route.
Return value:
If a name is set, returns the name of the client connection as a ClusterValue wrapped models.Result[string]. Otherwise, returns [models.CreateEmptyClusterValue[models.Result[string]]()] if no name is assigned.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
connectionName := "ConnectionName-" + uuid.NewString()
opts := options.RouteOption{Route: nil}
client.ClientSetNameWithOptions(context.Background(), connectionName, opts)
result, err := client.ClientGetNameWithOptions(context.Background(), opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.SingleValue().Value() == connectionName)
Output: true
func (*ClusterClient) ClientId ¶
func (client *ClusterClient) ClientId(ctx context.Context) (models.ClusterValue[int64], error)
Gets the current connection id.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
The id of the client.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.ClientId(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
assert := result.IsSingleValue()
fmt.Println(assert)
Output: true
func (*ClusterClient) ClientIdWithOptions ¶
func (client *ClusterClient) ClientIdWithOptions( ctx context.Context, opts options.RouteOption, ) (models.ClusterValue[int64], error)
Gets the current connection id.
Parameters:
ctx - The context for controlling the command execution.
opts - Specifies the routing configuration for the command. The client will route the
command to the nodes defined by route.
Return value:
The id of the client.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
opts := options.RouteOption{Route: nil}
result, err := client.ClientIdWithOptions(context.Background(), opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
assert := result.IsSingleValue()
fmt.Println(assert)
Output: true
func (*ClusterClient) ClientSetName ¶
func (client *ClusterClient) ClientSetName(ctx context.Context, connectionName string) (string, error)
Set the name of the current connection.
Parameters:
ctx - The context for controlling the command execution. connectionName - Connection name of the current connection.
Return value:
OK - when connection name is set
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
connectionName := "ConnectionName-" + uuid.NewString()
result, err := client.ClientSetName(context.Background(), connectionName)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*ClusterClient) ClientSetNameWithOptions ¶
func (client *ClusterClient) ClientSetNameWithOptions(ctx context.Context, connectionName string, opts options.RouteOption, ) (string, error)
Set the name of the current connection.
Parameters:
ctx - The context for controlling the command execution.
connectionName - Connection name of the current connection.
opts - Specifies the routing configuration for the command. The client will route the
command to the nodes defined by route.
Return value:
OK - when connection name is set
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
connectionName := "ConnectionName-" + uuid.NewString()
opts := options.RouteOption{Route: nil}
result, err := client.ClientSetNameWithOptions(context.Background(), connectionName, opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*ClusterClient) Close ¶
func (client *ClusterClient) Close()
Close terminates the client by closing all associated resources.
func (*ClusterClient) ClusterCountKeysInSlot ¶ added in v2.3.0
ClusterCountKeysInSlot returns the number of keys in the specified hash slot. The command will be routed to the node responsible for the specified slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. slot - The hash slot number (0-16383).
Return value:
The number of keys in the specified slot.
func (*ClusterClient) ClusterGetKeysInSlot ¶ added in v2.3.0
func (client *ClusterClient) ClusterGetKeysInSlot(ctx context.Context, slot int64, count int64) ([]string, error)
ClusterGetKeysInSlot returns an array of keys in the specified hash slot. The command will be routed to the node responsible for the specified slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. slot - The hash slot number (0-16383). count - Maximum number of keys to return.
Return value:
An array of keys in the specified slot.
func (*ClusterClient) ClusterInfo ¶ added in v2.3.0
func (client *ClusterClient) ClusterInfo(ctx context.Context) (string, error)
ClusterInfo returns information about the state of the cluster. The command will be routed to a random node.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
A string containing cluster information.
func (*ClusterClient) ClusterInfoWithRoute ¶ added in v2.3.0
func (client *ClusterClient) ClusterInfoWithRoute( ctx context.Context, route options.RouteOption, ) (models.ClusterValue[string], error)
ClusterInfoWithRoute returns information about the state of the cluster with routing options.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. route - Specifies the routing configuration for the command.
Return value:
A ClusterValue containing cluster information.
func (*ClusterClient) ClusterKeySlot ¶ added in v2.3.0
ClusterKeySlot returns the hash slot for a given key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to get the hash slot for.
Return value:
The hash slot number for the key (0-16383).
func (*ClusterClient) ClusterLinks ¶ added in v2.3.0
ClusterLinks returns information about all TCP links between cluster nodes. The command will be routed to a random node.
Since: Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
An array of maps containing link information.
func (*ClusterClient) ClusterLinksWithRoute ¶ added in v2.3.0
func (client *ClusterClient) ClusterLinksWithRoute( ctx context.Context, route options.RouteOption, ) (models.ClusterValue[[]map[string]any], error)
ClusterLinksWithRoute returns link information with routing options.
Since: Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. route - Specifies the routing configuration for the command.
Return value:
A ClusterValue containing link information.
func (*ClusterClient) ClusterMyId ¶ added in v2.3.0
func (client *ClusterClient) ClusterMyId(ctx context.Context) (string, error)
ClusterMyId returns the unique identifier of the node to which the command is routed.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
The unique identifier of the node to which the command is routed.
func (*ClusterClient) ClusterMyIdWithRoute ¶ added in v2.3.0
func (client *ClusterClient) ClusterMyIdWithRoute( ctx context.Context, route options.RouteOption, ) (models.ClusterValue[string], error)
ClusterMyIdWithRoute returns the node ID with routing options.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. route - Specifies the routing configuration for the command.
Return value:
A ClusterValue containing the node ID.
func (*ClusterClient) ClusterMyShardId ¶ added in v2.3.0
func (client *ClusterClient) ClusterMyShardId(ctx context.Context) (string, error)
ClusterMyShardId returns the shard ID of the current node. The command will be routed to a random node.
Since: Valkey 7.2 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
The shard ID of the current node.
func (*ClusterClient) ClusterMyShardIdWithRoute ¶ added in v2.3.0
func (client *ClusterClient) ClusterMyShardIdWithRoute( ctx context.Context, route options.RouteOption, ) (models.ClusterValue[string], error)
ClusterMyShardIdWithRoute returns the shard ID with routing options.
Since: Valkey 7.2 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. route - Specifies the routing configuration for the command.
Return value:
A ClusterValue containing the shard ID.
func (*ClusterClient) ClusterNodes ¶ added in v2.3.0
func (client *ClusterClient) ClusterNodes(ctx context.Context) (string, error)
ClusterNodes returns the cluster configuration as seen by the node. The command will be routed to a random node.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
A string containing cluster nodes information in the cluster config format.
func (*ClusterClient) ClusterNodesWithRoute ¶ added in v2.3.0
func (client *ClusterClient) ClusterNodesWithRoute( ctx context.Context, route options.RouteOption, ) (models.ClusterValue[string], error)
ClusterNodesWithRoute returns the cluster configuration with routing options.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. route - Specifies the routing configuration for the command.
Return value:
A ClusterValue containing cluster nodes information.
func (*ClusterClient) ClusterShards ¶ added in v2.3.0
ClusterShards returns the mapping of cluster slots to shards. Each shard contains information about the primary and replicas. The command will be routed to a random node.
Since: Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
An array of maps representing each shard with slots and node information.
func (*ClusterClient) ClusterShardsWithRoute ¶ added in v2.3.0
func (client *ClusterClient) ClusterShardsWithRoute( ctx context.Context, route options.RouteOption, ) (models.ClusterValue[[]map[string]any], error)
ClusterShardsWithRoute returns the mapping of cluster slots to shards with routing options.
Since: Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. route - Specifies the routing configuration for the command.
Return value:
A ClusterValue containing shard information.
func (*ClusterClient) ConfigGet ¶
func (client *ClusterClient) ConfigGet(ctx context.Context, parameters []string, ) (map[string]string, error)
Get the values of configuration parameters. The command will be sent to a random node.
Note:
Prior to Version 7.0.0, only one parameter can be send.
Parameters:
ctx - The context for controlling the command execution. parameters - An array of configuration parameter names to retrieve values for.
Return value:
A map of values corresponding to the configuration parameters.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
configParamSet := map[string]string{"timeout": "1000"}
client.ConfigSet(context.Background(), configParamSet)
configParamGet := []string{"timeout"}
result, err := client.ConfigGet(context.Background(), configParamGet)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: map[timeout:1000]
func (*ClusterClient) ConfigGetWithOptions ¶
func (client *ClusterClient) ConfigGetWithOptions(ctx context.Context, parameters []string, opts options.RouteOption, ) (models.ClusterValue[map[string]string], error)
Get the values of configuration parameters.
Note:
Prior to Version 7.0.0, only one parameter can be send.
Parameters:
ctx - The context for controlling the command execution.
parameters - An array of configuration parameter names to retrieve values for.
opts - Specifies the routing configuration for the command. The client will route the
command to the nodes defined by route.
Return value:
A map of values corresponding to the configuration parameters.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
opts := options.RouteOption{Route: config.RandomRoute}
configParamSet := map[string]string{"timeout": "1000"}
client.ConfigSetWithOptions(context.Background(), configParamSet, opts)
configParamGet := []string{"timeout"}
result, err := client.ConfigGetWithOptions(context.Background(), configParamGet, opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.SingleValue())
Output: map[timeout:1000]
func (*ClusterClient) ConfigResetStat ¶
func (client *ClusterClient) ConfigResetStat(ctx context.Context) (string, error)
Resets the statistics reported by the server using the INFO and LATENCY HISTOGRAM.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
OK to confirm that the statistics were successfully reset.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.ConfigResetStat(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*ClusterClient) ConfigResetStatWithOptions ¶
func (client *ClusterClient) ConfigResetStatWithOptions(ctx context.Context, opts options.RouteOption) (string, error)
Resets the statistics reported by the server using the INFO and LATENCY HISTOGRAM.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
route - Specifies the routing configuration for the command. The client will route the
command to the nodes defined by route.
Return value:
OK to confirm that the statistics were successfully reset.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
opts := options.RouteOption{Route: nil}
result, err := client.ConfigResetStatWithOptions(context.Background(), opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*ClusterClient) ConfigRewrite ¶
func (client *ClusterClient) ConfigRewrite(ctx context.Context) (string, error)
Rewrites the configuration file with the current configuration. The command will be routed a random node.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
"OK" when the configuration was rewritten properly, otherwise an error is thrown.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
var resultRewrite string
opts := options.ClusterInfoOptions{
InfoOptions: &options.InfoOptions{Sections: []constants.Section{constants.Server}},
}
res, err := client.InfoWithOptions(context.Background(), opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
for _, data := range res.MultiValue() {
lines := strings.Split(data, "\n")
var configFile string
for _, line := range lines {
if strings.HasPrefix(line, "config_file:") {
configFile = strings.TrimSpace(strings.TrimPrefix(line, "config_file:"))
break
}
}
if len(configFile) > 0 {
responseRewrite, err := client.ConfigRewrite(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
resultRewrite = responseRewrite
break
} else {
resultRewrite = "OK"
}
}
fmt.Println(resultRewrite)
Output: OK
func (*ClusterClient) ConfigRewriteWithOptions ¶
func (client *ClusterClient) ConfigRewriteWithOptions(ctx context.Context, opts options.RouteOption) (string, error)
Rewrites the configuration file with the current configuration.
Parameters:
ctx - The context for controlling the command execution.
opts - Specifies the routing configuration for the command. The client will route the
command to the nodes defined by route.
Return value:
"OK" when the configuration was rewritten properly, otherwise an error is thrown.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
sections := []constants.Section{constants.Server}
// info with option or with multiple options without route
var runResultNilRoute string
opts := options.ClusterInfoOptions{
InfoOptions: &options.InfoOptions{Sections: sections},
RouteOption: nil,
}
response, err := client.InfoWithOptions(context.Background(), opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
for _, data := range response.MultiValue() {
lines := strings.Split(data, "\n")
var configFile string
for _, line := range lines {
if strings.HasPrefix(line, "config_file:") {
configFile = strings.TrimSpace(strings.TrimPrefix(line, "config_file:"))
break
}
}
if len(configFile) > 0 {
responseRewrite, err := client.ConfigRewrite(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
runResultNilRoute = responseRewrite
break
}
runResultNilRoute = "OK"
}
// same sections with random route
var runResultRandomRoute string
opts = options.ClusterInfoOptions{
InfoOptions: &options.InfoOptions{Sections: sections},
RouteOption: &options.RouteOption{Route: config.RandomRoute},
}
response, err = client.InfoWithOptions(context.Background(), opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
lines := strings.Split(response.SingleValue(), "\n")
var configFile string
for _, line := range lines {
if strings.HasPrefix(line, "config_file:") {
configFile = strings.TrimSpace(strings.TrimPrefix(line, "config_file:"))
break
}
}
if len(configFile) > 0 {
responseRewrite, err := client.ConfigRewrite(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
runResultRandomRoute = responseRewrite
}
runResultRandomRoute = "OK"
// default sections, multi node route
var runResultMultiNodeRoute string
opts = options.ClusterInfoOptions{
InfoOptions: nil,
RouteOption: &options.RouteOption{Route: config.AllPrimaries},
}
response, err = client.InfoWithOptions(context.Background(), opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
for _, data := range response.MultiValue() {
lines := strings.Split(data, "\n")
var configFile string
for _, line := range lines {
if strings.HasPrefix(line, "config_file:") {
configFile = strings.TrimSpace(strings.TrimPrefix(line, "config_file:"))
break
}
}
if len(configFile) > 0 {
responseRewrite, err := client.ConfigRewrite(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
runResultMultiNodeRoute = responseRewrite
break
}
runResultMultiNodeRoute = "OK"
}
fmt.Println("Multiple options without route result:", runResultNilRoute)
fmt.Println("Random route result:", runResultRandomRoute)
fmt.Println("Multi node route result:", runResultMultiNodeRoute)
Output: Multiple options without route result: OK Random route result: OK Multi node route result: OK
func (*ClusterClient) ConfigSet ¶
func (client *ClusterClient) ConfigSet(ctx context.Context, parameters map[string]string, ) (string, error)
Sets configuration parameters to the specified values. Starting from server version 7, command supports multiple parameters. The command will be sent to all nodes.
Parameters:
ctx - The context for controlling the command execution. parameters - A map consisting of configuration parameters and their respective values to set.
Return value:
OK if all configurations have been successfully set. Otherwise, raises an error.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
configParam := map[string]string{"timeout": "1000", "maxmemory": "1GB"}
result, err := client.ConfigSet(context.Background(), configParam)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*ClusterClient) ConfigSetWithOptions ¶
func (client *ClusterClient) ConfigSetWithOptions(ctx context.Context, parameters map[string]string, opts options.RouteOption, ) (string, error)
Sets configuration parameters to the specified values Starting from server version 7, command supports multiple parameters.
Parameters:
ctx - The context for controlling the command execution.
parameters - A map consisting of configuration parameters and their respective values to set.
opts - Specifies the routing configuration for the command. The client will route the
command to the nodes defined by route.
Return value:
OK if all configurations have been successfully set. Otherwise, raises an error.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
opts := options.RouteOption{Route: config.RandomRoute}
configParam := map[string]string{"timeout": "1000", "maxmemory": "1GB"}
result, err := client.ConfigSetWithOptions(context.Background(), configParam, opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*ClusterClient) Copy ¶
func (client *ClusterClient) Copy(ctx context.Context, source string, destination string) (bool, error)
Copies the value stored at the source to the destination key if the destination key does not yet exist.
Note:
When in cluster mode, both `source` and `destination` must map to the same hash slot.
Since:
Valkey 6.2.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. source - The key to the source value. destination - The key where the value should be copied to.
Return value:
`true` if source was copied, `false` if source was not copied.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.Set(context.Background(), "{key}1", "someValue")
result1, err := client.Copy(context.Background(), "{key}1", "{key}2")
result2, err := client.Get(context.Background(), "{key}2")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: OK true {someValue false}
func (*ClusterClient) CopyWithOptions ¶
func (client *ClusterClient) CopyWithOptions( ctx context.Context, source string, destination string, options options.CopyOptions, ) (bool, error)
Copies the value stored at the source to the destination key. When `replace` in `options` is `true`, removes the destination key first if it already exists, otherwise performs no action.
Note:
When in cluster mode, both `source` and `destination` must map to the same hash slot.
Since:
Valkey 6.2.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. source - The key to the source value. destination - The key where the value should be copied to. copyOptions - Set copy options with replace and DB destination-db
Return value:
`true` if source was copied, `false` if source was not copied.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.Set(context.Background(), "{key}1", "someValue")
opts := options.NewCopyOptions().SetReplace()
client.CopyWithOptions(context.Background(), "{key}1", "{key}2", *opts)
result, err := client.Get(context.Background(), "{key}2")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.Value())
Output: someValue
Example (DbDestination) ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.Set(context.Background(), "{key}1", "someValue")
opts := options.NewCopyOptions().SetDBDestination(1)
client.CopyWithOptions(context.Background(), "{key}1", "{key}2", *opts)
client.Select(context.Background(), 1)
result, err := client.Get(context.Background(), "{key}2")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.Value())
Output: someValue
func (*ClusterClient) CustomCommand ¶
func (client *ClusterClient) CustomCommand(ctx context.Context, args []string) (models.ClusterValue[any], error)
CustomCommand executes a single command, specified by args, without checking inputs. Every part of the command, including the command name and subcommands, should be added as a separate value in args. The returning value depends on the executed command.
The command will be routed automatically based on the passed command's default request policy.
See Valkey GLIDE Documentation for details on the restrictions and limitations of the custom command API.
This function should only be used for single-response commands. Commands that don't return complete response and awaits (such as SUBSCRIBE), or that return potentially more than a single response (such as XREAD), or that change the client's behavior (such as entering pub/sub mode on RESP2 connections) shouldn't be called using this function.
Parameters:
ctx - The context for controlling the command execution. args - Arguments for the custom command including the command name.
Return value:
The returned value for the custom command.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.CustomCommand(context.Background(), []string{"ping"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.SingleValue().(string))
Output: PONG
func (*ClusterClient) CustomCommandWithRoute ¶
func (client *ClusterClient) CustomCommandWithRoute(ctx context.Context, args []string, route config.Route, ) (models.ClusterValue[any], error)
CustomCommandWithRoute executes a single command, specified by args, without checking inputs. Every part of the command, including the command name and subcommands, should be added as a separate value in args. The returning value depends on the executed command.
See Valkey GLIDE Documentation for details on the restrictions and limitations of the custom command API.
Parameters:
ctx - The context for controlling the command execution.
args - Arguments for the custom command including the command name.
route - Specifies the routing configuration for the command. The client will route the
command to the nodes defined by route.
Return value:
The returning value depends on the executed command and route.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
route := config.SimpleNodeRoute(config.RandomRoute)
result, _ := client.CustomCommandWithRoute(context.Background(), []string{"ping"}, route)
fmt.Println(result.SingleValue().(string))
Output: PONG
func (*ClusterClient) DBSizeWithOptions ¶
func (client *ClusterClient) DBSizeWithOptions(ctx context.Context, opts options.RouteOption) (int64, error)
Returns the number of keys in the database.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. options - The [RouteOption] type.
Return value:
The number of keys in the database.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
route := config.SimpleNodeRoute(config.RandomRoute)
opts := options.RouteOption{
Route: route,
}
result, err := client.DBSizeWithOptions(context.Background(), opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 0
func (*ClusterClient) Decr ¶
Decrements the number stored at key by one. If key does not exist, it is set to 0 before performing the operation.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to decrement its value.
Return value:
The value of `key` after the decrement.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.Set(context.Background(), "my_key", "0")
result, err := client.Decr(context.Background(), "my_key")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: -1
func (*ClusterClient) DecrBy ¶
Decrements the number stored at code by amount. If key does not exist, it is set to 0 before performing the operation.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to decrement its value. amount - The amount to decrement.
Return value:
The value of `key` after the decrement.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.Set(context.Background(), "my_key", "20")
result, err := client.DecrBy(context.Background(), "my_key", 5)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 15
func (*ClusterClient) Del ¶
Del removes the specified keys from the database. A key is ignored if it does not exist.
Note:
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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - One or more keys to delete.
Return value:
Returns the number of keys that were removed.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.Set(context.Background(), "key1", "someValue")
result1, err := client.Set(context.Background(), "key2", "someValue")
result2, err := client.Del(context.Background(), []string{"key1", "key2", "key3"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: OK OK 2
func (*ClusterClient) Dump ¶
Serializes the value stored at key in a Valkey-specific format.
Parameters:
ctx - The context for controlling the command execution. key - The key to serialize.
Return value:
The serialized value of the data stored at key. If key does not exist, `nil` will be returned.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.Set(context.Background(), "key1", "someValue")
result1, err := client.Dump(context.Background(), "key1") // Contains serialized value of the data stored at key1
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1.IsNil())
Output: OK false
func (*ClusterClient) Echo ¶
func (client *ClusterClient) Echo(ctx context.Context, message string) (models.Result[string], error)
Echo the provided message back. The command will be routed to a random node.
Parameters:
message - The provided message.
Return value:
The provided message
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.Echo(context.Background(), "Hello")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: {Hello false}
func (*ClusterClient) EchoWithOptions ¶
func (client *ClusterClient) EchoWithOptions( ctx context.Context, message string, opts options.RouteOption, ) (models.ClusterValue[string], error)
Echo the provided message back.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
message - The message to be echoed back.
opts - Specifies the routing configuration for the command. The client will route the
command to the nodes defined by `opts.Route`.
Return value:
The message to be echoed back.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.EchoWithOptions(context.Background(), "Hello World", options.RouteOption{Route: config.RandomRoute})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.SingleValue())
Output: Hello World
func (*ClusterClient) Exec ¶
func (client *ClusterClient) Exec(ctx context.Context, batch pipeline.ClusterBatch, raiseOnError bool) ([]any, error)
Executes a batch by processing the queued commands.
See Valkey Transactions (Atomic Batches) and Valkey Pipelines (Non-Atomic Batches) for details.
Routing Behavior:
- Atomic batches (Transactions): Routed to the slot owner of the first key in the batch. If no key is found, the request is sent to a random node.
- Non-atomic batches (Pipelines): Each command is routed to the node owning the corresponding key's slot. If no key is present, routing follows the command's default request policy. Multi-node commands are automatically split and dispatched to the appropriate nodes.
Behavior notes:
Atomic Batches (Transactions): All key-based commands must map to the same hash slot. If keys span different slots, the transaction will fail. If the transaction fails due to a `WATCH` command, `Exec` will return `nil`.
Retry and Redirection:
If a redirection error occurs:
- Atomic batches (Transactions): The entire transaction will be redirected.
- Non-atomic batches (Pipelines): Only commands that encountered redirection errors will be redirected.
Retries for failures will be handled according to the `retry_server_error` and `retry_connection_error` parameters.
Parameters:
ctx - The context for controlling the command execution batch - A `ClusterBatch` object containing a list of commands to be executed. raiseOnError - Determines how errors are handled within the batch response. When set to `true`, the first encountered error in the batch will be raised as an error after all retries and reconnections have been executed. When set to `false`, errors will be included as part of the batch response array, allowing the caller to process both successful and failed commands together. In this case, error details will be provided as instances of `RequestError`.
Return value:
A list of results corresponding to the execution of each command in the batch. 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 `nil`. If the batch failed due to a `WATCH` command, `Exec` will return `nil`.
Example (Pipeline) ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
// Example 2: Non-Atomic Batch (Pipeline)
batch := pipeline.NewClusterBatch(false)
batch.Set("key1", "value1").Set("key2", "value2").Get("key1").Get("key2")
result, err := client.Exec(context.Background(), *batch, false)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [OK OK value1 value2]
Example (Transaction) ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
// Example 1: Atomic Batch (Transaction)
batch := pipeline.NewClusterBatch(true)
batch.Set("key", "1").CustomCommand([]string{"incr", "key"}).Get("key")
result, err := client.Exec(context.Background(), *batch, false)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [OK 2 2]
func (*ClusterClient) ExecWithOptions ¶
func (client *ClusterClient) ExecWithOptions( ctx context.Context, batch pipeline.ClusterBatch, raiseOnError bool, options pipeline.ClusterBatchOptions, ) ([]any, error)
Executes a batch by processing the queued commands.
See Valkey Transactions (Atomic Batches) and Valkey Pipelines (Non-Atomic Batches) for details.
Routing Behavior ¶
If a `route` is specified:
- The entire batch is sent to the specified node.
If no `route` is specified:
- Atomic batches (Transactions): Routed to the slot owner of the first key in the batch. If no key is found, the request is sent to a random node.
- Non-atomic batches (Pipelines): Each command is routed to the node owning the corresponding key's slot. If no key is present, routing follows the command's default request policy. Multi-node commands are automatically split and dispatched to the appropriate nodes.
Behavior notes ¶
Atomic Batches (Transactions): All key-based commands must map to the same hash slot. If keys span different slots, the transaction will fail. If the transaction fails due to a `WATCH` command, `Exec` will return `nil`.
Retry and Redirection ¶
If a redirection error occurs:
- Atomic batches (Transactions): The entire transaction will be redirected.
- Non-atomic batches (Pipelines): Only commands that encountered redirection errors will be redirected.
Retries for failures will be handled according to the `retry_server_error` and `retry_connection_error` parameters.
Parameters:
ctx - The context for controlling the command execution batch - A `ClusterBatch` object containing a list of commands to be executed. raiseOnError - Determines how errors are handled within the batch response. When set to `true`, the first encountered error in the batch will be raised as an error after all retries and reconnections have been executed. When set to `false`, errors will be included as part of the batch response array, allowing the caller to process both successful and failed commands together. In this case, error details will be provided as instances of `RequestError`. options - A [ClusterBatchOptions] object containing execution options.
Return value:
A list of results corresponding to the execution of each command in the batch. 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 `nil`. If the batch failed due to a `WATCH` command, `ExecWithOptions` will return `nil`.
Example (Pipeline) ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
// Example 2: Non-Atomic Batch (Pipeline)
batch := pipeline.NewClusterBatch(false)
batch.Set("key1", "value1").Set("key2", "value2").Get("key1").Get("key2")
// Set command retry parameters
retryStrategy := pipeline.NewClusterBatchRetryStrategy().WithRetryServerError(true).WithRetryConnectionError(true)
options := pipeline.NewClusterBatchOptions().WithRetryStrategy(*retryStrategy)
result, err := client.ExecWithOptions(context.Background(), *batch, false, *options)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [OK OK value1 value2]
Example (Route) ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
// Example 3: A transaction with a route
batch := pipeline.NewClusterBatch(true)
batch.CustomCommand([]string{"info", "server"})
// Set batch route
route := config.NewSlotKeyRoute(config.SlotTypePrimary, "abc")
options := pipeline.NewClusterBatchOptions().WithRoute(route)
_, err := client.ExecWithOptions(context.Background(), *batch, false, *options)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
Example (Transaction) ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
// Example 1: Atomic Batch (Transaction)
batch := pipeline.NewClusterBatch(true)
batch.Set("key", "1").CustomCommand([]string{"incr", "key"}).Get("key")
// Set a timeout of 1000 milliseconds
options := pipeline.NewClusterBatchOptions().WithTimeout(1000 * time.Millisecond)
result, err := client.ExecWithOptions(context.Background(), *batch, false, *options)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [OK 2 2]
func (*ClusterClient) Exists ¶
Exists returns the number of keys that exist in the database.
Note:
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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - One or more keys to check if they exist.
Return value:
Returns the number of existing keys.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.Set(context.Background(), "key1", "someValue")
result1, err := client.Set(context.Background(), "key2", "someValue")
result2, err := client.Exists(context.Background(), []string{"key1", "key2", "key3"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: OK OK 2
func (*ClusterClient) Expire ¶
func (client *ClusterClient) Expire(ctx context.Context, key string, expireTime time.Duration) (bool, error)
Expire sets a timeout on key. 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 expireTime is a 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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to expire. expireTime - Duration for the key to expire
Return value:
`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 ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.Set(context.Background(), "key", "someValue")
result1, err := client.ExpireAt(context.Background(), "key", time.Now().Add(1*time.Second))
result2, err := client.Expire(context.Background(), "key", 1*time.Second)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: OK true true
func (*ClusterClient) ExpireAt ¶
func (client *ClusterClient) ExpireAt(ctx context.Context, key string, expireTime time.Time) (bool, error)
ExpireAt 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 If key already has an existing expire set, the time to live is updated to the new value. If expireTime is a 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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to expire. expireTime - The timestamp for expiry.
Return value:
`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 ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.Set(context.Background(), "key", "someValue")
result1, err := client.ExpireAt(context.Background(), "key", time.Now().Add(1*time.Second))
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK true
func (*ClusterClient) ExpireAtWithOptions ¶
func (client *ClusterClient) ExpireAtWithOptions( ctx context.Context, key string, expireTime time.Time, expireCondition constants.ExpireCondition, ) (bool, error)
ExpireAt 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 If key already has an existing expire set, the time to live is updated to the new value. If expireTime is a 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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to expire. expireTime - The timestamp for expiry. expireCondition - The option to set expiry - see [options.ExpireCondition].
Return value:
`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 ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.Set(context.Background(), "key", "someValue")
result1, err := client.ExpireAtWithOptions(
context.Background(),
"key",
time.Now().Add(1*time.Second),
constants.HasNoExpiry,
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK true
func (*ClusterClient) ExpireTime ¶
Expire Time returns the absolute Unix timestamp (since January 1, 1970) at which the given key will expire, in seconds.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to determine the expiration value of.
Return value:
The expiration Unix timestamp in seconds. `-2` if key does not exist or `-1` is key exists but has no associated expiration.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.Set(context.Background(), "key", "someValue")
result1, err := client.ExpireTime(context.Background(), "key")
_, err = client.ExpireAt(
context.Background(),
"key",
time.Now().Add(10*time.Second),
) // ExpireTime("key") returns proper unix timestamp in seconds
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK -1
func (*ClusterClient) ExpireWithOptions ¶
func (client *ClusterClient) ExpireWithOptions( ctx context.Context, key string, expireTime time.Duration, expireCondition constants.ExpireCondition, ) (bool, error)
Expire sets a timeout on key. 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 expireTime is a 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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to expire. expireTime - Duration for the key to expire expireCondition - The option to set expiry, see [options.ExpireCondition].
Return value:
`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 ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.Set(context.Background(), "key", "someValue")
result1, err := client.ExpireWithOptions(context.Background(), "key", 1*time.Second, constants.HasNoExpiry)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK true
func (*ClusterClient) FCall ¶
Invokes a previously loaded function. The command will be routed to a primary random node. To route to a replica please refer to Client.FCallReadOnly or ClusterClient.FCallReadOnly.
Since:
Valkey 7.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. function - The function name.
Return value:
The invoked function's return value.
Example ¶
client := getExampleClusterClient()
// Load function
_, err := client.FunctionLoad(context.Background(), libraryCode, true)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Call function
fcallResult, err := client.FCall(context.Background(), "myfunc")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(fcallResult)
Output: 42
func (*ClusterClient) FCallReadOnly ¶
Invokes a previously loaded read-only function. This command is routed depending on the client's {@link ReadFrom} strategy.
Since:
Valkey 7.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. function - The function name.
Return value:
The invoked function's return value.
Example ¶
client := getExampleClusterClient()
// Load function
_, err := client.FunctionLoad(context.Background(), libraryCode, true)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Call function
fcallResult, err := client.FCallReadOnly(context.Background(), "myfunc")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(fcallResult)
Output: 42
func (*ClusterClient) FCallReadOnlyWithArgs ¶
func (client *ClusterClient) FCallReadOnlyWithArgs( ctx context.Context, function string, args []string, ) (models.ClusterValue[any], error)
Invokes a previously loaded read-only function. The command will be routed to a random primary node.
Since:
Valkey 7.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. function - The function name. args - An `array` of `function` arguments. `args` should not represent names of keys.
Return value:
The invoked function's return value wrapped by a [models.ClusterValue].
Example ¶
client := getExampleClusterClient()
// Load function
_, err := client.FunctionLoad(context.Background(), libraryCodeWithArgs, true)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Call function
result, err := client.FCallReadOnlyWithArgs(context.Background(), "myfunc", []string{"1", "2"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.SingleValue())
Output: 1
func (*ClusterClient) FCallReadOnlyWithArgsWithRoute ¶
func (client *ClusterClient) FCallReadOnlyWithArgsWithRoute(ctx context.Context, function string, args []string, route options.RouteOption, ) (models.ClusterValue[any], error)
Invokes a previously loaded read-only function.
Since:
Valkey 7.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution.
function - The function name.
args - An `array` of `function` arguments. `args` should not represent names of keys.
route - Specifies the routing configuration for the command. The client will route the
command to the nodes defined by `route`.
Return value:
The invoked function's return value wrapped by a [models.ClusterValue].
Example ¶
client := getExampleClusterClient()
// Load function
route := config.Route(config.AllPrimaries)
opts := options.RouteOption{
Route: route,
}
_, err := client.FunctionLoadWithRoute(context.Background(), libraryCodeWithArgs, true, opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Call function
result, err := client.FCallReadOnlyWithArgsWithRoute(context.Background(), "myfunc", []string{"1", "2"}, opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
for _, value := range result.MultiValue() {
fmt.Println(value)
break
}
Output: 1
func (*ClusterClient) FCallReadOnlyWithKeysAndArgs ¶
func (client *ClusterClient) FCallReadOnlyWithKeysAndArgs( ctx context.Context, function string, keys []string, args []string, ) (any, error)
Invokes a previously loaded read-only function. This command is routed depending on the client's {@link ReadFrom} strategy.
Note: When in cluster mode, all `keys` must map to the same hash slot.
Since:
Valkey 7.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. function - The function name. keys - An `array` of keys accessed by the function. To ensure the correct execution of functions, both in standalone and clustered deployments, all names of keys that a function accesses must be explicitly provided as `keys`. arguments - An `array` of `function` arguments. `arguments` should not represent names of keys.
Return value:
The invoked function's return value.
Example ¶
client := getExampleClusterClient()
// Load function
_, err := client.FunctionLoad(context.Background(), libraryCodeWithArgs, true)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Call function
key1 := "{testKey}-" + uuid.New().String()
key2 := "{testKey}-" + uuid.New().String()
result, err := client.FCallReadOnlyWithKeysAndArgs(
context.Background(),
"myfunc",
[]string{key1, key2},
[]string{"3", "4"},
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 3
func (*ClusterClient) FCallReadOnlyWithRoute ¶
func (client *ClusterClient) FCallReadOnlyWithRoute(ctx context.Context, function string, route options.RouteOption, ) (models.ClusterValue[any], error)
Invokes a previously loaded read-only function.
Since:
Valkey 7.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution.
function - The function name.
route - Specifies the routing configuration for the command. The client will route the
command to the nodes defined by route.
Return value:
The invoked function's return value.
Example ¶
client := getExampleClusterClient()
// Load function
route := config.Route(config.AllPrimaries)
opts := options.RouteOption{
Route: route,
}
_, err := client.FunctionLoadWithRoute(context.Background(), libraryCode, true, opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Call function
result, err := client.FCallReadOnlyWithRoute(context.Background(), "myfunc", opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
for _, value := range result.MultiValue() {
fmt.Println(value)
break
}
Output: 42
func (*ClusterClient) FCallWithArgs ¶
func (client *ClusterClient) FCallWithArgs( ctx context.Context, function string, args []string, ) (models.ClusterValue[any], error)
Invokes a previously loaded function. The command will be routed to a random primary node.
Since:
Valkey 7.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. function - The function name. args - An `array` of `function` arguments. `args` should not represent names of keys.
Return value:
The invoked function's return value wrapped by a [models.ClusterValue].
Example ¶
client := getExampleClusterClient()
// Load function
_, err := client.FunctionLoad(context.Background(), libraryCodeWithArgs, true)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Call function
result, err := client.FCallWithArgs(context.Background(), "myfunc", []string{"1", "2"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.SingleValue())
Output: 1
func (*ClusterClient) FCallWithArgsWithRoute ¶
func (client *ClusterClient) FCallWithArgsWithRoute(ctx context.Context, function string, args []string, route options.RouteOption, ) (models.ClusterValue[any], error)
Invokes a previously loaded function.
Since:
Valkey 7.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution.
function - The function name.
arguments - An `array` of `function` arguments. `arguments` should not represent names of keys.
route - Specifies the routing configuration for the command. The client will route the
command to the nodes defined by `route`.
Return value:
The invoked function's return value wrapped by a [models.ClusterValue].
Example ¶
client := getExampleClusterClient()
// Load function
route := config.Route(config.AllPrimaries)
opts := options.RouteOption{
Route: route,
}
_, err := client.FunctionLoadWithRoute(context.Background(), libraryCodeWithArgs, true, opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Call function
result, err := client.FCallWithArgsWithRoute(context.Background(), "myfunc", []string{"1", "2"}, opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
for _, value := range result.MultiValue() {
fmt.Println(value)
break
}
Output: 1
func (*ClusterClient) FCallWithKeysAndArgs ¶
func (client *ClusterClient) FCallWithKeysAndArgs( ctx context.Context, function string, keys []string, args []string, ) (any, error)
Invokes a previously loaded function. This command is routed to primary nodes only. To route to a replica please refer to Client.FCallReadOnly or ClusterClient.FCallReadOnly.
Since:
Valkey 7.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. function - The function name. keys - An `array` of keys accessed by the function. To ensure the correct execution of functions, both in standalone and clustered deployments, all names of keys that a function accesses must be explicitly provided as `keys`. arguments - An `array` of `function` arguments. `arguments` should not represent names of keys.
Return value:
The invoked function's return value.
Example ¶
client := getExampleClusterClient()
// Load function
_, err := client.FunctionLoad(context.Background(), libraryCodeWithArgs, true)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Call function
key1 := "{testKey}-" + uuid.New().String()
key2 := "{testKey}-" + uuid.New().String()
result, err := client.FCallWithKeysAndArgs(context.Background(), "myfunc", []string{key1, key2}, []string{"3", "4"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 3
func (*ClusterClient) FCallWithRoute ¶
func (client *ClusterClient) FCallWithRoute( ctx context.Context, function string, route options.RouteOption, ) (models.ClusterValue[any], error)
Invokes a previously loaded function. To route to a replica please refer to ClusterClient.FCallReadOnly.
Since:
Valkey 7.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution.
function - The function name.
route - Specifies the routing configuration for the command. The client will route the
command to the nodes defined by route.
Return value:
The invoked function's return value.
Example ¶
client := getExampleClusterClient()
// Load function
route := config.Route(config.AllPrimaries)
opts := options.RouteOption{
Route: route,
}
_, err := client.FunctionLoadWithRoute(context.Background(), libraryCode, true, opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Call function
result, err := client.FCallWithRoute(context.Background(), "myfunc", opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
for _, value := range result.MultiValue() {
fmt.Println(value)
break
}
Output: 42
func (*ClusterClient) FlushAll ¶
func (client *ClusterClient) FlushAll(ctx context.Context) (string, error)
Deletes all the keys of all the existing databases. The command will be routed to all primary nodes.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
`"OK"` response on success.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.FlushAll(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*ClusterClient) FlushAllWithOptions ¶
func (client *ClusterClient) FlushAllWithOptions( ctx context.Context, flushOptions options.FlushClusterOptions, ) (string, error)
Deletes all the keys of all the existing databases.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. flushOptions - The [FlushClusterOptions] type.
Return value:
`"OK"` response on success.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
route := config.SimpleNodeRoute(config.AllPrimaries)
routeOption := &options.RouteOption{
Route: route,
}
asyncMode := options.ASYNC
flushOptions := options.FlushClusterOptions{
FlushMode: &asyncMode,
RouteOption: routeOption,
}
result, err := client.FlushAllWithOptions(context.Background(), flushOptions)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*ClusterClient) FlushDB ¶
func (client *ClusterClient) FlushDB(ctx context.Context) (string, error)
Deletes all the keys of the currently selected database. The command will be routed to all primary nodes.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
`"OK"` response on success.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.FlushDB(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*ClusterClient) FlushDBWithOptions ¶
func (client *ClusterClient) FlushDBWithOptions( ctx context.Context, flushOptions options.FlushClusterOptions, ) (string, error)
Deletes all the keys of the currently selected database.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. flushOptions - The [FlushClusterOptions] type.
Return value:
`"OK"` response on success.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
route := config.SimpleNodeRoute(config.AllPrimaries)
routeOption := &options.RouteOption{
Route: route,
}
syncMode := options.SYNC
flushOptions := options.FlushClusterOptions{
FlushMode: &syncMode,
RouteOption: routeOption,
}
result, err := client.FlushDBWithOptions(context.Background(), flushOptions)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*ClusterClient) FunctionDelete ¶
Deletes a library and all its functions. The command will be routed to all primary nodes.
Since:
Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. libName - The library name to delete.
Return value:
"OK" if the library exists, otherwise an error is thrown.
Example ¶
client := getExampleClusterClient()
// Load a function first
_, err := client.FunctionLoad(context.Background(), libraryCode, true)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
// Delete function
result, err := client.FunctionDelete(context.Background(), "mylib")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*ClusterClient) FunctionDeleteWithRoute ¶
func (client *ClusterClient) FunctionDeleteWithRoute( ctx context.Context, libName string, route options.RouteOption, ) (string, error)
Deletes a library and all its functions.
Since:
Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
libName - The library name to delete.
route - Specifies the routing configuration for the command. The client will route the
command to the nodes defined by `route`.
Return value:
"OK" if the library exists, otherwise an error is thrown.
Example ¶
client := getExampleClusterClient()
// Load a function first
route := config.Route(config.AllPrimaries)
opts := options.RouteOption{
Route: route,
}
_, err := client.FunctionLoadWithRoute(context.Background(), libraryCode, true, opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
// Delete function with route
result, err := client.FunctionDeleteWithRoute(context.Background(), "mylib", opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*ClusterClient) FunctionDump ¶
func (client *ClusterClient) FunctionDump(ctx context.Context) (string, error)
Returns the serialized payload of all loaded libraries.
Note:
The command will be routed to a random node.
Since:
Valkey 7.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
The serialized payload of all loaded libraries.
Example ¶
client := getExampleClusterClient()
// Call FunctionDump to get the serialized payload of all loaded libraries
dump, _ := client.FunctionDump(context.Background())
if len(dump) > 0 {
fmt.Println("Function dump got a payload")
}
Output: Function dump got a payload
func (*ClusterClient) FunctionDumpWithRoute ¶
func (client *ClusterClient) FunctionDumpWithRoute( ctx context.Context, route config.Route, ) (models.ClusterValue[string], error)
Returns the serialized payload of all loaded libraries. The command will be routed to the nodes defined by the route parameter.
Since:
Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. route - Specifies the routing configuration for the command.
Return value:
A [models.ClusterValue] containing the serialized payload of all loaded libraries.
Example ¶
client := getExampleClusterClient()
// Call FunctionDumpWithRoute to get the serialized payload of all loaded libraries with a route
dump, _ := client.FunctionDumpWithRoute(context.Background(), config.RandomRoute)
if len(dump.SingleValue()) > 0 {
fmt.Println("Function dump got a payload")
}
Output: Function dump got a payload
func (*ClusterClient) FunctionFlush ¶
Deletes all function libraries.
Since:
Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
`OK`
Example ¶
client := getExampleClusterClient()
result, err := client.FunctionFlush(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*ClusterClient) FunctionFlushAsync ¶
Deletes all function libraries in asynchronous mode.
Since:
Valkey 7.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
`OK`
Example ¶
client := getExampleClusterClient()
result, err := client.FunctionFlushAsync(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
func (*ClusterClient) FunctionFlushAsyncWithRoute ¶
func (client *ClusterClient) FunctionFlushAsyncWithRoute(ctx context.Context, route options.RouteOption) (string, error)
Deletes all function libraries in asynchronous mode.
Since:
Valkey 7.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution.
route - Specifies the routing configuration for the command. The client will route the
command to the nodes defined by route.
Return value:
`OK`
Example ¶
client := getExampleClusterClient()
route := config.Route(config.AllPrimaries)
opts := options.RouteOption{
Route: route,
}
result, err := client.FunctionFlushAsyncWithRoute(context.Background(), opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*ClusterClient) FunctionFlushSync ¶
Deletes all function libraries in synchronous mode.
Since:
Valkey 7.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
`OK`
Example ¶
client := getExampleClient()
result, err := client.FunctionFlushSync(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*ClusterClient) FunctionFlushSyncWithRoute ¶
func (client *ClusterClient) FunctionFlushSyncWithRoute(ctx context.Context, route options.RouteOption) (string, error)
Deletes all function libraries in synchronous mode.
Since:
Valkey 7.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution.
route - Specifies the routing configuration for the command. The client will route the
command to the nodes defined by route.
Return value:
`OK`
Example ¶
client := getExampleClusterClient()
route := config.Route(config.AllPrimaries)
opts := options.RouteOption{
Route: route,
}
result, err := client.FunctionFlushSyncWithRoute(context.Background(), opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*ClusterClient) FunctionFlushWithRoute ¶
func (client *ClusterClient) FunctionFlushWithRoute(ctx context.Context, route options.RouteOption) (string, error)
Deletes all function libraries.
Since:
Valkey 7.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution.
route - Specifies the routing configuration for the command. The client will route the
command to the nodes defined by route.
Return value:
`OK`
Example ¶
client := getExampleClusterClient()
route := config.Route(config.AllPrimaries)
opts := options.RouteOption{
Route: route,
}
result, err := client.FunctionFlushWithRoute(context.Background(), opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*ClusterClient) FunctionKill ¶
func (client *ClusterClient) FunctionKill(ctx context.Context) (string, error)
Kills a function that is currently executing.
`FUNCTION KILL` terminates read-only functions only.
Since:
Valkey 7.0 and above.
Note:
This command will be routed to all nodes.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
`OK` if function is terminated. Otherwise, throws an error.
Example ¶
client := getExampleClusterClient()
// Try to kill when no function is running
_, err := client.FunctionKill(context.Background())
if err != nil {
fmt.Println("Expected error:", err)
}
Output: Expected error: An error was signalled by the server: - NotBusy: No scripts in execution right now.
func (*ClusterClient) FunctionKillWithRoute ¶
func (client *ClusterClient) FunctionKillWithRoute(ctx context.Context, route options.RouteOption) (string, error)
Kills a function that is currently executing.
`FUNCTION KILL` terminates read-only functions only.
Since:
Valkey 7.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution.
route - Specifies the routing configuration for the command. The client will route the
command to the nodes defined by route.
Return value:
`OK` if function is terminated. Otherwise, throws an error.
Example ¶
client := getExampleClusterClient()
// Try to kill with route when no function is running
route := config.Route(config.AllPrimaries)
opts := options.RouteOption{
Route: route,
}
_, err := client.FunctionKillWithRoute(context.Background(), opts)
if err != nil {
fmt.Println("Expected error:", err)
}
Output: Expected error: An error was signalled by the server: - NotBusy: No scripts in execution right now.
func (*ClusterClient) FunctionList ¶
func (client *ClusterClient) FunctionList(ctx context.Context, query models.FunctionListQuery) ([]models.LibraryInfo, error)
Returns information about the functions and libraries.
Since:
Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. query - The query to use to filter the functions and libraries.
Return value:
A list of info about queried libraries and their functions.
Example ¶
client := getExampleClusterClient()
// Load a function first
_, err := client.FunctionLoad(context.Background(), libraryCode, true)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
query := models.FunctionListQuery{
LibraryName: "mylib",
WithCode: true,
}
libs, err := client.FunctionList(context.Background(), query)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Printf("There are %d libraries loaded.\n", len(libs))
for i, lib := range libs {
fmt.Printf("%d) Library name '%s', on engine %s, with %d functions\n", i+1, lib.Name, lib.Engine, len(lib.Functions))
for j, fn := range lib.Functions {
fmt.Printf(" %d) function '%s'\n", j+1, fn.Name)
}
}
Output: There are 1 libraries loaded. 1) Library name 'mylib', on engine LUA, with 1 functions 1) function 'myfunc'
func (*ClusterClient) FunctionListWithRoute ¶
func (client *ClusterClient) FunctionListWithRoute(ctx context.Context, query models.FunctionListQuery, route options.RouteOption, ) (models.ClusterValue[[]models.LibraryInfo], error)
Returns information about the functions and libraries.
Since:
Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
query - The query to use to filter the functions and libraries.
route - Specifies the routing configuration for the command. The client will route the
command to the nodes defined by route.
Return value:
A [models.ClusterValue] containing a list of info about queried libraries and their functions.
Example ¶
client := getExampleClusterClient()
// Load a function first
route := config.Route(config.AllPrimaries)
opts := options.RouteOption{
Route: route,
}
_, err := client.FunctionLoadWithRoute(context.Background(), libraryCode, true, opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
// List functions with route
query := models.FunctionListQuery{
WithCode: true,
}
result, err := client.FunctionListWithRoute(context.Background(), query, opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
// Print results for each node
for _, libs := range result.MultiValue() {
fmt.Println("Example Node:")
for _, lib := range libs {
fmt.Printf(" Library: %s\n", lib.Name)
fmt.Printf(" Engine: %s\n", lib.Engine)
fmt.Printf(" Functions: %d\n", len(lib.Functions))
}
break
}
Output: Example Node: Library: mylib Engine: LUA Functions: 1
func (*ClusterClient) FunctionLoad ¶
func (client *ClusterClient) FunctionLoad(ctx context.Context, libraryCode string, replace bool) (string, error)
Loads a library to Valkey.
Since:
Valkey 7.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. libraryCode - The source code that implements the library. replace - Whether the given library should overwrite a library with the same name if it already exists.
Return value:
The library name that was loaded.
Example ¶
client := getExampleClusterClient()
result, err := client.FunctionLoad(context.Background(), libraryCode, true)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: mylib
func (*ClusterClient) FunctionLoadWithRoute ¶
func (client *ClusterClient) FunctionLoadWithRoute(ctx context.Context, libraryCode string, replace bool, route options.RouteOption, ) (string, error)
Loads a library to Valkey.
Since:
Valkey 7.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. libraryCode - The source code that implements the library. replace - Whether the given library should overwrite a library with the same name if it already exists. route - Specifies the routing configuration for the command. The client will route the command to the nodes defined by route.
Return value:
The library name that was loaded.
Example ¶
client := getExampleClusterClient()
route := config.Route(config.AllPrimaries)
opts := options.RouteOption{
Route: route,
}
result, err := client.FunctionLoadWithRoute(context.Background(), libraryCode, true, opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: mylib
func (*ClusterClient) FunctionRestore ¶
Restores libraries from the serialized payload returned by `FunctionDump`.
Note:
The command will be routed to all primary nodes.
Since:
Valkey 7.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. payload - The serialized data from `FunctionDump`.
Return value:
`OK`
Example ¶
client := getExampleClusterClient()
// Attempt to restore with invalid dump data
invalidDump := "invalid_dump_data"
_, err := client.FunctionRestore(context.Background(), invalidDump)
if err != nil {
fmt.Println("Error:", err.Error())
}
Output: Error: An error was signalled by the server: - ResponseError: DUMP payload version or checksum are wrong
func (*ClusterClient) FunctionRestoreWithPolicy ¶
func (client *ClusterClient) FunctionRestoreWithPolicy( ctx context.Context, payload string, policy constants.FunctionRestorePolicy, ) (string, error)
Restores libraries from the serialized payload returned by `FunctionDump`.
Note:
The command will be routed to all primary nodes.
Since:
Valkey 7.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. payload - The serialized data from `FunctionDump`. policy - A policy for handling existing libraries.
Return value:
`OK`
Example ¶
client := getExampleClusterClient()
// Attempt to restore with invalid dump data and policy
invalidDump := "invalid_dump_data"
_, err := client.FunctionRestoreWithPolicy(context.Background(), invalidDump, constants.FlushPolicy)
if err != nil {
fmt.Println("Error:", err.Error())
}
Output: Error: An error was signalled by the server: - ResponseError: DUMP payload version or checksum are wrong
func (*ClusterClient) FunctionRestoreWithPolicyWithRoute ¶
func (client *ClusterClient) FunctionRestoreWithPolicyWithRoute( ctx context.Context, payload string, policy constants.FunctionRestorePolicy, route config.Route, ) (string, error)
Restores libraries from the serialized payload. The command will be routed to the nodes defined by the route parameter.
Since:
Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. payload - The serialized data from dump operation. policy - A policy for handling existing libraries. route - Specifies the routing configuration for the command.
Return value:
`OK`
Example ¶
client := getExampleClusterClient()
// Attempt to restore with invalid dump data, policy and route
invalidDump := "invalid_dump_data"
route := config.RandomRoute
_, err := client.FunctionRestoreWithPolicyWithRoute(context.Background(), invalidDump, constants.FlushPolicy, route)
if err != nil {
fmt.Println("Error:", err.Error())
}
Output: Error: An error was signalled by the server: - ResponseError: DUMP payload version or checksum are wrong
func (*ClusterClient) FunctionRestoreWithRoute ¶
func (client *ClusterClient) FunctionRestoreWithRoute( ctx context.Context, payload string, route config.Route, ) (string, error)
Restores libraries from the serialized payload. The command will be routed to the nodes defined by the route parameter.
Since:
Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. payload - The serialized data from dump operation. route - Specifies the routing configuration for the command.
Return value:
`OK`
Example ¶
client := getExampleClusterClient()
// Attempt to restore with invalid dump data and route
invalidDump := "invalid_dump_data"
route := config.RandomRoute
_, err := client.FunctionRestoreWithRoute(context.Background(), invalidDump, route)
if err != nil {
fmt.Println("Error:", err.Error())
}
Output: Error: An error was signalled by the server: - ResponseError: DUMP payload version or checksum are wrong
func (*ClusterClient) FunctionStats ¶
func (client *ClusterClient) FunctionStats(ctx context.Context) ( map[string]models.FunctionStatsResult, error, )
FunctionStats returns information about the function that's currently running and information about the available execution engines. The command will be routed to all nodes by default.
Since:
Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
A map of node addresses to their function statistics represented by [FunctionStatsResult] object containing the following information: running_script - Information about the running script. engines - Information about available engines and their stats.
Example ¶
client := getExampleClusterClient()
// Load a function first
_, err := client.FunctionLoad(context.Background(), libraryCode, true)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
// Get function statistics
stats, err := client.FunctionStats(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
// Print statistics
fmt.Printf("Nodes reached: %d\n", len(stats))
for _, nodeStats := range stats {
fmt.Println("Example stats:")
for engineName, engine := range nodeStats.Engines {
fmt.Printf(" Engine %s: %d functions, %d libraries\n",
engineName, engine.FunctionCount, engine.LibraryCount)
}
break
}
Output: Nodes reached: 6 Example stats: Engine LUA: 1 functions, 1 libraries
func (*ClusterClient) FunctionStatsWithRoute ¶
func (client *ClusterClient) FunctionStatsWithRoute(ctx context.Context, opts options.RouteOption, ) (models.ClusterValue[models.FunctionStatsResult], error)
FunctionStatsWithRoute returns information about the function that's currently running and information about the available execution engines.
Since:
Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
opts - Specifies the routing configuration for the command. The client will route the
command to the nodes defined by route. If no route is specified, the command
will be routed to all nodes.
Return value:
A [models.ClusterValue] containing a map of node addresses to their function statistics.
Example ¶
client := getExampleClusterClient()
// Load a function first
route := config.Route(config.AllPrimaries)
opts := options.RouteOption{
Route: route,
}
_, err := client.FunctionLoadWithRoute(context.Background(), libraryCode, true, opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
// Get function statistics with route
stats, err := client.FunctionStatsWithRoute(context.Background(), opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
// Print statistics
fmt.Printf("Nodes reached: %d\n", len(stats.MultiValue()))
for _, nodeStats := range stats.MultiValue() {
fmt.Println("Example stats:")
for engineName, engine := range nodeStats.Engines {
fmt.Printf(" Engine %s: %d functions, %d libraries\n",
engineName, engine.FunctionCount, engine.LibraryCount)
}
break
}
Output: Nodes reached: 3 Example stats: Engine LUA: 1 functions, 1 libraries
func (*ClusterClient) GeoAdd ¶
func (client *ClusterClient) GeoAdd( ctx context.Context, key string, membersToGeospatialData map[string]options.GeospatialData, ) (int64, error)
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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. membersToGeospatialData - A map of member names to their corresponding positions. See [options.GeospatialData]. The command will report an error when index coordinates are out of the specified range.
Return value:
The number of elements added to the sorted set.
Example ¶
client := getExampleClusterClient()
membersToCoordinates := map[string]options.GeospatialData{
"Palermo": {Longitude: 13.361389, Latitude: 38.115556},
"Catania": {Longitude: 15.087269, Latitude: 37.502669},
}
result, err := client.GeoAdd(context.Background(), uuid.New().String(), membersToCoordinates)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 2
func (*ClusterClient) GeoAddWithOptions ¶
func (client *ClusterClient) GeoAddWithOptions( ctx context.Context, key string, membersToGeospatialData map[string]options.GeospatialData, geoAddOptions options.GeoAddOptions, ) (int64, error)
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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. membersToGeospatialData - A map of member names to their corresponding positions. See [options.GeospatialData]. The command will report an error when index coordinates are out of the specified range. geoAddOptions - The options for the GeoAdd command, see - [options.GeoAddOptions].
Return value:
The number of elements added to the sorted set.
func (*ClusterClient) GeoDist ¶
func (client *ClusterClient) GeoDist( ctx context.Context, key string, member1 string, member2 string, ) (models.Result[float64], error)
Returns the distance between `member1` and `member2` saved in the geospatial index stored at `key`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. member1 - The name of the first member. member2 - The name of the second member.
Return value:
The distance between `member1` and `member2`. If one or both members do not exist, or if the key does not exist, returns `nil`. The default unit is meters, see - [options.Meters]
Example ¶
client := getExampleClusterClient()
key := uuid.New().String()
member1 := "Palermo"
member2 := "Catania"
membersToCoordinates := map[string]options.GeospatialData{
"Palermo": {Longitude: 13.361389, Latitude: 38.115556},
"Catania": {Longitude: 15.087269, Latitude: 37.502669},
}
// Add the coordinates
_, err := client.GeoAdd(context.Background(), key, membersToCoordinates)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Test getting geodist for multiple members
result, err := client.GeoDist(context.Background(), key, member1, member2)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.Value())
Output: 166274.1516
func (*ClusterClient) GeoDistWithUnit ¶
func (client *ClusterClient) GeoDistWithUnit( ctx context.Context, key string, member1 string, member2 string, unit constants.GeoUnit, ) (models.Result[float64], error)
Returns the distance between `member1` and `member2` saved in the geospatial index stored at `key`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. member1 - The name of the first member. member2 - The name of the second member. unit - The unit of distance measurement - see [options.GeoUnit].
Return value:
The distance between `member1` and `member2`. If one or both members do not exist, or if the key does not exist, returns `nil`.
func (*ClusterClient) GeoHash ¶
func (client *ClusterClient) GeoHash(ctx context.Context, key string, members []string) ([]models.Result[string], error)
Returns the GeoHash strings representing the positions of all the specified `members` in the sorted set stored at the `key`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. members - The array of members whose GeoHash strings are to be retrieved.
Returns value:
An array of GeoHash strings (of type models.Result[string]) representing the positions of the specified members stored at key. If a member does not exist in the sorted set, a `nil` value is returned for that member.
Example ¶
client := getExampleClusterClient()
key := uuid.New().String()
membersToCoordinates := map[string]options.GeospatialData{
"Palermo": {Longitude: 13.361389, Latitude: 38.115556},
"Catania": {Longitude: 15.087269, Latitude: 37.502669},
}
// Add the coordinates
_, err := client.GeoAdd(context.Background(), key, membersToCoordinates)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Test getting geohash for multiple members
geoHashResults, err := client.GeoHash(context.Background(), key, []string{"Palermo", "Catania"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(geoHashResults)
Output: [{sqc8b49rny0 false} {sqdtr74hyu0 false}]
func (*ClusterClient) GeoPos ¶
func (client *ClusterClient) GeoPos(ctx context.Context, key string, members []string) ([][]float64, error)
Returns the positions (longitude,latitude) of all the specified members of the geospatial index represented by the sorted set at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. members - The members of the sorted set.
Return value:
A 2D `array` which represent positions (longitude and latitude) corresponding to the given members. If a member does not exist, its position will be `nil`.
Example ¶
client := getExampleClusterClient()
key := uuid.New().String()
_, err := client.GeoAdd(context.Background(), key, map[string]options.GeospatialData{
"Palermo": {Longitude: 13.361389, Latitude: 38.115556},
"Catania": {Longitude: 15.087269, Latitude: 37.502669},
})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
positions, err := client.GeoPos(context.Background(), key, []string{"Palermo", "Catania"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(positions)
Output: [[13.361389338970184 38.1155563954963] [15.087267458438873 37.50266842333162]]
func (*ClusterClient) GeoSearch ¶
func (client *ClusterClient) GeoSearch( ctx context.Context, key string, searchFrom options.GeoSearchOrigin, searchByShape options.GeoSearchShape, ) ([]string, error)
Returns the members of a sorted set populated with geospatial information using Client.GeoAdd or ClusterClient.GeoAdd, which are within the borders of the area specified by a given shape.
Since:
Valkey 6.2.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. searchFrom - 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. searchByShape - The query's shape options: - `BYRADIUS` to search inside circular area according to given radius. - `BYBOX` to search inside an axis-aligned rectangle, determined by height and width.
Return value:
An array of matched member names.
Example ¶
client := getExampleClusterClient()
key := uuid.New().String()
AddInitialGeoData(client, key)
result, err := client.GeoSearch(context.Background(),
key,
&options.GeoMemberOrigin{Member: "Palermo"},
*options.NewCircleSearchShape(200, constants.GeoUnitKilometers),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [Palermo]
func (*ClusterClient) GeoSearchStore ¶
func (client *ClusterClient) GeoSearchStore( ctx context.Context, destinationKey string, sourceKey string, searchFrom options.GeoSearchOrigin, searchByShape options.GeoSearchShape, ) (int64, error)
Searches for members in a sorted set stored at `sourceKey` representing geospatial data within a circular or rectangular area and stores the result in `destinationKey`. If `destinationKey` already exists, it is overwritten. Otherwise, a new sorted set will be created. To get the result directly, see Client.GeoSearchWithFullOptions or ClusterClient.GeoSearchWithFullOptions.
Since:
Valkey 6.2.0 and above.
Note:
When in cluster mode, `destinationKey` and `sourceKey` must map to the same hash slot.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution.
destinationKey - The key of the sorted set to store the result.
sourceKey - The key of the sorted set to search.
searchFrom - 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.
searchByShape - The query's shape options:
- `BYRADIUS` to search inside circular area according to given radius.
- `BYBOX` to search inside an axis-aligned rectangle, determined by height and width.
Return value:
The number of elements in the resulting set.
Example ¶
client := getExampleClusterClient()
source := "{key-}" + uuid.New().String()
destination := "{key-}" + uuid.New().String()
AddInitialGeoData(client, source)
result, err := client.GeoSearchStore(context.Background(),
destination,
source,
&options.GeoMemberOrigin{Member: "Palermo"},
*options.NewCircleSearchShape(200, constants.GeoUnitKilometers),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 1
func (*ClusterClient) GeoSearchStoreWithFullOptions ¶
func (client *ClusterClient) GeoSearchStoreWithFullOptions( ctx context.Context, destinationKey string, sourceKey string, searchFrom options.GeoSearchOrigin, searchByShape options.GeoSearchShape, resultOptions options.GeoSearchResultOptions, infoOptions options.GeoSearchStoreInfoOptions, ) (int64, error)
Searches for members in a sorted set stored at `sourceKey` representing geospatial data within a circular or rectangular area and stores the result in `destinationKey`. If `destinationKey` already exists, it is overwritten. Otherwise, a new sorted set will be created. To get the result directly, see Client.GeoSearchWithFullOptions or ClusterClient.GeoSearchWithFullOptions.
Since:
Valkey 6.2.0 and above.
Note:
When in cluster mode, `destinationKey` and `sourceKey` must map to the same hash slot.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. destinationKey - The key of the sorted set to store the result. sourceKey - The key of the sorted set to search. searchFrom - 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. searchByShape - The query's shape options: - `BYRADIUS` to search inside circular area according to given radius. - `BYBOX` to search inside an axis-aligned rectangle, determined by height and width. resultOptions - Optional inputs for sorting/limiting the results. infoOptions - The optional inputs to request additional information.
Return value:
The number of elements in the resulting set.
Example ¶
client := getExampleClusterClient()
source := "{key-}" + uuid.New().String()
destination := "{key-}" + uuid.New().String()
AddInitialGeoData(client, source)
result, err := client.GeoSearchStoreWithFullOptions(context.Background(),
destination,
source,
&options.GeoMemberOrigin{Member: "Palermo"},
*options.NewCircleSearchShape(200, constants.GeoUnitKilometers),
*options.NewGeoSearchResultOptions().SetCount(1).SetSortOrder(options.DESC),
*options.NewGeoSearchStoreInfoOptions().SetStoreDist(true),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 1
func (*ClusterClient) GeoSearchStoreWithInfoOptions ¶
func (client *ClusterClient) GeoSearchStoreWithInfoOptions( ctx context.Context, destinationKey string, sourceKey string, searchFrom options.GeoSearchOrigin, searchByShape options.GeoSearchShape, infoOptions options.GeoSearchStoreInfoOptions, ) (int64, error)
Searches for members in a sorted set stored at `sourceKey` representing geospatial data within a circular or rectangular area and stores the result in `destinationKey`. If `destinationKey` already exists, it is overwritten. Otherwise, a new sorted set will be created. To get the result directly, see Client.GeoSearchWithFullOptions or ClusterClient.GeoSearchWithFullOptions.
Since:
Valkey 6.2.0 and above.
Note:
When in cluster mode, `destinationKey` and `sourceKey` must map to the same hash slot.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution.
destinationKey - The key of the sorted set to store the result.
sourceKey - The key of the sorted set to search.
searchFrom - 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.
searchByShape - The query's shape options:
- `BYRADIUS` to search inside circular area according to given radius.
- `BYBOX` to search inside an axis-aligned rectangle, determined by height and width.
infoOptions - The optional inputs to request additional information.
Return value:
The number of elements in the resulting set.
Example ¶
client := getExampleClusterClient()
source := "{key-}" + uuid.New().String()
destination := "{key-}" + uuid.New().String()
AddInitialGeoData(client, source)
result, err := client.GeoSearchStoreWithInfoOptions(context.Background(),
destination,
source,
&options.GeoMemberOrigin{Member: "Palermo"},
*options.NewCircleSearchShape(200, constants.GeoUnitKilometers),
*options.NewGeoSearchStoreInfoOptions().SetStoreDist(true),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 1
func (*ClusterClient) GeoSearchStoreWithResultOptions ¶
func (client *ClusterClient) GeoSearchStoreWithResultOptions( ctx context.Context, destinationKey string, sourceKey string, searchFrom options.GeoSearchOrigin, searchByShape options.GeoSearchShape, resultOptions options.GeoSearchResultOptions, ) (int64, error)
Searches for members in a sorted set stored at `sourceKey` representing geospatial data within a circular or rectangular area and stores the result in `destinationKey`. If `destinationKey` already exists, it is overwritten. Otherwise, a new sorted set will be created. To get the result directly, see Client.GeoSearchWithFullOptions or ClusterClient.GeoSearchWithFullOptions.
Since:
Valkey 6.2.0 and above.
Note:
When in cluster mode, `destinationKey` and `sourceKey` must map to the same hash slot.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution.
destinationKey - The key of the sorted set to store the result.
sourceKey - The key of the sorted set to search.
searchFrom - 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.
searchByShape - The query's shape options:
- `BYRADIUS` to search inside circular area according to given radius.
- `BYBOX` to search inside an axis-aligned rectangle, determined by height and width.
resultOptions - Optional inputs for sorting/limiting the results.
Return value:
The number of elements in the resulting set.
Example ¶
client := getExampleClusterClient()
source := "{key-}" + uuid.New().String()
destination := "{key-}" + uuid.New().String()
AddInitialGeoData(client, source)
result, err := client.GeoSearchStoreWithResultOptions(context.Background(),
destination,
source,
&options.GeoMemberOrigin{Member: "Palermo"},
*options.NewCircleSearchShape(200, constants.GeoUnitKilometers),
*options.NewGeoSearchResultOptions().SetCount(1).SetSortOrder(options.DESC),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 1
func (*ClusterClient) GeoSearchWithFullOptions ¶
func (client *ClusterClient) GeoSearchWithFullOptions( ctx context.Context, key string, searchFrom options.GeoSearchOrigin, searchByShape options.GeoSearchShape, resultOptions options.GeoSearchResultOptions, infoOptions options.GeoSearchInfoOptions, ) ([]options.Location, error)
Returns the members of a sorted set populated with geospatial information using Client.GeoAdd or ClusterClient.GeoAdd, which are within the borders of the area specified by a given shape.
Since:
Valkey 6.2.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. searchFrom - 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. searchByShape - The query's shape options: - `BYRADIUS` to search inside circular area according to given radius. - `BYBOX` to search inside an axis-aligned rectangle, determined by height and width. resultOptions - Optional inputs for sorting/limiting the results. infoOptions - The optional inputs to request additional information.
Return value:
An array of [options.Location] containing the following information: - The coordinates as a [options.GeospatialData] object. - The member (location) name. - The distance from the center as a `float64`, in the same unit specified for `searchByShape`. - The geohash of the location as a `int64`.
Example ¶
client := getExampleClusterClient()
key := uuid.New().String()
AddInitialGeoData(client, key)
result, err := client.GeoSearchWithFullOptions(context.Background(),
key,
&options.GeoMemberOrigin{Member: "Palermo"},
*options.NewCircleSearchShape(200, constants.GeoUnitKilometers),
*options.NewGeoSearchResultOptions().SetCount(2).SetSortOrder(options.DESC),
*options.NewGeoSearchInfoOptions().SetWithDist(true).SetWithCoord(true).SetWithHash(true),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [{Palermo {38.1155563954963 13.361389338970184} 0 3479099956230698}]
func (*ClusterClient) GeoSearchWithInfoOptions ¶
func (client *ClusterClient) GeoSearchWithInfoOptions( ctx context.Context, key string, searchFrom options.GeoSearchOrigin, searchByShape options.GeoSearchShape, infoOptions options.GeoSearchInfoOptions, ) ([]options.Location, error)
Returns the members of a sorted set populated with geospatial information using Client.GeoAdd or ClusterClient.GeoAdd, which are within the borders of the area specified by a given shape.
Since:
Valkey 6.2.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. searchFrom - 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. searchByShape - The query's shape options: - `BYRADIUS` to search inside circular area according to given radius. - `BYBOX` to search inside an axis-aligned rectangle, determined by height and width. infoOptions - The optional inputs to request additional information.
Return value:
An array of [options.Location] containing the following information: - The coordinates as a [options.GeospatialData] object. - The member (location) name. - The distance from the center as a `float64`, in the same unit specified for `searchByShape`. - The geohash of the location as a `int64`.
Example ¶
client := getExampleClusterClient()
key := uuid.New().String()
AddInitialGeoData(client, key)
result, err := client.GeoSearchWithInfoOptions(context.Background(),
key,
&options.GeoMemberOrigin{Member: "Palermo"},
*options.NewCircleSearchShape(200, constants.GeoUnitKilometers),
*options.NewGeoSearchInfoOptions().SetWithDist(true).SetWithCoord(true).SetWithHash(true),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [{Palermo {38.1155563954963 13.361389338970184} 0 3479099956230698}]
func (*ClusterClient) GeoSearchWithResultOptions ¶
func (client *ClusterClient) GeoSearchWithResultOptions( ctx context.Context, key string, searchFrom options.GeoSearchOrigin, searchByShape options.GeoSearchShape, resultOptions options.GeoSearchResultOptions, ) ([]string, error)
Returns the members of a sorted set populated with geospatial information using Client.GeoAdd or ClusterClient.GeoAdd, which are within the borders of the area specified by a given shape.
Since:
Valkey 6.2.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. searchFrom - 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. searchByShape - The query's shape options: - `BYRADIUS` to search inside circular area according to given radius. - `BYBOX` to search inside an axis-aligned rectangle, determined by height and width. resultOptions - Optional inputs for sorting/limiting the results.
Return value:
An array of matched member names.
Example ¶
client := getExampleClusterClient()
key := uuid.New().String()
AddInitialGeoData(client, key)
result, err := client.GeoSearchWithResultOptions(context.Background(),
key,
&options.GeoMemberOrigin{Member: "Palermo"},
*options.NewCircleSearchShape(200, constants.GeoUnitKilometers),
*options.NewGeoSearchResultOptions().SetCount(1).SetSortOrder(options.DESC),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [Palermo]
func (*ClusterClient) Get ¶
Get string value associated with the given key, or models.CreateNilStringResult() is returned if no such key exists.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to be retrieved from the database.
Return value:
If key exists, returns the value of key as a String. Otherwise, return [models.CreateNilStringResult()].
Example (Keyexists) ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.Set(context.Background(), "my_key", "my_value")
result, err := client.Get(context.Background(), "my_key")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.Value())
Output: my_value
Example (Keynotexists) ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.Get(context.Background(), "my_key")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.IsNil()) // missing key returns nil result
Output: true
func (*ClusterClient) GetBit ¶
Returns the bit value at offset in the string value stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the string. offset - The index of the bit to return. Should be greater than or equal to zero.
Return value:
The bit at offset of the string. Returns zero if the key is empty or if the positive offset exceeds the length of the string.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.SetBit(context.Background(), "my_key", 1, 1)
client.SetBit(context.Background(), "my_key", 1, 1)
result, err := client.GetBit(context.Background(), "my_key", 1)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 1
func (*ClusterClient) GetDel ¶
GetDel gets the value associated with the given key and deletes the key.
Parameters:
ctx - The context for controlling the command execution. key - The key to get and delete.
Return value:
If key exists, returns the value of the key as a String and deletes the key. If key does not exist, returns a [models.Result[string]](models.CreateNilStringResult()).
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.Set(context.Background(), "my_key", "my_value")
result, err := client.GetDel(context.Background(), "my_key") // return value and delete key
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.Value())
value, _ := client.Get(context.Background(), "my_key") // key should be missing
fmt.Println(value.IsNil())
Output: my_value true
func (*ClusterClient) GetEx ¶
Get string value associated with the given key, or an empty string is returned [models.CreateNilStringResult()] if no such value exists.
Since:
Valkey 6.2.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to be retrieved from the database.
Return value:
If key exists, returns the value of key as a models.Result[string]. Otherwise, return [models.CreateNilStringResult()].
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.Set(context.Background(), "my_key", "my_value")
result, err := client.GetEx(context.Background(), "my_key")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.Value())
ttl, _ := client.TTL(context.Background(), "my_key")
fmt.Println(ttl)
Output: my_value -1
func (*ClusterClient) GetExWithOptions ¶
func (client *ClusterClient) GetExWithOptions( ctx context.Context, key string, options options.GetExOptions, ) (models.Result[string], error)
Get string value associated with the given key and optionally sets the expiration of the key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to be retrieved from the database. options - The [options.GetExOptions].
Return value:
If key exists, returns the value of key as a models.Result[string]. Otherwise, return [models.CreateNilStringResult()].
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.Set(context.Background(), "my_key", "my_value")
options := options.NewGetExOptions().
SetExpiry(options.NewExpiryIn(5 * time.Second))
result, err := client.GetExWithOptions(context.Background(), "my_key", *options)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.Value())
ttl, _ := client.TTL(context.Background(), "my_key")
fmt.Println(ttl)
Output: my_value 5
func (*ClusterClient) GetQueue ¶
func (client *ClusterClient) GetQueue() (*PubSubMessageQueue, error)
GetQueue returns the pub/sub queue for the client. GetQueue returns the pub/sub queue for the client. Returns an error if the client is configured with a callback.
func (*ClusterClient) GetRange ¶
func (client *ClusterClient) GetRange(ctx context.Context, key string, start int, end int) (string, error)
Returns the substring of the string value stored at key, determined by the byte's 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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the string. start - The starting offset. end - The ending offset.
Return value:
A substring extracted from the value stored at key. Returns empty string if the offset is out of bounds.
Example (One) ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.Set(context.Background(), "my_key", "Welcome to Valkey Glide!")
result, err := client.GetRange(context.Background(), "my_key", 0, 7)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: Welcome
Example (Two) ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.Set(context.Background(), "my_key", "愛")
fmt.Println([]byte("愛")) // "愛" is a single character in UTF-8, but 3 bytes long
result, err := client.GetRange(context.Background(), "my_key", 0, 1)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println([]byte(result))
Output: [230 132 155] [230 132]
func (*ClusterClient) GetStatistics ¶ added in v2.3.0
GetStatistics retrieves compression, connection, and PubSub statistics for this client.
Return value:
A map[string]uint64 containing statistics: - total_connections: Total number of connections opened to Valkey - total_clients: Total number of GLIDE clients - total_values_compressed: Number of values successfully compressed - total_values_decompressed: Number of values successfully decompressed - total_original_bytes: Total bytes of original data before compression - total_bytes_compressed: Total bytes after compression - total_bytes_decompressed: Total bytes after decompression - compression_skipped_count: Number of times compression was skipped - subscription_out_of_sync_count: Number of times subscriptions were out of sync during reconciliation - subscription_last_sync_timestamp: Timestamp of last successful subscription sync (milliseconds since epoch)
func (*ClusterClient) GetSubscriptions ¶ added in v2.3.0
func (client *ClusterClient) GetSubscriptions(ctx context.Context) (*models.PubSubState, error)
GetSubscriptions retrieves both the desired and current subscription states. This allows verification of synchronization between what the client intends to be subscribed to (desired) and what it is actually subscribed to on the server (actual).
Parameters:
ctx - The context for the operation.
Return value:
A PubSubState containing desired and actual subscriptions, or an error.
Example:
state, err := client.GetSubscriptions(ctx)
if err != nil {
return err
}
// Check if subscribed to a channel
if _, ok := state.ActualSubscriptions[models.Exact]["channel1"]; ok {
fmt.Println("Subscribed to channel1")
}
func (*ClusterClient) HDel ¶
HDel removes the specified fields from the hash stored at key. Specified fields that do not exist within this hash are ignored. If key does not exist, it is treated as an empty hash and this command returns 0.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. fields - The fields to remove from the hash stored at key.
Return value:
The number of fields that were removed from the hash, not including specified but non-existing fields.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
fields := map[string]string{
"field1": "someValue",
"field2": "someOtherValue",
}
result, err := client.HSet(context.Background(), "my_hash", fields)
result1, err := client.HDel(context.Background(), "my_hash", []string{"field1", "field2"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 2 2
func (*ClusterClient) HExists ¶
HExists returns if field is an existing field in the hash stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. field - The field to check in the hash stored at key.
Return value:
A bool containing true if the hash contains the specified field. false if the hash does not contain the field, or if the key does not exist.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
fields := map[string]string{
"field1": "someValue",
"field2": "someOtherValue",
}
result, err := client.HSet(context.Background(), "my_hash", fields)
result1, err := client.HExists(context.Background(), "my_hash", "field1")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 2 true
func (*ClusterClient) HExpire ¶ added in v2.1.0
func (client *ClusterClient) HExpire( ctx context.Context, key string, expireTime time.Duration, fields []string, opts options.HExpireOptions, ) ([]int64, error)
Sets an expiration (TTL or time to live) on one or more fields of a given hash key. You must specify at least one field. Field(s) will automatically be deleted from the hash key when their TTLs expire. Field expirations will only be cleared by commands that delete or overwrite the contents of the hash fields, including HDEL and HSET commands. This means that all the operations that conceptually alter the value stored at a hash key's field without replacing it with a new one will leave the TTL untouched. You can clear the TTL of a specific field by specifying 0 for the `seconds` argument.
Note:
Calling HEXPIRE/HPEXPIRE with a time in the past will result in the hash field being deleted immediately.
Since:
Valkey 9.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. expireTime - The expiration time as a duration. fields - The fields to set expiration for. options - Optional arguments for the command, see [options.HExpireOptions].
Return value:
An array of integers indicating the result for each field: - -2: Field does not exist in the hash, or key does not exist. - 0: The specified condition was not met. - 1: The expiration time was applied. - 2: When called with 0 seconds.
Example ¶
// This command requires Valkey 9.0+
var client *ClusterClient = getExampleClusterClient() // example helper function
// First set some fields
fields := map[string]string{
"field1": "value1",
"field2": "value2",
}
client.HSet(context.Background(), "my_hash", fields)
// Set 30 second expiration on fields
result, err := client.HExpire(
context.Background(),
"my_hash",
30*time.Second,
[]string{"field1", "field2"},
options.HExpireOptions{},
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result[0]) // 1 means expiration was set
fmt.Println(result[1]) // 1 means expiration was set
Output: 1 1
func (*ClusterClient) HExpireAt ¶ added in v2.1.0
func (client *ClusterClient) HExpireAt( ctx context.Context, key string, expireTime time.Time, fields []string, opts options.HExpireOptions, ) ([]int64, error)
Sets an expiration (TTL or time to live) on one or more fields of a given hash key using an absolute Unix timestamp. A timestamp in the past will delete the field immediately. Field(s) will automatically be deleted from the hash key when their TTLs expire.
Since:
Valkey 9.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. expireTime - The expiration time as a time.Time. fields - The fields to set expiration for. options - Optional arguments for the command, see [options.HExpireOptions].
Return value:
An array of integers indicating the result for each field: - -2: Field does not exist in the hash, or hash is empty. - 0: The specified condition was not met. - 1: The expiration time was applied. - 2: When called with 0 seconds or past Unix time.
func (*ClusterClient) HExpireTime ¶ added in v2.1.0
func (client *ClusterClient) HExpireTime(ctx context.Context, key string, fields []string) ([]int64, error)
Returns the absolute Unix timestamp in seconds since Unix epoch at which the given key's field(s) will expire.
Since:
Valkey 9.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. fields - The fields to get expiration time for.
Return value:
An array of integers indicating the expiration timestamp for each field in seconds: - Positive number: expiration timestamp. - -1: field exists but has no expiration. - -2: field doesn't exist.
func (*ClusterClient) HGet ¶
func (client *ClusterClient) HGet(ctx context.Context, key string, field string) (models.Result[string], error)
HGet returns the value associated with field in the hash stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. field - The field in the hash stored at key to retrieve from the database.
Return value:
The models.Result[string] associated with field, or [models.Result[string]](models.CreateNilStringResult()) when field is not present in the hash or key does not exist.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
fields := map[string]string{
"field1": "someValue",
"field2": "someOtherValue",
}
result, err := client.HSet(context.Background(), "my_hash", fields)
payload, err := client.HGet(context.Background(), "my_hash", "field1")
payload2, err := client.HGet(context.Background(), "my_hash", "nonexistent_field")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(payload)
fmt.Println(payload2.IsNil())
Output: 2 {someValue false} true
func (*ClusterClient) HGetAll ¶
HGetAll returns all fields and values of the hash stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash.
Return value:
A map of all fields and their values in the hash, or an empty map when key does not exist.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
fields := map[string]string{
"field1": "someValue",
"field2": "someOtherValue",
}
result, err := client.HSet(context.Background(), "my_hash", fields)
payload, err := client.HGetAll(context.Background(), "my_hash")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(payload["field1"])
fmt.Println(payload["field2"])
fmt.Println(payload["notExistentField"]) // prints nothing
Output: 2 someValue someOtherValue
func (*ClusterClient) HGetEx ¶ added in v2.1.0
func (client *ClusterClient) HGetEx( ctx context.Context, key string, fields []string, opts options.HGetExOptions, ) ([]models.Result[string], error)
Gets the values of one or more fields of a given hash key and optionally sets their expiration time or time-to-live (TTL).
Since:
Valkey 9.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. fields - The fields in the hash stored at key to retrieve from the database. options - Optional arguments for the command.
Return value:
An array of [models.Result[string]] 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 [models.CreateNilStringResult()] is returned. - If key does not exist, returns an empty string array.
Example ¶
// This command requires Valkey 9.0+
var client *ClusterClient = getExampleClusterClient() // example helper function
// First set some fields
fields := map[string]string{
"field1": "value1",
"field2": "value2",
}
client.HSet(context.Background(), "my_hash", fields)
// Get fields and set 5 second expiration
options := options.NewHGetExOptions().SetExpiry(options.NewExpiryIn(5 * time.Second))
result, err := client.HGetEx(context.Background(), "my_hash", []string{"field1", "field2"}, options)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result[0].Value())
fmt.Println(result[1].Value())
Output: value1 value2
func (*ClusterClient) HIncrBy ¶
func (client *ClusterClient) HIncrBy(ctx context.Context, key string, field string, increment int64) (int64, error)
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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. field - The field in the hash stored at `key` to increment its value. increment - The amount to increment.
Return value:
The value of `field` in the hash stored at `key` after the increment.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
fields := map[string]string{
"field1": "10",
"field2": "14",
}
result, err := client.HSet(context.Background(), "my_hash", fields)
result1, err := client.HIncrBy(context.Background(), "my_hash", "field1", 1)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 2 11
func (*ClusterClient) HIncrByFloat ¶
func (client *ClusterClient) HIncrByFloat(ctx context.Context, key string, field string, increment float64) (float64, error)
Increments 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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. field - The field in the hash stored at `key` to increment its value. increment - The amount to increment.
Return value:
The value of `field` in the hash stored at `key` after the increment.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
fields := map[string]string{
"field1": "10",
"field2": "14",
}
result, err := client.HSet(context.Background(), "my_hash", fields)
result1, err := client.HIncrByFloat(context.Background(), "my_hash", "field1", 1.5)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 2 11.5
func (*ClusterClient) HKeys ¶
HKeys returns all field names in the hash stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash.
Return value:
A slice containing all the field names in the hash, or an empty slice when key does not exist.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
fields := map[string]string{
"field1": "someValue",
}
client.HSet(context.Background(), "my_hash", fields)
result, err := client.HKeys(context.Background(), "my_hash")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [field1]
func (*ClusterClient) HLen ¶
HLen returns the number of fields contained in the hash stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash.
Return value:
The number of fields in the hash, or `0` when key does not exist. If key holds a value that is not a hash, an error is returned.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
fields := map[string]string{
"field1": "someValue",
"field2": "someOtherValue",
}
result, err := client.HSet(context.Background(), "my_hash", fields)
result1, err := client.HLen(context.Background(), "my_hash")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 2 2
func (*ClusterClient) HMGet ¶
func (client *ClusterClient) HMGet(ctx context.Context, key string, fields []string) ([]models.Result[string], error)
HMGet returns the values associated with the specified fields in the hash stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. fields - The fields in the hash stored at key to retrieve from the database.
Return value:
An array of [models.Result[string]] 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 [models.CreateNilStringResult()] is returned. If key does not exist, returns an empty string array.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
fields := map[string]string{
"field1": "someValue",
"field2": "someOtherValue",
}
result, err := client.HSet(context.Background(), "my_hash", fields)
values, err := client.HMGet(context.Background(), "my_hash", []string{"field1", "field2"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(values[0])
fmt.Println(values[1])
Output: 2 {someValue false} {someOtherValue false}
func (*ClusterClient) HPExpire ¶ added in v2.1.0
func (client *ClusterClient) HPExpire( ctx context.Context, key string, expireTime time.Duration, fields []string, opts options.HExpireOptions, ) ([]int64, error)
Sets an expiration (TTL or time to live) on one or more fields of a given hash key. Field(s) will automatically be deleted from the hash key when their TTLs expire.
Since:
Valkey 9.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. expireTime - The expiration time as a duration. fields - The fields to set expiration for. options - Optional arguments for the command, see [options.HExpireOptions].
Return value:
An array of integers indicating the result for each field: - -2: Field does not exist in the hash, or hash is empty. - 0: The specified condition was not met. - 1: The expiration time was applied. - 2: When called with 0 milliseconds.
func (*ClusterClient) HPExpireAt ¶ added in v2.1.0
func (client *ClusterClient) HPExpireAt( ctx context.Context, key string, expireTime time.Time, fields []string, opts options.HExpireOptions, ) ([]int64, error)
Sets an expiration (TTL or time to live) on one or more fields of a given hash key using an absolute Unix timestamp. A timestamp in the past will delete the field immediately. Field(s) will automatically be deleted from the hash key when their TTLs expire.
Since:
Valkey 9.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. expireTime - The expiration time as a time.Time. fields - The fields to set expiration for. options - Optional arguments for the command, see [options.HExpireOptions].
Return value:
An array of integers indicating the result for each field: - -2: Field does not exist in the hash, or hash is empty. - 0: The specified condition was not met. - 1: The expiration time was applied. - 2: When called with 0 milliseconds or past Unix time.
func (*ClusterClient) HPExpireTime ¶ added in v2.1.0
func (client *ClusterClient) HPExpireTime(ctx context.Context, key string, fields []string) ([]int64, error)
Returns the absolute Unix timestamp in milliseconds since Unix epoch at which the given key's field(s) will expire.
Since:
Valkey 9.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. fields - The fields to get expiration time for.
Return value:
An array of integers indicating the expiration timestamp for each field in milliseconds: - Positive number: expiration timestamp. - -1: field exists but has no expiration. - -2: field doesn't exist.
func (*ClusterClient) HPTtl ¶ added in v2.1.0
func (client *ClusterClient) HPTtl(ctx context.Context, key string, fields []string) ([]int64, error)
Returns the remaining TTL (time to live) of a hash key's field(s) that have a set expiration, in milliseconds.
Since:
Valkey 9.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. fields - The fields to get TTL for.
Return value:
An array of integers indicating the TTL for each field in milliseconds: - Positive number: remaining TTL. - -1: field exists but has no expiration. - -2: field doesn't exist.
func (*ClusterClient) HPersist ¶ added in v2.1.0
func (client *ClusterClient) HPersist(ctx context.Context, key string, fields []string) ([]int64, error)
Removes the existing expiration on a hash key's field(s), turning the field(s) from volatile (a field with expiration set) to persistent (a field that will never expire as no TTL (time to live) is associated).
Since:
Valkey 9.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. fields - The fields to remove expiration from.
Return value:
An array of integers indicating the result for each field: - -2: Field does not exist in the hash, or hash does not exist. - -1: Field exists but has no expiration. - 1: The expiration was successfully removed from the field.
Example ¶
// This command requires Valkey 9.0+
var client *ClusterClient = getExampleClusterClient() // example helper function
// First set some fields with expiration
fields := map[string]string{
"field1": "value1",
"field2": "value2",
}
options := options.NewHSetExOptions().SetExpiry(options.NewExpiryIn(60 * time.Second))
client.HSetEx(context.Background(), "my_hash", fields, options)
// Remove expiration from fields
result, err := client.HPersist(context.Background(), "my_hash", []string{"field1", "field2"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result[0]) // 1 means expiration was removed
fmt.Println(result[1]) // 1 means expiration was removed
Output: 1 1
func (*ClusterClient) HRandField ¶
func (client *ClusterClient) HRandField(ctx context.Context, key string) (models.Result[string], error)
Returns a random field name from the hash value stored at `key`.
Since:
Valkey 6.2.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash.
Return value:
A random field name from the hash stored at `key`, or `nil` when the key does not exist.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
// For this example we only use 1 field to ensure consistent output
fields := map[string]string{
"field1": "someValue",
// other fields here...
}
client.HSet(context.Background(), "my_hash", fields)
result, err := client.HRandField(context.Background(), "my_hash")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: {field1 false}
func (*ClusterClient) HRandFieldWithCount ¶
func (client *ClusterClient) HRandFieldWithCount(ctx context.Context, key string, count int64) ([]string, error)
Retrieves up to `count` random field names from the hash value stored at `key`.
Since:
Valkey 6.2.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. count - The number of field names to return. If `count` is positive, returns unique elements. If negative, allows for duplicates.
Return value:
An array of random field names from the hash stored at `key`, or an empty array when the key does not exist.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
fields := map[string]string{
"field1": "someValue",
"field2": "someOtherValue",
}
client.HSet(context.Background(), "my_hash", fields)
result, err := client.HRandFieldWithCount(context.Background(), "my_hash", 2)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(len(result) == 2)
Output: true
func (*ClusterClient) HRandFieldWithCountWithValues ¶
func (client *ClusterClient) HRandFieldWithCountWithValues(ctx context.Context, key string, count int64) ([][]string, error)
Retrieves up to `count` random field names along with their values from the hash value stored at `key`.
Since:
Valkey 6.2.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. count - The number of field names to return. If `count` is positive, returns unique elements. If negative, allows for duplicates.
Return value:
A 2D `array` of `[field, value]` arrays, where `field` 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.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
fields := map[string]string{
"field1": "someValue",
"field2": "someOtherValue",
}
client.HSet(context.Background(), "my_hash", fields)
result, err := client.HRandFieldWithCountWithValues(context.Background(), "my_hash", 2)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(len(result) == 2)
Output: true
func (*ClusterClient) HScan ¶
func (client *ClusterClient) HScan(ctx context.Context, key string, cursor models.Cursor) (models.ScanResult, error)
Iterates fields of Hash types and their associated values. This definition of HSCAN command does not include the optional arguments of the command.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. cursor - The cursor that points to the next iteration of results.
Return value:
An object which holds the next cursor and the subset of the hash held by `key`. The cursor will return `false` from `IsFinished()` method on the last iteration of the subset. The data array in the result is always a flattened series of string pairs, where the hash field names are at even indices, and the hash field value are at odd indices.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
// For this example we only use 1 field to ensure a consistent output
fields := map[string]string{
"field1": "someValue",
// other fields here
}
client.HSet(context.Background(), "my_hash", fields)
result, err := client.HScan(context.Background(), "my_hash", models.NewCursor())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println("Cursor:", result.Cursor)
fmt.Println("Collection:", result.Data)
Output: Cursor: 0 Collection: [field1 someValue]
func (*ClusterClient) HScanWithOptions ¶
func (client *ClusterClient) HScanWithOptions( ctx context.Context, key string, cursor models.Cursor, options options.HashScanOptions, ) (models.ScanResult, error)
Iterates fields of Hash types and their associated values. This definition of HSCAN includes optional arguments of the command.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. cursor - The cursor that points to the next iteration of results. options - The [options.HashScanOptions].
Return value:
An object which holds the next cursor and the subset of the hash held by `key`. The cursor will return `false` from `IsFinished()` method on the last iteration of the subset. The data array in the result is always a flattened series of string pairs, where the hash field names are at even indices, and the hash field value are at odd indices.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
fields := map[string]string{
"a": "1",
"b": "2",
}
client.HSet(context.Background(), "my_hash", fields)
opts := options.NewHashScanOptions().SetMatch("a")
result, err := client.HScanWithOptions(context.Background(), "my_hash", models.NewCursor(), *opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println("Cursor:", result.Cursor)
fmt.Println("Collection:", result.Data)
// The collection only contains the hash map entry that matches with the match option provided with the command
Output: Cursor: 0 Collection: [a 1]
func (*ClusterClient) HSet ¶
func (client *ClusterClient) HSet(ctx context.Context, key string, values map[string]string) (int64, error)
HSet sets the specified fields to their respective values in the hash stored at key. This command overwrites the values of specified fields that exist in the hash. If key doesn't exist, a new key holding a hash is created.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. values - A map of field-value pairs to set in the hash.
Return value:
The number of fields that were added or updated.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
fields := map[string]string{
"field1": "someValue",
"field2": "someOtherValue",
}
result, err := client.HSet(context.Background(), "my_hash", fields)
result1, err := client.HGet(context.Background(), "my_hash", "field1")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 2 {someValue false}
func (*ClusterClient) HSetEx ¶ added in v2.1.0
func (client *ClusterClient) HSetEx( ctx context.Context, key string, fieldsAndValues map[string]string, opts options.HSetExOptions, ) (int64, error)
Sets the value of one or more fields of a given hash key, and optionally set their expiration time or time-to-live (TTL). This command overwrites the values and expirations of specified fields that exist in the hash. If `key` doesn't exist, a new key holding a hash is created.
Since:
Valkey 9.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. fieldsAndValues - A map of field-value pairs to set in the hash. options - Optional arguments for the command.
Return value:
- 1 if all fields were set successfully.
- 0 if no fields were set due to conditional restrictions.
Example ¶
// This command requires Valkey 9.0+
var client *ClusterClient = getExampleClusterClient() // example helper function
fields := map[string]string{
"field1": "value1",
"field2": "value2",
}
// Set fields with 10 second expiration
options := options.NewHSetExOptions().SetExpiry(options.NewExpiryIn(10 * time.Second))
result, err := client.HSetEx(context.Background(), "my_hash", fields, options)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 1
func (*ClusterClient) HSetNX ¶
func (client *ClusterClient) HSetNX(ctx context.Context, key string, field string, value string) (bool, error)
HSetNX 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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. field - The field to set. value - The value to set.
Return value:
A bool containing true if field is a new field in the hash and value was set. false if field already exists in the hash and no operation was performed.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
fields := map[string]string{
"field1": "someValue",
"field2": "someOtherValue",
}
result, err := client.HSet(context.Background(), "my_hash", fields)
result1, err := client.HSetNX(context.Background(), "my_hash", "field3", "value")
payload, err := client.HGet(context.Background(), "my_hash", "field3")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(payload)
Output: 2 true {value false}
func (*ClusterClient) HStrLen ¶
HStrLen returns the string length of the value associated with field in the hash stored at key. If the key or the field do not exist, 0 is returned.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. field - The field to get the string length of its value.
Return value:
The length of the string value associated with field, or `0` when field or key do not exist.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
fields := map[string]string{
"field1": "someValue",
"field2": "someOtherValue",
}
result, err := client.HSet(context.Background(), "my_hash", fields)
result1, err := client.HStrLen(context.Background(), "my_hash", "field1")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 2 9
func (*ClusterClient) HTtl ¶ added in v2.1.0
func (client *ClusterClient) HTtl(ctx context.Context, key string, fields []string) ([]int64, error)
Returns the remaining TTL (time to live) of a hash key's field(s) that have a set expiration.
Since:
Valkey 9.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash. fields - The fields to get TTL for.
Return value:
An array of integers indicating the TTL for each field in seconds: - Positive number: remaining TTL. - -1: field exists but has no expiration. - -2: field doesn't exist.
Example ¶
// This command requires Valkey 9.0+
var client *ClusterClient = getExampleClusterClient() // example helper function
// First set some fields with expiration
fields := map[string]string{
"field1": "value1",
"field2": "value2",
}
options := options.NewHSetExOptions().SetExpiry(options.NewExpiryIn(60 * time.Second))
client.HSetEx(context.Background(), "my_hash", fields, options)
// Get TTL for fields
result, err := client.HTtl(context.Background(), "my_hash", []string{"field1", "field2"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Printf("Field1 TTL > 0: %t\n", result[0] > 0)
fmt.Printf("Field2 TTL > 0: %t\n", result[1] > 0)
Output: Field1 TTL > 0: true Field2 TTL > 0: true
func (*ClusterClient) HVals ¶
HVals returns all values in the hash stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the hash.
Return value:
A slice containing all the values in the hash, or an empty slice when key does not exist.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
// For this example, we only use 1 field for consistent output
fields := map[string]string{
"field1": "someValue",
// other fields here
}
result, err := client.HSet(context.Background(), "my_hash", fields)
result1, err := client.HVals(context.Background(), "my_hash")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 1 [someValue]
func (*ClusterClient) Incr ¶
Increments the number stored at key by one. If key does not exist, it is set to 0 before performing the operation.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to increment its value.
Return value:
The value of `key` after the increment.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.Set(context.Background(), "my_key", "1")
result, err := client.Incr(context.Background(), "my_key")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 2
func (*ClusterClient) IncrBy ¶
Increments the number stored at key by amount. If key does not exist, it is set to 0 before performing the operation.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to increment its value. amount - The amount to increment.
Return value:
The value of `key` after the increment.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.Set(context.Background(), "my_key", "5")
result, err := client.IncrBy(context.Background(), "my_key", 5)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 10
func (*ClusterClient) IncrByFloat ¶
func (client *ClusterClient) IncrByFloat(ctx context.Context, key string, amount float64) (float64, error)
Increments 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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to increment its value. amount - The amount to increment.
Return value:
The value of key after the increment.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.Set(context.Background(), "my_key", "1")
result, err := client.IncrByFloat(context.Background(), "my_key", 5.5)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 6.5
func (*ClusterClient) Info ¶
Gets information and statistics about the server. The command will be routed to all primary nodes.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
A map where each address is the key and its corresponding node response is the information for the default sections.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
response, err := client.Info(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
for _, data := range response {
if strings.Contains(data, "cluster_enabled:1") {
fmt.Println("OK")
break
}
}
Output: OK
func (*ClusterClient) InfoWithOptions ¶
func (client *ClusterClient) InfoWithOptions( ctx context.Context, options options.ClusterInfoOptions, ) (models.ClusterValue[string], error)
Gets information and statistics about the server. The command will be routed to all primary nodes, unless `route` in options.ClusterInfoOptions is provided.
Note:
Starting from server version 7, command supports multiple section arguments.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. options - Additional command parameters, see [ClusterInfoOptions] for more details.
Return value:
When specifying a route other than a single node or when route is not given, it returns a map where each address is the key and its corresponding node response is the value. When a single node route is given, command returns a string containing the information for the sections requested.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
opts := options.ClusterInfoOptions{
InfoOptions: &options.InfoOptions{Sections: []constants.Section{constants.Cluster}},
}
response, err := client.InfoWithOptions(context.Background(), opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
for _, data := range response.MultiValue() {
if strings.Contains(data, "cluster_enabled:1") {
fmt.Println("OK")
break
}
}
Output: OK
func (*ClusterClient) InvokeScript ¶
Executes a Lua script on the server.
This function simplifies the process of invoking scripts on the server by using an object that represents a Lua script. The script loading 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.
See LOAD and EVALSHA for details.
Parameters:
ctx - The context for controlling the command execution. script - The Lua script to execute.
Return value:
The result of the script execution.
Example ¶
client := getExampleClusterClient()
// Create a simple Lua script that returns a number
script := options.NewScript("return 123")
// Execute the script
result, err := client.InvokeScript(context.Background(), *script)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
fmt.Println(result)
Output: 123
func (*ClusterClient) InvokeScriptWithClusterOptions ¶
func (client *ClusterClient) InvokeScriptWithClusterOptions( ctx context.Context, script options.Script, clusterScriptOptions options.ClusterScriptOptions, ) (models.ClusterValue[any], error)
Executes a Lua script on the server with cluster script options.
This function simplifies the process of invoking scripts on the 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.
Note:
- all `keys` in `clusterScriptOptions` must map to the same hash slot.
- the command will be routed based on the Route specified in clusterScriptOptions.
See LOAD and EVALSHA for details.
Parameters:
ctx - The context for controlling the command execution. script - The script to execute. clusterScriptOptions - Combined options for script execution including keys, arguments, and routing information.
Return value:
The result of the script execution.
Example ¶
client := getExampleClusterClient()
// Create a Lua script.
scriptText := "return 'Hello'"
script := options.NewScript(scriptText)
// Set up cluster script options
clusterScriptOptions := options.NewClusterScriptOptions()
// Set the route
clusterScriptOptions.Route = config.AllPrimaries
// Execute the script with cluster options
result, err := client.InvokeScriptWithClusterOptions(context.Background(), *script, *clusterScriptOptions)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
// Print the result. The result contains response from multiple nodes.
// We are checking and printing the response from only one node below.
for _, value := range result.MultiValue() {
if value != nil && value.(string) == "Hello" {
fmt.Println(value)
break
}
}
Output: Hello
func (*ClusterClient) InvokeScriptWithOptions ¶
func (client *ClusterClient) InvokeScriptWithOptions( ctx context.Context, script options.Script, scriptOptions options.ScriptOptions, ) (any, error)
Executes a Lua script on the server with additional options.
This function simplifies the process of invoking scripts on the 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.
Note:
When in cluster mode: - all `keys` in `scriptOptions` must map to the same hash slot. - if no `keys` are given, command will be routed to a random primary node.
See LOAD and EVALSHA for details.
Parameters:
ctx - The context for controlling the command execution. script - The Lua script to execute. scriptOptions - Options for script execution including keys and arguments.
Return value:
The result of the script execution.
Example ¶
client := getExampleClusterClient()
// Create a Lua script that performs calculations with arguments
scriptText := `
local a = tonumber(ARGV[1])
local b = tonumber(ARGV[2])
return a + b
`
script := options.NewScript(scriptText)
// Set up script options with arguments
scriptOptions := options.NewScriptOptions().
WithArgs([]string{"10", "20"})
// Execute the script with options
result, err := client.InvokeScriptWithOptions(context.Background(), *script, *scriptOptions)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
fmt.Println(result)
Output: 30
func (*ClusterClient) InvokeScriptWithRoute ¶
func (client *ClusterClient) InvokeScriptWithRoute( ctx context.Context, script options.Script, route options.RouteOption, ) (models.ClusterValue[any], error)
Executes a Lua script on the server with routing information.
This function simplifies the process of invoking scripts on the server by using an object that represents a Lua script. The script loading 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.
Note:
The command will be routed to a random node, unless `route` is provided.
See LOAD and EVALSHA for details.
Parameters:
ctx - The context for controlling the command execution. script - The Lua script to execute. route - Routing information for the script execution.
Return value:
The result of the script execution.
func (*ClusterClient) LCS ¶
func (client *ClusterClient) LCS(ctx context.Context, key1 string, key2 string) (*models.LCSMatch, error)
Returns the longest common subsequence between strings stored at `key1` and `key2`.
Since:
Valkey 7.0 and above.
Note:
When in cluster mode, `key1` and `key2` must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key1 - The key that stores the first string. key2 - The key that stores the second string.
Return value:
A [models.LCSMatch] object containing: - `MatchString`: A string containing all the longest common subsequences combined between the 2 strings. An empty string is returned if the keys do not exist or have no common subsequences. - `Matches`: Empty array. - `Len`: 0
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.MSet(context.Background(), map[string]string{"{my_key}1": "oh my gosh", "{my_key}2": "hello world"})
result, err := client.LCS(context.Background(), "{my_key}1", "{my_key}2")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.MatchString)
// LCS is only available in 7.0 and above. It will fail in any release < 7.0
Output: h o
func (*ClusterClient) LCSLen ¶
func (client *ClusterClient) LCSLen(ctx context.Context, key1, key2 string) (*models.LCSMatch, error)
Returns the total length of all the longest common subsequences between strings stored at `key1` and `key2`.
Since:
Valkey 7.0 and above.
Note:
When in cluster mode, `key1` and `key2` must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key1 - The key that stores the first string. key2 - The key that stores the second string.
Return value:
A [models.LCSMatch] object containing: - `MatchString`: Empty string. - `Matches`: Empty array. - `Len`: The total length of all the longest common subsequences the 2 strings.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.Set(context.Background(), "{my_key}1", "ohmytext")
client.Set(context.Background(), "{my_key}2", "mynewtext")
result, err := client.LCSLen(context.Background(), "{my_key}1", "{my_key}2")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.Len)
// LCS is only available in 7.0 and above. It will fail in any release < 7.0
Output: 6
func (*ClusterClient) LCSWithOptions ¶
func (client *ClusterClient) LCSWithOptions( ctx context.Context, key1, key2 string, opts options.LCSIdxOptions, ) (*models.LCSMatch, error)
Returns the longest common subsequence between strings stored at `key1` and `key2`.
Since:
Valkey 7.0 and above.
Note:
When in cluster mode, `key1` and `key2` must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key1 - The key that stores the first string. key2 - The key that stores the second string. opts - The [LCSIdxOptions] type.
Return value:
A [models.LCSMatch] object containing: - `MatchString`: Empty string. - `Matches`: Array of [models.LCSMatchedPosition] objects with the common subsequences in the strings held by key1 and key2. If WithMatchLen is specified, the array also contains the length of each match, otherwise the length is 0. - `Len`: The total length of all the longest common subsequences the 2 strings.
Example (Basic) ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.Set(context.Background(), "{key}1", "ohmytext")
client.Set(context.Background(), "{key}2", "mynewtext")
// Basic LCS IDX without additional options
opts := options.NewLCSIdxOptions()
result, err := client.LCSWithOptions(context.Background(), "{key}1", "{key}2", *opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
jsonRes, _ := json.MarshalIndent(result, "", " ")
fmt.Println("Basic LCS result:\n", string(jsonRes))
// LCS is only available in 7.0 and above. It will fail in any server < 7.0
Output: Basic LCS result: { "MatchString": "", "Matches": [ { "Key1": { "Start": 4, "End": 7 }, "Key2": { "Start": 5, "End": 8 }, "MatchLen": 0 }, { "Key1": { "Start": 2, "End": 3 }, "Key2": { "Start": 0, "End": 1 }, "MatchLen": 0 } ], "Len": 6 }
Example (Minmatchlen) ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.Set(context.Background(), "{key}1", "ohmytext")
client.Set(context.Background(), "{key}2", "mynewtext")
// LCS IDX with MINMATCHLEN = 4
optsWithMin := options.NewLCSIdxOptions()
optsWithMin.SetMinMatchLen(4)
result2, err := client.LCSWithOptions(context.Background(), "{key}1", "{key}2", *optsWithMin)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
jsonRes2, _ := json.MarshalIndent(result2, "", " ")
fmt.Println("With MinMatchLen 4:\n", string(jsonRes2))
// LCS is only available in 7.0 and above. It will fail in any server < 7.0
Output: With MinMatchLen 4: { "MatchString": "", "Matches": [ { "Key1": { "Start": 4, "End": 7 }, "Key2": { "Start": 5, "End": 8 }, "MatchLen": 0 } ], "Len": 6 }
func (*ClusterClient) LIndex ¶
func (client *ClusterClient) LIndex(ctx context.Context, key string, index int64) (models.Result[string], error)
Returns the element at index from 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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list. index - The index of the element in the list to retrieve.
Return value:
The models.Result[string] containing element at index in the list stored at key. If index is out of range or if key does not exist, [models.CreateNilStringResult()] is returned.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.RPush(context.Background(), "my_list", []string{"a", "b", "c", "d", "e", "e", "e"})
result1, err := client.LIndex(context.Background(), "my_list", 3)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 7 {d false}
func (*ClusterClient) LInsert ¶
func (client *ClusterClient) LInsert( ctx context.Context, key string, insertPosition constants.InsertPosition, pivot string, element string, ) (int64, error)
Inserts element in the list at key either before or after the pivot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list. insertPosition - The relative position to insert into - either constants.Before or constants.After the pivot. pivot - An element of the list. element - The new element to insert.
Return value:
The list length after a successful insert operation. If the `key` doesn't exist returns `-1`. If the `pivot` wasn't found, returns `0`.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.Del(context.Background(), []string{"my_list"})
result, err := client.RPush(context.Background(), "my_list", []string{"hello", "world"})
result1, err := client.LInsert(context.Background(), "my_list", constants.Before, "world", "there")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 2 3
func (*ClusterClient) LLen ¶
Returns the length of the list stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list.
Return value:
The length of the list at `key`. If `key` does not exist, it is interpreted as an empty list and `0` is returned.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.RPush(context.Background(), "my_list", []string{"a", "b", "c", "d", "e", "e", "e"})
result1, err := client.LLen(context.Background(), "my_list")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 7 7
func (*ClusterClient) LMPop ¶
func (client *ClusterClient) LMPop( ctx context.Context, keys []string, listDirection constants.ListDirection, ) ([]models.KeyValues, error)
Pops one element from the first non-empty list from the provided keys.
Note:
When in cluster mode, `keys` must map to the same hash slot.
Since:
Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - An array of keys to lists. listDirection - The direction based on which elements are popped from - see [options.ListDirection].
Return value:
A slice of [models.KeyValues], each containing a key name and an array of popped elements. If no elements could be popped, returns 'nil'.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.LPush(context.Background(), "my_list", []string{"one", "two", "three"})
result1, err := client.LMPop(context.Background(), []string{"my_list"}, constants.Left)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
jsonResult1, err := json.Marshal(result1)
fmt.Println(string(jsonResult1))
Output: 3 [{"Key":"my_list","Values":["three"]}]
func (*ClusterClient) LMPopCount ¶
func (client *ClusterClient) LMPopCount( ctx context.Context, keys []string, listDirection constants.ListDirection, count int64, ) ([]models.KeyValues, error)
Pops one or more elements from the first non-empty list from the provided keys.
Note:
When in cluster mode, `keys` must map to the same hash slot.
Since:
Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - An array of keys to lists. listDirection - The direction based on which elements are popped from - see [options.ListDirection]. count - The maximum number of popped elements.
Return value:
A slice of [models.KeyValues], each containing a key name and an array of popped elements. If no elements could be popped, returns 'nil'.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.LPush(context.Background(), "my_list", []string{"one", "two", "three"})
result1, err := client.LMPopCount(context.Background(), []string{"my_list"}, constants.Left, 2)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
jsonResult1, err := json.Marshal(result1)
fmt.Println(string(jsonResult1))
Output: 3 [{"Key":"my_list","Values":["three","two"]}]
func (*ClusterClient) LMove ¶
func (client *ClusterClient) LMove( ctx context.Context, source string, destination string, whereFrom constants.ListDirection, whereTo constants.ListDirection, ) (models.Result[string], error)
Atomically pops 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`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. source - The key to the source list. destination - The key to the destination list. wherefrom - The ListDirection the element should be removed from. whereto - The ListDirection the element should be added to.
Return value:
A models.Result[string] containing the popped element or models.CreateNilStringResult() if source does not exist.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.LPush(context.Background(), "{list}-1", []string{"two", "one"})
result1, err := client.LPush(context.Background(), "{list}-2", []string{"four", "three"})
result2, err := client.LMove(context.Background(), "{list}-1", "{list}-2", constants.Left, constants.Left)
result3, err := client.LRange(context.Background(), "{list}-1", 0, -1)
result4, err := client.LRange(context.Background(), "{list}-2", 0, -1)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
Output: 2 2 {one false} [two] [one three four]
func (*ClusterClient) LPop ¶
Removes and returns the first elements of the list stored at key. The command pops a single element from the beginning of the list.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list.
Return value:
The models.Result[string] containing the value of the first element. If key does not exist, [models.CreateNilStringResult()] will be returned.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.LPush(context.Background(), "my_list", []string{"value1", "value2"})
result1, err := client.LPop(context.Background(), "my_list")
result2, err := client.LPop(context.Background(), "non_existent")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2.IsNil())
Output: 2 {value2 false} true
func (*ClusterClient) LPopCount ¶
func (client *ClusterClient) LPopCount(ctx context.Context, key string, count int64) ([]string, error)
Removes and returns up to `count` elements of the list stored at key, depending on the list's length.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list. count - The count of the elements to pop from the list.
Return value:
An array of the popped elements as strings will be returned depending on the list's length If key does not exist, nil will be returned.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.LPush(context.Background(), "my_list", []string{"value1", "value2"})
result1, err := client.LPopCount(context.Background(), "my_list", 2)
result2, err := client.LPop(context.Background(), "non_existent")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2.IsNil())
Output: 2 [value2 value1] true
func (*ClusterClient) LPos ¶
func (client *ClusterClient) LPos(ctx context.Context, key string, element string) (models.Result[int64], error)
Returns the index of the first occurrence of element inside the list specified by key. If no match is found, [models.CreateNilInt64Result()] is returned.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The name of the list. element - The value to search for within the list.
Return value:
The models.Result[int64] containing the index of the first occurrence of element, or [models.CreateNilInt64Result()] if element is not in the list.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.RPush(context.Background(), "my_list", []string{"a", "b", "c", "d", "e", "e"})
result1, err := client.LPos(context.Background(), "my_list", "e")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 6 {4 false}
func (*ClusterClient) LPosCount ¶
func (client *ClusterClient) LPosCount(ctx context.Context, key string, element string, count int64) ([]int64, error)
Returns an array of indices of matching elements within a list.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The name of the list. element - The value to search for within the list. count - The number of matches wanted.
Return value:
An array that holds the indices of the matching elements within the list.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.RPush(context.Background(), "my_list", []string{"a", "b", "c", "d", "e", "e", "e"})
result1, err := client.LPosCount(context.Background(), "my_list", "e", 3)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 7 [4 5 6]
func (*ClusterClient) LPosCountWithOptions ¶
func (client *ClusterClient) LPosCountWithOptions( ctx context.Context, key string, element string, count int64, opts options.LPosOptions, ) ([]int64, error)
Returns an array of indices of matching elements within a list based on the given options. If no match is found, an empty array is returned.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The name of the list. element - The value to search for within the list. count - The number of matches wanted. opts - The LPos options.
Return value:
An array that holds the indices of the matching elements within the list.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.RPush(context.Background(), "my_list", []string{"a", "b", "c", "d", "e", "e", "e"})
result1, err := client.LPosCountWithOptions(context.Background(), "my_list", "e", 1, *options.NewLPosOptions().SetRank(2))
result2, err := client.LPosCountWithOptions(context.Background(), "my_list", "e", 3,
*options.NewLPosOptions().SetRank(2).SetMaxLen(1000))
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: 7 [5] [5 6]
func (*ClusterClient) LPosWithOptions ¶
func (client *ClusterClient) LPosWithOptions( ctx context.Context, key string, element string, options options.LPosOptions, ) (models.Result[int64], error)
Returns the index of an occurrence of element within a list based on the given options. If no match is found, [models.CreateNilInt64Result()] is returned.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The name of the list. element - The value to search for within the list. options - The LPos options.
Return value:
The models.Result[int64] containing the index of element, or [models.CreateNilInt64Result()] if element is not in the list.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.RPush(context.Background(), "my_list", []string{"a", "b", "c", "d", "e", "e"})
result1, err := client.LPosWithOptions(context.Background(),
"my_list",
"e",
*options.NewLPosOptions().SetRank(2),
) // (Returns the second occurrence of the element "e")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 6 {5 false}
func (*ClusterClient) LPush ¶
func (client *ClusterClient) LPush(ctx context.Context, key string, elements []string) (int64, error)
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 an empty list before performing the push operation.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list. elements - The elements to insert at the head of the list stored at key.
Return value:
The length of the list after the push operation.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.LPush(context.Background(), "my_list", []string{"value1", "value2"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 2
func (*ClusterClient) LPushX ¶
func (client *ClusterClient) LPushX(ctx context.Context, key string, elements []string) (int64, error)
Inserts all the specified values at the head of the list stored at key, only if key exists and holds a list. If key is not a list, this performs no operation.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list. elements - The elements to insert at the head of the list stored at key.
Return value:
The length of the list after the push operation.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.RPush(context.Background(), "my_list", []string{"value1"})
result1, err := client.LPushX(context.Background(), "my_list", []string{"value2", "value3"})
result2, err := client.LRange(context.Background(), "my_list", 0, -1)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: 1 3 [value3 value2 value1]
func (*ClusterClient) LRange ¶
func (client *ClusterClient) LRange(ctx context.Context, key string, start int64, end int64) ([]string, error)
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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list. start - The starting point of the range. end - The end of the range.
Return value:
Array of strings in the specified range. If start exceeds the end of the list, or if start is greater than end, an empty array 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 array will be returned.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.RPush(context.Background(), "my_list", []string{"a", "b", "c", "d", "e", "e", "e"})
result1, err := client.LRange(context.Background(), "my_list", 0, 2)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 7 [a b c]
func (*ClusterClient) LRem ¶
func (client *ClusterClient) LRem(ctx context.Context, key string, count int64, element string) (int64, error)
Removes the first count occurrences of elements equal to element from the list stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list. count - 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, it removes all elements equal to element. element - The element to remove from the list.
Return value:
The number of the removed elements. If `key` does not exist, `0` is returned.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.RPush(context.Background(), "my_list", []string{"a", "b", "c", "d", "e", "e", "e"})
result1, err := client.LRem(context.Background(), "my_list", 2, "e")
result2, err := client.LRange(context.Background(), "my_list", 0, -1)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: 7 2 [a b c d e]
func (*ClusterClient) LSet ¶
func (client *ClusterClient) LSet(ctx context.Context, key string, index int64, element string) (string, error)
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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list. index - The index of the element in the list to be set. element - The element to be set.
Return value:
`"OK"`.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.LPush(context.Background(), "my_list", []string{"one", "two", "three"})
result1, err := client.LSet(context.Background(), "my_list", 1, "someOtherValue")
result2, err := client.LRange(context.Background(), "my_list", 0, -1)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: 3 OK [three someOtherValue one]
func (*ClusterClient) LTrim ¶
func (client *ClusterClient) LTrim(ctx context.Context, key string, start int64, end int64) (string, error)
Trims 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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list. start - The starting point of the range. end - The end of the range.
Return value:
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, `"OK"` will be returned without changes to the database.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.RPush(context.Background(), "my_list", []string{"a", "b", "c", "d", "e", "e", "e"})
result1, err := client.LTrim(context.Background(), "my_list", 0, 4)
result2, err := client.LRange(context.Background(), "my_list", 0, -1)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: 7 OK [a b c d e]
func (*ClusterClient) LastSave ¶
func (client *ClusterClient) LastSave(ctx context.Context) (models.ClusterValue[int64], error)
Returns UNIX TIME of the last DB save timestamp or startup timestamp if no save was made since then. The command is routed to a random node by default, which is safe for read-only commands.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
UNIX TIME of the last DB save executed with success.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "key-" + uuid.NewString()
client.Set(context.Background(), key, "hello")
result, err := client.LastSave(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.IsSingleValue())
Output: true
func (*ClusterClient) LastSaveWithOptions ¶
func (client *ClusterClient) LastSaveWithOptions( ctx context.Context, opts options.RouteOption, ) (models.ClusterValue[int64], error)
Returns UNIX TIME of the last DB save timestamp or startup timestamp if no save was made since then.
Parameters:
ctx - The context for controlling the command execution.
route - Specifies the routing configuration for the command. The client will route the
command to the nodes defined by route.
Return value:
UNIX TIME of the last DB save executed with success.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
opts := options.RouteOption{Route: nil}
key := "key-" + uuid.NewString()
client.Set(context.Background(), key, "hello")
result, err := client.LastSaveWithOptions(context.Background(), opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.IsSingleValue())
Output: true
func (*ClusterClient) Lolwut ¶
func (client *ClusterClient) Lolwut(ctx context.Context) (string, error)
Displays a piece of generative computer art of the specific Valkey version and it's optional arguments.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
A piece of generative computer art of that specific valkey version along with the Valkey version.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.Lolwut(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error:", err)
} else {
if len(result) > 0 {
fmt.Println("LOLWUT pattern generated successfully")
}
}
Output: LOLWUT pattern generated successfully
func (*ClusterClient) LolwutWithOptions ¶
func (client *ClusterClient) LolwutWithOptions( ctx context.Context, lolwutOptions options.ClusterLolwutOptions, ) (models.ClusterValue[string], error)
Displays a piece of generative computer art of the specific Valkey version and it's optional arguments.
Parameters:
ctx - The context for controlling the command execution. lolwutOptions - The [LolwutOptions] type.
Return value:
A piece of generative computer art of that specific valkey version along with the Valkey version.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
randomRouteOptions := options.ClusterLolwutOptions{
LolwutOptions: &options.LolwutOptions{
Version: 6,
Args: []int{10, 20},
},
RouteOption: &options.RouteOption{
Route: config.RandomRoute,
},
}
result, err := client.LolwutWithOptions(context.Background(), randomRouteOptions)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
if len(result.SingleValue()) > 0 {
fmt.Println("LOLWUT pattern generated successfully")
}
Output: LOLWUT pattern generated successfully
func (*ClusterClient) MGet ¶
func (client *ClusterClient) MGet(ctx context.Context, keys []string) ([]models.Result[string], error)
Retrieves the values of multiple keys.
Note:
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.
Parameters:
ctx - The context for controlling the command execution. keys - A list of keys to retrieve values for.
Return value:
An array of [models.Result[string]] values corresponding to the provided keys. If a key is not found, its corresponding value in the list will be a [models.CreateNilStringResult()].
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.MSet(
context.Background(),
map[string]string{"my_key1": "my_value1", "my_key2": "my_value2", "my_key3": "my_value3"},
)
keys := []string{"my_key1", "my_key2", "my_key3"}
result, err := client.MGet(context.Background(), keys)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
for _, res := range result {
fmt.Println(res.Value())
}
Output: my_value1 my_value2 my_value3
func (*ClusterClient) MSet ¶
func (client *ClusterClient) MSet(ctx context.Context, keyValueMap map[string]string) (string, error)
Sets multiple keys to multiple values in a single operation.
Note:
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.
Parameters:
ctx - The context for controlling the command execution. keyValueMap - A key-value map consisting of keys and their respective values to set.
Return value:
`"OK"` on success.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
keyValueMap := map[string]string{
"key1": "value1",
"key2": "value2",
}
result, err := client.MSet(context.Background(), keyValueMap)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*ClusterClient) MSetNX ¶
func (client *ClusterClient) MSetNX(ctx context.Context, keyValueMap map[string]string) (bool, error)
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.
Note:
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.
Parameters:
ctx - The context for controlling the command execution. keyValueMap - A key-value map consisting of keys and their respective values to set.
Return value:
A bool containing true, if all keys were set. false, if no key was set.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
keyValueMap := map[string]string{"{my_key}1": "my_value1", "{my_key}2": "my_value2"}
result, err := client.MSetNX(context.Background(), keyValueMap)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
client.Set(context.Background(), "{my_key}3", "my_value3")
result, _ = client.MSetNX(context.Background(), map[string]string{"{my_key}3": "my_value3"})
fmt.Println(result)
Output: true false
func (*ClusterClient) Move ¶ added in v2.1.1
Move key from the currently selected database to the database specified by `dbIndex`.
Note:
In cluster mode move is available since Valkey 9.0.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to move. dbIndex - The index of the database to move key to.
Return value:
`true` if `key` was moved, or `false` if the `key` already exists in the destination database or does not exist in the source database.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := uuid.New().String()
_, err := client.Set(context.Background(), key, "hello")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
result, err := client.Move(context.Background(), key, 2)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: true
func (*ClusterClient) ObjectEncoding ¶
func (client *ClusterClient) ObjectEncoding(ctx context.Context, key string) (models.Result[string], error)
Returns the internal encoding for the Valkey object stored at key.
Parameters:
ctx - The context for controlling the command execution. key - The key of the object to get the internal encoding of.
Return value:
If key exists, returns the internal encoding of the object stored at key as a String. Otherwise, returns `null`.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.Set(context.Background(), "key1", "someValue")
result1, err := client.ObjectEncoding(context.Background(), "key1")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK {embstr false}
func (*ClusterClient) ObjectFreq ¶
func (client *ClusterClient) ObjectFreq(ctx context.Context, key string) (models.Result[int64], error)
Returns the logarithmic access frequency counter of a Valkey object stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the object to get the logarithmic access frequency counter of.
Return value:
If key exists, returns the logarithmic access frequency counter of the object stored at key as a long. Otherwise, returns `nil`.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
// TODO: Once ConfigSet and ConfigGet are implemented, replace CustomCommand
client.CustomCommand(context.Background(), []string{"CONFIG", "SET", "maxmemory-policy", "allkeys-lfu"})
result, err := client.Set(context.Background(), "key1", "someValue")
_, err = client.Set(context.Background(), "key1", "someOtherValue")
result1, err := client.ObjectFreq(context.Background(), "key1")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK {6 false}
func (*ClusterClient) ObjectIdleTime ¶
func (client *ClusterClient) ObjectIdleTime(ctx context.Context, key string) (models.Result[int64], error)
Returns the logarithmic access frequency counter of a Valkey object stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the object to get the logarithmic access frequency counter of.
Return value:
If key exists, returns the idle time in seconds. Otherwise, returns `nil`.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
// TODO: Once ConfigSet and ConfigGet are implemented, replace CustomCommand
client.CustomCommand(context.Background(), []string{"CONFIG", "SET", "maxmemory-policy", "allkeys-lru"})
result, err := client.Set(context.Background(), "key1", "someValue")
result1, err := client.ObjectIdleTime(context.Background(), "key1")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK {0 false}
func (*ClusterClient) ObjectRefCount ¶
func (client *ClusterClient) ObjectRefCount(ctx context.Context, key string) (models.Result[int64], error)
Returns the reference count of the object stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the object to get the reference count of.
Return value:
If key exists, returns the reference count of the object stored at key. Otherwise, returns `nil`.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.CustomCommand(context.Background(), []string{"CONFIG", "SET", "maxmemory-policy", "allkeys-lru"})
result, err := client.Set(context.Background(), "key1", "someValue")
result1, err := client.ObjectRefCount(context.Background(), "key1")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK {1 false}
func (*ClusterClient) PExpire ¶
func (client *ClusterClient) PExpire(ctx context.Context, key string, expireTime time.Duration) (bool, error)
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 expireTime is a 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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to set timeout on it. expireTime - Duration for the key to expire.
Return value:
`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 ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.Set(context.Background(), "key", "someValue")
result1, err := client.PExpire(context.Background(), "key", 5000*time.Millisecond)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK true
func (*ClusterClient) PExpireAt ¶
func (client *ClusterClient) PExpireAt(ctx context.Context, key string, expireTime time.Time) (bool, error)
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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to set timeout on it. expireTime - The timestamp for expiry.
Return value:
`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 ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.Set(context.Background(), "key", "someValue")
result1, err := client.PExpireAt(context.Background(), "key", time.Now().Add(10000*time.Millisecond))
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK true
func (*ClusterClient) PExpireAtWithOptions ¶
func (client *ClusterClient) PExpireAtWithOptions( ctx context.Context, key string, expireTime time.Time, expireCondition constants.ExpireCondition, ) (bool, error)
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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to set timeout on it. expireTime - The timestamp for expiry. expireCondition - The option to set expiry, see [options.ExpireCondition].
Return value:
`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 ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.Set(context.Background(), "key", "someValue")
result1, err := client.PExpireAtWithOptions(
context.Background(),
"key",
time.Now().Add(10000*time.Millisecond),
constants.HasNoExpiry,
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK true
func (*ClusterClient) PExpireTime ¶
PExpire Time returns the absolute Unix timestamp (since January 1, 1970) at which the given key will expire, in milliseconds.
Parameters:
ctx - The context for controlling the command execution. key - The key to determine the expiration value of.
Return value:
The expiration Unix timestamp in milliseconds. `-2` if key does not exist or `-1` is key exists but has no associated expiration.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.Set(context.Background(), "key", "someValue")
result1, err := client.PExpireTime(context.Background(), "key")
_, err = client.PExpireAt(
context.Background(),
"key",
time.Now().Add(10000*time.Millisecond),
) // PExpireTime("key") returns proper unix time in milliseconds
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK -1
func (*ClusterClient) PExpireWithOptions ¶
func (client *ClusterClient) PExpireWithOptions( ctx context.Context, key string, expireTime time.Duration, expireCondition constants.ExpireCondition, ) (bool, error)
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 expireTime is a 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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to set timeout on it. expireTime - Duration for the key to expire option - The option to set expiry, see [options.ExpireCondition].
Return value:
`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 ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.Set(context.Background(), "key", "someValue")
result1, err := client.PExpireWithOptions(context.Background(), "key", 5000*time.Millisecond, constants.HasNoExpiry)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK true
func (*ClusterClient) PSubscribe ¶ added in v2.3.0
func (client *ClusterClient) PSubscribe(ctx context.Context, patterns []string, timeoutMs int) error
PSubscribe subscribes the client to the specified patterns (blocking). This command updates the client's internal desired subscription state and waits for server confirmation.
Parameters:
ctx - The context for the operation.
patterns - A slice of patterns to subscribe to (e.g., []string{"news.*"}).
timeoutMs - Maximum time in milliseconds to wait for server confirmation.
A value of 0 blocks indefinitely until confirmation.
Return value:
An error if the operation fails or times out.
Example:
err := client.PSubscribe(ctx, []string{"news.*"}, 5000)
func (*ClusterClient) PSubscribeBlocking ¶ added in v2.3.0
func (client *ClusterClient) PSubscribeBlocking(ctx context.Context, patterns []string, timeoutMs int) error
PSubscribeBlocking subscribes the client to the specified patterns (blocking). This command updates the client's internal desired subscription state and waits for server confirmation.
Parameters:
ctx - The context for the operation.
patterns - A slice of patterns to subscribe to.
timeoutMs - Maximum time in milliseconds to wait for server confirmation.
A value of 0 blocks indefinitely until confirmation.
Return value:
An error if the operation fails or times out.
Example:
err := client.PSubscribeBlocking(ctx, []string{"news.*"}, 5000)
func (*ClusterClient) PSubscribeLazy ¶ added in v2.3.0
PSubscribeLazy subscribes the client to the specified patterns (non-blocking). This command updates the client's internal desired subscription state without waiting for server confirmation. It returns immediately after updating the local state.
Parameters:
ctx - The context for the operation.
patterns - A slice of patterns to subscribe to (e.g., []string{"news.*"}).
Return value:
An error if the operation fails.
Example:
err := client.PSubscribeLazy(ctx, []string{"news.*", "updates.*"})
PSubscribeLazy subscribes the client to the specified patterns (non-blocking). This command updates the client's internal desired subscription state without waiting for server confirmation. It returns immediately after updating the local state. The client will attempt to subscribe asynchronously in the background.
Note: Use GetSubscriptions() to verify the actual server-side subscription state.
Parameters:
ctx - The context for the operation.
patterns - A slice of patterns to subscribe to (e.g., []string{"news.*"}).
Return value:
An error if the operation fails.
Example:
err := client.PSubscribeLazy(ctx, []string{"news.*", "updates.*"})
func (*ClusterClient) PTTL ¶
PTTL returns the remaining time to live of key that has a timeout, in milliseconds.
Parameters:
ctx - The context for controlling the command execution. key - The key to return its timeout.
Return value:
Returns TTL in milliseconds, `-2` if key does not exist, or `-1` if key exists but has no associated expiration.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.Set(context.Background(), "key", "someValue")
result1, err := client.PTTL(context.Background(), "key")
_, err = client.PExpireAt(
context.Background(),
"key",
time.Now().Add(10000*time.Millisecond),
) // PTTL("key") returns proper TTL in milliseconds
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK -1
func (*ClusterClient) PUnsubscribe ¶ added in v2.3.0
func (client *ClusterClient) PUnsubscribe(ctx context.Context, patterns []string, timeoutMs int) error
PUnsubscribe unsubscribes the client from the specified patterns (blocking). This command updates the client's internal desired subscription state and waits for server confirmation. If no patterns are specified (nil or empty slice), unsubscribes from all patterns.
Parameters:
ctx - The context for the operation.
patterns - A slice of patterns to unsubscribe from. Pass nil to unsubscribe from all.
timeoutMs - Maximum time in milliseconds to wait for server confirmation.
A value of 0 blocks indefinitely until confirmation.
Return value:
An error if the operation fails or times out.
Example:
err := client.PUnsubscribe(ctx, []string{"news.*"}, 5000)
err := client.PUnsubscribe(ctx, nil, 5000) // Unsubscribe from all
func (*ClusterClient) PUnsubscribeLazy ¶ added in v2.3.0
PUnsubscribeLazy unsubscribes the client from the specified patterns (non-blocking). This command updates the client's internal desired subscription state without waiting for server confirmation. It returns immediately after updating the local state. If no patterns are specified (nil), unsubscribes from all patterns.
Parameters:
ctx - The context for the operation. patterns - A slice of patterns to unsubscribe from. Pass nil to unsubscribe from all.
Return value:
An error if the operation fails.
Example:
err := client.PUnsubscribeLazy(ctx, []string{"news.*"})
err := client.PUnsubscribeLazy(ctx, nil) // Unsubscribe from all
func (*ClusterClient) Persist ¶
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:
ctx - The context for controlling the command execution. key - The key to remove the existing timeout on.
Return value:
`false` if key does not exist or does not have an associated timeout, `true` if the timeout has been removed.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.Set(context.Background(), "key1", "someValue")
result1, err := client.ExpireAt(context.Background(), "key1", time.Now().Add(10*time.Second))
result2, err := client.Persist(context.Background(), "key1")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: OK true true
func (*ClusterClient) PfAdd ¶
func (client *ClusterClient) PfAdd(ctx context.Context, key string, elements []string) (bool, error)
PfAdd 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. If key does not exist, then the HyperLogLog structure is created.
Parameters:
ctx - The context for controlling the command execution. key - The key of the HyperLogLog data structure to add elements into. elements - An array of members to add to the HyperLogLog stored at key.
Return value:
If the HyperLogLog is newly created, or if the HyperLogLog approximated cardinality is altered, then returns `true`. Otherwise, returns `false`.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.PfAdd(context.Background(), uuid.New().String(), []string{"value1", "value2", "value3"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: true
func (*ClusterClient) PfCount ¶
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.
Note:
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.
Parameters:
ctx - The context for controlling the command execution. key - The keys of the HyperLogLog data structures to be analyzed.
Return value:
The approximated cardinality of given HyperLogLog data structures. The cardinality of a key that does not exist is `0`.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := uuid.New().String()
result, err := client.PfAdd(context.Background(), key, []string{"value1", "value2", "value3"})
result1, err := client.PfCount(context.Background(), []string{key})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: true 3
func (*ClusterClient) PfMerge ¶
func (client *ClusterClient) PfMerge(ctx context.Context, destination string, sourceKeys []string) (string, error)
PfMerge 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.
Note:
When in cluster mode, `sourceKeys` and `destination` must map to the same hash slot.
Parameters:
ctx - The context for controlling the command execution. destination - The key of the destination HyperLogLog where the merged data sets will be stored. sourceKeys - An array of sourceKeys of the HyperLogLog structures to be merged.
Return value:
If the HyperLogLog values is successfully merged it returns "OK".
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
// Create source keys with some values
sourceKey1 := uuid.New().String() + "{group}"
sourceKey2 := uuid.New().String() + "{group}"
// Add values to source keys
_, err := client.PfAdd(context.Background(), sourceKey1, []string{"value1", "value2"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
_, err = client.PfAdd(context.Background(), sourceKey2, []string{"value2", "value3", "value4"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
// Merge the source keys into a destination key
destKey := uuid.New().String() + "{group}"
result, err := client.PfMerge(context.Background(), destKey, []string{sourceKey1, sourceKey2})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
fmt.Println(result)
Output: OK
func (*ClusterClient) Ping ¶
func (client *ClusterClient) Ping(ctx context.Context) (string, error)
Pings the server. The command will be routed to all primary nodes.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
Returns "PONG".
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.Ping(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: PONG
func (*ClusterClient) PingWithOptions ¶
func (client *ClusterClient) PingWithOptions( ctx context.Context, pingOptions options.ClusterPingOptions, ) (string, error)
Pings the server. The command will be routed to all primary nodes, unless `Route` is provided in `pingOptions`.
Parameters:
ctx - The context for controlling the command execution. pingOptions - The [ClusterPingOptions] type.
Return value:
Returns the copy of message.
For example:
route := options.RouteOption{config.RandomRoute}
opts := options.ClusterPingOptions{ &options.PingOptions{ "Hello" }, &route }
result, err := clusterClient.PingWithOptions(context.Background(), opts)
fmt.Println(result) // Output: Hello
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
options := options.ClusterPingOptions{
PingOptions: &options.PingOptions{
Message: "hello",
},
RouteOption: nil,
}
result, err := client.PingWithOptions(context.Background(), options)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: hello
func (*ClusterClient) PubSubChannels ¶
Lists the currently active channels.
When used in cluster mode, the command is routed to all nodes and aggregates the responses into a single array.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
An array of active channel names.
Example ¶
var publisher *ClusterClient = getExampleClusterClient() // example helper function
defer closeAllClients()
// Create subscribers with subscriptions
getExampleClusterClientWithSubscription(config.ExactClusterChannelMode, "channel1")
// Allow subscriptions to establish
time.Sleep(100 * time.Millisecond)
result, err := publisher.PubSubChannels(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [channel1]
func (*ClusterClient) PubSubChannelsWithPattern ¶
func (client *ClusterClient) PubSubChannelsWithPattern(ctx context.Context, pattern string) ([]string, error)
Lists the currently active channels matching the specified pattern.
Pattern can be any glob-style pattern: - h?llo matches hello, hallo and hxllo - h*llo matches hllo and heeeello - h[ae]llo matches hello and hallo, but not hillo
When used in cluster mode, the command is routed to all nodes and aggregates the responses into a single array.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. pattern - The pattern to match channel names against.
Return value:
An array of active channel names matching the pattern.
Example ¶
var publisher *ClusterClient = getExampleClusterClient() // example helper function
defer closeAllClients()
// Create subscribers with subscriptions to different channels
getExampleClusterClientWithSubscription(config.ExactClusterChannelMode, "news.sports")
getExampleClusterClientWithSubscription(config.ExactClusterChannelMode, "news.weather")
getExampleClusterClientWithSubscription(config.ExactClusterChannelMode, "events.local")
// Allow subscriptions to establish
time.Sleep(100 * time.Millisecond)
// Get channels matching the "news.*" pattern
result, err := publisher.PubSubChannelsWithPattern(context.Background(), "news.*")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
sort.Strings(result)
fmt.Println(result)
Output: [news.sports news.weather]
func (*ClusterClient) PubSubNumPat ¶
Returns the number of patterns that are subscribed to by clients.
This returns the total number of unique patterns that all clients are subscribed to, not the count of clients subscribed to patterns.
When used in cluster mode, the command is routed to all nodes and aggregates the responses.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
The number of patterns that are subscribed to by clients.
Example ¶
var publisher *ClusterClient = getExampleClusterClient() // example helper function
defer closeAllClients()
// Create subscribers with subscriptions
getExampleClusterClientWithSubscription(config.PatternClusterChannelMode, "news.*")
getExampleClusterClientWithSubscription(config.PatternClusterChannelMode, "events.*")
// Allow subscriptions to establish
time.Sleep(100 * time.Millisecond)
result, err := publisher.PubSubNumPat(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 2
func (*ClusterClient) PubSubNumSub ¶
func (client *ClusterClient) PubSubNumSub(ctx context.Context, channels ...string) (map[string]int64, error)
Returns the number of subscribers for the specified channels.
The count only includes clients subscribed to exact channels, not pattern subscriptions. If no channels are specified, an empty map is returned.
When used in cluster mode, the command is routed to all nodes and aggregates the responses into a single map.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. channels - The channel names to get subscriber counts for.
Return value:
A map of channel names to their subscriber counts.
Example ¶
var publisher *ClusterClient = getExampleClusterClient() // example helper function
defer closeAllClients()
// Create subscribers with subscriptions to different channels
getExampleClusterClientWithSubscription(config.ExactClusterChannelMode, "news.sports")
getExampleClusterClientWithSubscription(config.ExactClusterChannelMode, "news.weather")
// Second subscriber to same channel
getExampleClusterClientWithSubscription(config.ExactClusterChannelMode, "news.weather")
getExampleClusterClientWithSubscription(config.ExactClusterChannelMode, "events.local")
// Allow subscriptions to establish
time.Sleep(100 * time.Millisecond)
// Get subscriber counts for specific channels
result, err := publisher.PubSubNumSub(context.Background(), "news.sports", "news.weather", "events.local")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Sort the channels for consistent output
channels := make([]string, 0, len(result))
for channel := range result {
channels = append(channels, channel)
}
sort.Strings(channels)
// Print results in sorted order
for _, channel := range channels {
fmt.Printf("%s: %d\n", channel, result[channel])
}
Output: events.local: 1 news.sports: 1 news.weather: 2
func (*ClusterClient) PubSubShardChannels ¶
func (client *ClusterClient) PubSubShardChannels(ctx context.Context) ([]string, error)
Returns a list of all sharded channels.
Since:
Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
A list of shard channels.
Example ¶
var publisher *ClusterClient = getExampleClusterClient() // example helper function
defer closeAllClients()
// Create subscribers with subscriptions
getExampleClusterClientWithSubscription(config.ShardedClusterChannelMode, "channel1")
// Allow subscriptions to establish
time.Sleep(100 * time.Millisecond)
result, err := publisher.PubSubShardChannels(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [channel1]
func (*ClusterClient) PubSubShardChannelsWithPattern ¶
func (client *ClusterClient) PubSubShardChannelsWithPattern(ctx context.Context, pattern string) ([]string, error)
Returns a list of all sharded channels that match the given pattern.
Since:
Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. pattern - A glob-style pattern to match active shard channels.
Return value:
A list of shard channels that match the given pattern.
Example ¶
var publisher *ClusterClient = getExampleClusterClient() // example helper function
defer closeAllClients()
// Create subscribers with subscriptions to different channels
getExampleClusterClientWithSubscription(config.ShardedClusterChannelMode, "news.sports")
getExampleClusterClientWithSubscription(config.ShardedClusterChannelMode, "news.weather")
getExampleClusterClientWithSubscription(config.ShardedClusterChannelMode, "events.local")
// Allow subscriptions to establish
time.Sleep(100 * time.Millisecond)
// Get channels matching the "news.*" pattern
result, err := publisher.PubSubShardChannelsWithPattern(context.Background(), "news.*")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
sort.Strings(result)
fmt.Println(result)
Output: [news.sports news.weather]
func (*ClusterClient) PubSubShardNumSub ¶
func (client *ClusterClient) PubSubShardNumSub(ctx context.Context, channels ...string) (map[string]int64, error)
Returns the number of subscribers for a sharded channel.
Since:
Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. channels - The channel to get the number of subscribers for.
Return value:
The number of subscribers for the sharded channel.
Example ¶
var publisher *ClusterClient = getExampleClusterClient() // example helper function
defer closeAllClients()
// Create subscribers with subscriptions to different channels
getExampleClusterClientWithSubscription(config.ShardedClusterChannelMode, "news.sports")
getExampleClusterClientWithSubscription(config.ShardedClusterChannelMode, "news.weather")
// Second subscriber to same channel
getExampleClusterClientWithSubscription(config.ShardedClusterChannelMode, "news.weather")
getExampleClusterClientWithSubscription(config.ShardedClusterChannelMode, "events.local")
// Allow subscriptions to establish
time.Sleep(100 * time.Millisecond)
// Get subscriber counts for specific channels
result, err := publisher.PubSubShardNumSub(context.Background(), "news.sports", "news.weather", "events.local")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Sort the channels for consistent output
channels := make([]string, 0, len(result))
for channel := range result {
channels = append(channels, channel)
}
sort.Strings(channels)
// Print results in sorted order
for _, channel := range channels {
fmt.Printf("%s: %d\n", channel, result[channel])
}
Output: events.local: 1 news.sports: 1 news.weather: 2
func (*ClusterClient) Publish ¶
func (client *ClusterClient) Publish(ctx context.Context, channel string, message string, sharded bool) (int64, error)
Publish posts a message to the specified channel. Returns the number of clients that received the message.
Channel can be any string, but common patterns include using "." to create namespaces like "news.sports" or "news.weather".
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. channel - The channel to publish the message to. message - The message to publish. sharded - Whether the channel is sharded.
Return value:
The number of clients that received the message.
Example ¶
var publisher *ClusterClient = getExampleClusterClient() // example helper function
defer closeAllClients()
// Create a subscriber with subscription
subscriber := getExampleClusterClientWithSubscription(config.ExactClusterChannelMode, "my_channel")
queue, err := subscriber.GetQueue()
if err != nil {
fmt.Println("Failed to get queue: ", err)
return
}
// Allow subscription to establish
time.Sleep(100 * time.Millisecond)
// Publish a message
result, err := publisher.Publish(context.Background(), "my_channel", "Hello, World!", false)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
// Wait for and print the received message
msg := <-queue.WaitForMessage()
fmt.Println(msg.Message)
Output: 1 Hello, World!
func (*ClusterClient) RPop ¶
Removes and returns the last elements of the list stored at key. The command pops a single element from the end of the list.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list.
Return value:
The models.Result[string] containing the value of the last element. If key does not exist, [models.CreateNilStringResult()] will be returned.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.RPush(context.Background(), "my_list", []string{"a", "b", "c", "d", "e", "e", "e"})
result1, err := client.RPop(context.Background(), "my_list")
result2, err := client.RPop(context.Background(), "non_existing_key")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2.IsNil())
Output: 7 {e false} true
func (*ClusterClient) RPopCount ¶
func (client *ClusterClient) RPopCount(ctx context.Context, key string, count int64) ([]string, error)
Removes and returns up to count elements from the list stored at key, depending on the list's length.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list. count - The count of the elements to pop from the list.
Return value:
An array of popped elements as strings will be returned depending on the list's length. If key does not exist, nil will be returned.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.RPush(context.Background(), "my_list", []string{"a", "b", "c", "d", "e", "e", "e"})
result1, err := client.RPopCount(context.Background(), "my_list", 4)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 7 [e e e d]
func (*ClusterClient) RPush ¶
func (client *ClusterClient) RPush(ctx context.Context, key string, elements []string) (int64, error)
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 an empty list before performing the push operation.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list. elements - The elements to insert at the tail of the list stored at key.
Return value:
The length of the list after the push operation.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.RPush(context.Background(), "my_list", []string{"a", "b", "c", "d", "e", "e", "e"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 7
func (*ClusterClient) RPushX ¶
func (client *ClusterClient) RPushX(ctx context.Context, key string, elements []string) (int64, error)
Inserts all the specified values at the tail of the list stored at key, only if key exists and holds a list. If key is not a list, this performs no operation.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list. elements - The elements to insert at the tail of the list stored at key.
Return value:
The length of the list after the push operation.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.RPush(context.Background(), "my_list", []string{"value1"})
result1, err := client.RPushX(context.Background(), "my_list", []string{"value2", "value3"})
result2, err := client.LRange(context.Background(), "my_list", 0, -1)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: 1 3 [value1 value2 value3]
func (*ClusterClient) RandomKey ¶
Returns a random key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
A random key from the database.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := uuid.New().String()
client.Set(context.Background(), key, "Hello")
result, err := client.RandomKey(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(len(result.Value()) > 0)
Output: true
func (*ClusterClient) RandomKeyWithRoute ¶
func (client *ClusterClient) RandomKeyWithRoute(ctx context.Context, opts options.RouteOption) (models.Result[string], error)
Returns a random key.
Parameters:
ctx - The context for controlling the command execution. opts - specifies the routing configuration for the command. The client will route the command to the nodes defined by route, and will return the first successful result.
Return value:
A random key from the database.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
options := options.RouteOption{Route: nil}
key := uuid.New().String()
client.Set(context.Background(), key, "Hello")
result, err := client.RandomKeyWithRoute(context.Background(), options)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(len(result.Value()) > 0)
Output: true
func (*ClusterClient) RefreshIamToken ¶ added in v2.2.0
RefreshIamToken manually refreshes the IAM authentication token for the current connection.
This method is only available if the client was created with IAM authentication (using [ServerCredentials] with [IamAuthConfig]). It triggers an immediate refresh of the IAM token and updates the connection with the new token.
Normally, IAM tokens are refreshed automatically based on the refresh interval configured in [IamAuthConfig]. Use this method when you need to force an immediate token refresh, such as when credentials have been rotated or when troubleshooting authentication issues.
Parameters:
ctx - The context for controlling the command execution and cancellation.
Return value:
Returns "OK" on successful token refresh.
Errors:
Returns an error if: - The client was not configured with IAM authentication - The token refresh operation fails - The context is cancelled - The client is closed
Example:
// Create client with IAM authentication
iamConfig := config.NewIamAuthConfig("my-cluster", config.ElastiCache, "us-east-1")
creds, _ := config.NewServerCredentialsWithIam("myuser", iamConfig)
clientConfig := config.NewClientConfiguration().WithCredentials(creds)
client, _ := glide.NewClient(clientConfig)
// Manually refresh the token
result, err := client.RefreshIamToken(context.Background())
if err != nil {
log.Printf("Token refresh failed: %v", err)
return
}
log.Printf("Token refreshed: %s", result) // "OK"
See also: [IamAuthConfig], [ServerCredentials], [NewServerCredentialsWithIam]
func (*ClusterClient) Rename ¶
Renames `key` to `newKey`. If `newKey` already exists it is overwritten.
Note:
When in cluster mode, both `key` and `newKey` must map to the same hash slot.
Parameters:
ctx - The context for controlling the command execution. key - The key to rename. newKey - The new name of the key.
Return value:
If the key was successfully renamed, return "OK". If key does not exist, an error is thrown.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.Set(context.Background(), "{key}1", "someValue")
result1, err := client.Rename(context.Background(), "{key}1", "{key}2")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK OK
func (*ClusterClient) RenameNX ¶
Renames `key` to `newkey` if `newKey` does not yet exist.
Note:
When in cluster mode, both `key` and `newkey` must map to the same hash slot.
Parameters:
ctx - The context for controlling the command execution. key - The key to rename. newKey - The new name of the key.
Return value:
`true` if key was renamed to `newKey`, `false` if `newKey` already exists.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.Set(context.Background(), "{key}1", "someValue")
result1, err := client.RenameNX(context.Background(), "{key}1", "{key}2")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK true
func (*ClusterClient) ResetConnectionPassword ¶
Update the current connection by removing the 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.
Note:
This method updates the client's internal password configuration and does not perform password rotation on the server side.
Parameters:
ctx - The context for controlling the command execution.
Return value:
`"OK"` response on success.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
response, err := client.ResetConnectionPassword(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(response)
Output: OK
func (*ClusterClient) Restore ¶
func (client *ClusterClient) Restore(ctx context.Context, key string, ttl time.Duration, value string) (string, error)
Creates a key associated with a value that is obtained by deserializing the provided serialized value (obtained via Client.Dump or ClusterClient.Dump).
Parameters:
ctx - The context for controlling the command execution. key - The key to create. ttl - The expiry time. If 0, the key will persist. value - The serialized value to deserialize and assign to key.
Return value:
Return OK if successfully create a key with a value.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.Set(context.Background(), "key1", "someValue")
dump, err := client.Dump(context.Background(), "key1")
result1, err := client.Del(context.Background(), []string{"key1"})
result2, err := client.Restore(context.Background(), "key1", 0, dump.Value())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: OK 1 OK
func (*ClusterClient) RestoreWithOptions ¶
func (client *ClusterClient) RestoreWithOptions(ctx context.Context, key string, ttl time.Duration, value string, options options.RestoreOptions, ) (string, error)
Creates a key associated with a value that is obtained by deserializing the provided serialized value (obtained via Client.Dump or ClusterClient.Dump).
Parameters:
ctx - The context for controlling the command execution. key - The key to create. ttl - The expiry time. If 0, the key will persist. value - The serialized value to deserialize and assign to key. restoreOptions - Set restore options with replace and absolute TTL modifiers, object idletime and frequency.
Return value:
Return OK if successfully create a key with a value.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.Set(context.Background(), "key1", "someValue")
dump, err := client.Dump(context.Background(), "key1")
result1, err := client.Del(context.Background(), []string{"key1"})
opts := options.NewRestoreOptions().SetReplace().SetABSTTL().SetEviction(constants.FREQ, 10)
result2, err := client.RestoreWithOptions(context.Background(), "key1", 0, dump.Value(), *opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: OK 1 OK
func (*ClusterClient) SAdd ¶
SAdd adds specified members to the set stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key where members will be added to its set. members - A list of members to add to the set stored at key.
Return value:
The number of members that were added to the set, excluding members already present.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "my_set"
result, err := client.SAdd(context.Background(), key, []string{"member1", "member2"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 2
func (*ClusterClient) SCard ¶
SCard retrieves the set cardinality (number of elements) of the set stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key from which to retrieve the number of set members.
Return value:
The cardinality (number of elements) of the set, or `0` if the key does not exist.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "my_set"
client.SAdd(context.Background(), key, []string{"member1", "member2"})
result, err := client.SCard(context.Background(), key)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 2
func (*ClusterClient) SDiff ¶
SDiff computes the difference between the first set and all the successive sets in keys.
Note:
When in cluster mode, all keys must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - The keys of the sets to diff.
Return value:
A `map[string]struct{}` representing the difference between the sets.
If a key does not exist, it is treated as an empty set.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key1 := "{set}1"
key2 := "{set}2"
client.SAdd(context.Background(), key1, []string{"member1", "member2"})
client.SAdd(context.Background(), key2, []string{"member2"})
result, err := client.SDiff(context.Background(), []string{key1, key2})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: map[member1:{}]
func (*ClusterClient) SDiffStore ¶
func (client *ClusterClient) SDiffStore(ctx context.Context, destination string, keys []string) (int64, error)
SDiffStore stores the difference between the first set and all the successive sets in `keys` into a new set at `destination`.
Note:
When in cluster mode, `destination` and all keys must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. destination - The key of the destination set. keys - The keys of the sets to diff.
Return value:
The number of elements in the resulting set.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key1 := "{set}1"
key2 := "{set}2"
destination := "{set}3"
client.SAdd(context.Background(), key1, []string{"member1", "member2"})
client.SAdd(context.Background(), key2, []string{"member2"})
result, err := client.SDiffStore(context.Background(), destination, []string{key1, key2})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 1
func (*ClusterClient) SInter ¶
func (client *ClusterClient) SInter(ctx context.Context, keys []string) (map[string]struct{}, error)
SInter gets the intersection of all the given sets.
Note:
When in cluster mode, all keys must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - The keys of the sets to intersect.
Return value:
A `map[string]struct{}` containing members which are present in all given sets.
If one or more sets do not exist, an empty collection will be returned.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key1 := "{set}1"
key2 := "{set}2"
client.SAdd(context.Background(), key1, []string{"member1", "member2"})
client.SAdd(context.Background(), key2, []string{"member2"})
result, err := client.SInter(context.Background(), []string{key1, key2})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: map[member2:{}]
func (*ClusterClient) SInterCard ¶
SInterCard gets the cardinality of the intersection of all the given sets.
Since:
Valkey 7.0 and above.
Note:
When in cluster mode, all keys must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - The keys of the sets to intersect.
Return value:
The cardinality of the intersection result. If one or more sets do not exist, `0` is returned.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key1 := "{set}1"
key2 := "{set}2"
client.SAdd(context.Background(), key1, []string{"member1", "member2"})
client.SAdd(context.Background(), key2, []string{"member2"})
result, err := client.SInterCard(context.Background(), []string{key1, key2})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 1
func (*ClusterClient) SInterCardLimit ¶
func (client *ClusterClient) SInterCardLimit(ctx context.Context, keys []string, limit int64) (int64, error)
SInterCardLimit gets the cardinality of the intersection of all the given sets, up to the specified limit.
Since:
Valkey 7.0 and above.
Note:
When in cluster mode, all keys must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - The keys of the sets to intersect. limit - The limit for the intersection cardinality value.
Return value:
The cardinality of the intersection result, or the limit if reached. If one or more sets do not exist, `0` is returned. If the intersection cardinality reaches 'limit' partway through the computation, returns 'limit' as the cardinality.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key1 := "{set}1"
key2 := "{set}2"
limit := int64(1)
client.SAdd(context.Background(), key1, []string{"member1", "member2", "member3"})
client.SAdd(context.Background(), key2, []string{"member2", "member3"})
result, err := client.SInterCardLimit(context.Background(), []string{key1, key2}, limit)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 1
func (*ClusterClient) SInterStore ¶
func (client *ClusterClient) SInterStore(ctx context.Context, destination string, keys []string) (int64, error)
Stores the members of the intersection of all given sets specified by `keys` into a new set at `destination`
Note:
When in cluster mode, `destination` and all keys must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. destination - The key of the destination set. keys - The keys from which to retrieve the set members.
Return value:
The number of elements in the resulting set.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key1 := "{set}1"
key2 := "{set}2"
destination := "{set}3"
client.SAdd(context.Background(), key1, []string{"member1", "member2"})
client.SAdd(context.Background(), key2, []string{"member2"})
result, err := client.SInterStore(context.Background(), destination, []string{key1, key2})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 1
func (*ClusterClient) SIsMember ¶
func (client *ClusterClient) SIsMember(ctx context.Context, key string, member string) (bool, error)
SIsMember returns if member is a member of the set stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the set. member - The member to check for existence in the set.
Return value:
A bool containing true if the member exists in the set, false otherwise. If key doesn't exist, it is treated as an empty set and the method returns false.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "my_set"
client.SAdd(context.Background(), key, []string{"member1", "member2"})
result, err := client.SIsMember(context.Background(), key, "member1")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: true
func (*ClusterClient) SMIsMember ¶
func (client *ClusterClient) SMIsMember(ctx context.Context, key string, members []string) ([]bool, error)
SMIsMember returns whether each member is a member of the set stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the set. members - The members to check.
Return value:
A []bool containing whether each member is a member of the set stored at key.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "my_set"
members := []string{"member1", "member2"}
client.SAdd(context.Background(), key, members)
memberTest := []string{"member1", "member2", "member3"}
result, err := client.SMIsMember(context.Background(), key, memberTest)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [true true false]
func (*ClusterClient) SMembers ¶
SMembers retrieves all the members of the set value stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key from which to retrieve the set members.
Return value:
A `map[string]struct{}` containing all members of the set.
Returns an empty collection if key does not exist.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "my_set"
client.SAdd(context.Background(), key, []string{"member1", "member2"})
result, err := client.SMembers(context.Background(), key)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: map[member1:{} member2:{}]
func (*ClusterClient) SMove ¶
func (client *ClusterClient) SMove(ctx context.Context, source string, destination string, member string) (bool, error)
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.
Note: When in cluster mode, `source` and `destination` must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. source - The key of the set to remove the element from. destination - The key of the set to add the element to. member - The set element to move.
Return value:
`true` on success, or `false` if the `source` set does not exist or the element is not a member of the source set.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
source := "{set}1"
destination := "{set}2"
member := "member1"
client.SAdd(context.Background(), source, []string{member})
result, err := client.SMove(context.Background(), source, destination, member)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: true
func (*ClusterClient) SPop ¶
SPop removes and returns one random member from the set stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the set.
Return value:
A models.Result[string] containing the value of the popped member. Returns a NilResult if key does not exist.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "my_set"
client.SAdd(context.Background(), key, []string{"member1", "member2"})
result, err := client.SPop(context.Background(), key)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.IsNil())
Output: false
func (*ClusterClient) SPopCount ¶
func (client *ClusterClient) SPopCount(ctx context.Context, key string, count int64) (map[string]struct{}, error)
SpopCount removes and returns up to count random members from the set stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the set. count - The number of members to return. If count is positive, returns unique elements. If count is larger than the set's cardinality, returns the entire set.
Return value:
A `map[string]struct{}` of popped elements.
If key does not exist, an empty collection will be returned.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "my_set"
client.SAdd(context.Background(), key, []string{"member1", "member2", "member3", "member4"})
result, err := client.SPopCount(context.Background(), key, 2)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(len(result))
Output: 2
func (*ClusterClient) SRandMember ¶
func (client *ClusterClient) SRandMember(ctx context.Context, key string) (models.Result[string], error)
SRandMember returns a random element from the set value stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key from which to retrieve the set member.
Return value:
A models.Result[string] containing a random element from the set. Returns models.CreateNilStringResult() if key does not exist.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "my_set"
client.SAdd(context.Background(), key, []string{"member1", "member2"})
result, err := client.SRandMember(context.Background(), key)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.IsNil()) // Unable to test for a random value so just check if it is not nil
Output: false
func (*ClusterClient) SRandMemberCount ¶
func (client *ClusterClient) SRandMemberCount(ctx context.Context, key string, count int64) ([]string, error)
SRandMemberCount returns multiple random members from the set value stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
key - The key from which to retrieve the set members.
count - The number of members to return.
If count is positive, returns unique elements (no repetition) up to count or the set size, whichever is smaller.
If count is negative, returns elements with possible repetition (the same element may be returned multiple times),
and the number of returned elements is the absolute value of count.
Return value:
An array of random elements from the set. When count is positive, the returned elements are unique (no repetitions). When count is negative, the returned elements may contain duplicates. If the set does not exist or is empty, an empty array is returned.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "my_set"
client.SAdd(context.Background(), key, []string{"member1", "member2", "member3"})
// Get 2 unique random members
result, err := client.SRandMemberCount(context.Background(), key, 2)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(len(result)) // Cannot test exact values as they are random
Output: 2
func (*ClusterClient) SRem ¶
SRem removes specified members from the set stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key from which members will be removed. members - A list of members to remove from the set stored at key.
Return value:
The number of members that were removed from the set, excluding non-existing members.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "my_set"
client.SAdd(context.Background(), key, []string{"member1", "member2", "member3", "member4", "member5"})
result, err := client.SRem(context.Background(), key, []string{"member1", "member2"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 2
func (*ClusterClient) SScan ¶
func (client *ClusterClient) SScan(ctx context.Context, key string, cursor models.Cursor) (models.ScanResult, error)
Iterates incrementally over a set.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the set. cursor - The cursor that points to the next iteration of results.
Return value:
An object which holds the next cursor and the subset of the hash held by `key`. The cursor will return `false` from `IsFinished()` method on the last iteration of the subset. The data array in the result is always an array of the subset of the set held in `key`.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "my_set"
client.SAdd(context.Background(), key, []string{"member1", "member2"})
result, err := client.SScan(context.Background(), key, models.NewCursor())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
sort.Strings(result.Data) // Sort for consistent comparison
fmt.Println("Cursor:", result.Cursor)
fmt.Println("Collection:", result.Data)
Output: Cursor: 0 Collection: [member1 member2]
func (*ClusterClient) SScanWithOptions ¶
func (client *ClusterClient) SScanWithOptions( ctx context.Context, key string, cursor models.Cursor, options options.BaseScanOptions, ) (models.ScanResult, error)
Iterates incrementally over a set.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the set. cursor - The cursor that points to the next iteration of results. options - [options.BaseScanOptions]
Return value:
An object which holds the next cursor and the subset of the hash held by `key`. The cursor will return `false` from `IsFinished()` method on the last iteration of the subset. The data array in the result is always an array of the subset of the set held in `key`.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "my_set"
client.SAdd(context.Background(), key, []string{"member1", "member2", "item3"})
options := options.NewBaseScanOptions().SetMatch("mem*")
result, err := client.SScanWithOptions(context.Background(), key, models.NewCursor(), *options)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
sort.Strings(result.Data) // Sort for consistent comparison
fmt.Println("Cursor:", result.Cursor)
fmt.Println("Collection:", result.Data)
Output: Cursor: 0 Collection: [member1 member2]
func (*ClusterClient) SSubscribe ¶ added in v2.3.0
func (client *ClusterClient) SSubscribe(ctx context.Context, channels []string, timeoutMs int) error
SSubscribe subscribes the client to the specified sharded channels (blocking). This command updates the client's internal desired subscription state and waits for server confirmation.
Sharded pubsub is only available in cluster mode and requires Valkey 7.0+.
Parameters:
ctx - The context for the operation.
channels - A slice of sharded channel names to subscribe to.
timeoutMs - Maximum time in milliseconds to wait for server confirmation.
A value of 0 blocks indefinitely until confirmation.
Return value:
An error if the operation fails or times out.
Example:
err := client.SSubscribe(ctx, []string{"shard_channel1"}, 5000)
SSubscribe subscribes the client to the specified sharded channels (blocking). This command updates the client's internal desired subscription state and waits for server confirmation.
Sharded pubsub is only available in cluster mode and requires Valkey 7.0+.
Parameters:
ctx - The context for the operation.
channels - A slice of sharded channel names to subscribe to.
timeoutMs - Maximum time in milliseconds to wait for server confirmation.
A value of 0 blocks indefinitely until confirmation.
Return value:
An error if the operation fails or times out.
Example:
err := client.SSubscribe(ctx, []string{"shard_channel1"}, 0)
func (*ClusterClient) SSubscribeLazy ¶ added in v2.3.0
func (client *ClusterClient) SSubscribeLazy(ctx context.Context, channels []string) error
SSubscribeLazy subscribes the client to the specified sharded channels (non-blocking). This command updates the client's internal desired subscription state without waiting for server confirmation. It returns immediately after updating the local state.
Sharded pubsub is only available in cluster mode and requires Valkey 7.0+.
Parameters:
ctx - The context for the operation. channels - A slice of sharded channel names to subscribe to.
Return value:
An error if the operation fails.
Example:
err := client.SSubscribeLazy(ctx, []string{"shard_channel1"})
SSubscribeLazy subscribes the client to the specified sharded channels (non-blocking). This command updates the client's internal desired subscription state without waiting for server confirmation. It returns immediately after updating the local state. The client will attempt to subscribe asynchronously in the background.
Sharded pubsub is only available in cluster mode and requires Valkey 7.0+.
Note: Use GetSubscriptions() to verify the actual server-side subscription state.
Parameters:
ctx - The context for the operation. channels - A slice of sharded channel names to subscribe to.
Return value:
An error if the operation fails.
Example:
err := client.SSubscribeLazy(ctx, []string{"shard_channel1"})
func (*ClusterClient) SUnion ¶
func (client *ClusterClient) SUnion(ctx context.Context, keys []string) (map[string]struct{}, error)
SUnion gets the union of all the given sets.
Note:
When in cluster mode, all keys must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - The keys of the sets.
Return value:
A `map[string]struct{}` of members which are present in at least one of the given sets.
If none of the sets exist, an empty collection will be returned.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key1 := "{set}1"
key2 := "{set}2"
client.SAdd(context.Background(), key1, []string{"member1", "member2"})
client.SAdd(context.Background(), key2, []string{"member2", "member3"})
result, err := client.SUnion(context.Background(), []string{key1, key2})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: map[member1:{} member2:{} member3:{}]
func (*ClusterClient) SUnionStore ¶
func (client *ClusterClient) SUnionStore(ctx context.Context, destination string, keys []string) (int64, error)
SUnionStore stores the members of the union of all given sets specified by `keys` into a new set at `destination`.
Note:
When in cluster mode, `destination` and all `keys` must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. destination - The key of the destination set. keys - The keys from which to retrieve the set members.
Return value:
The number of elements in the resulting set.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key1 := "{set}1"
key2 := "{set}2"
destination := "{set}3"
client.SAdd(context.Background(), key1, []string{"member1", "member2"})
client.SAdd(context.Background(), key2, []string{"member2", "member3"})
result, err := client.SUnionStore(context.Background(), destination, []string{key1, key2})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 3
func (*ClusterClient) SUnsubscribe ¶ added in v2.3.0
func (client *ClusterClient) SUnsubscribe(ctx context.Context, channels []string, timeoutMs int) error
SUnsubscribe unsubscribes the client from the specified sharded channels (blocking). This command updates the client's internal desired subscription state and waits for server confirmation. If no channels are specified (nil or empty slice), unsubscribes from all sharded channels.
Parameters:
ctx - The context for the operation.
channels - A slice of sharded channel names to unsubscribe from. Pass nil to unsubscribe from all.
timeoutMs - Maximum time in milliseconds to wait for server confirmation.
A value of 0 blocks indefinitely until confirmation.
Return value:
An error if the operation fails or times out.
Example:
err := client.SUnsubscribe(ctx, []string{"shard_channel1"}, 5000)
err := client.SUnsubscribe(ctx, nil, 5000) // Unsubscribe from all
func (*ClusterClient) SUnsubscribeLazy ¶ added in v2.3.0
func (client *ClusterClient) SUnsubscribeLazy(ctx context.Context, channels []string) error
SUnsubscribeLazy unsubscribes the client from the specified sharded channels (non-blocking). This command updates the client's internal desired subscription state without waiting for server confirmation. It returns immediately after updating the local state. If no channels are specified (nil), unsubscribes from all sharded channels.
Parameters:
ctx - The context for the operation. channels - A slice of sharded channel names to unsubscribe from. Pass nil to unsubscribe from all.
Return value:
An error if the operation fails.
Example:
err := client.SUnsubscribeLazy(ctx, []string{"shard_channel1"})
err := client.SUnsubscribeLazy(ctx, nil) // Unsubscribe from all
func (*ClusterClient) Scan ¶
func (client *ClusterClient) Scan( ctx context.Context, cursor models.ClusterScanCursor, ) (models.ClusterScanResult, error)
Incrementally iterates over the keys in the cluster. The method returns a list containing the next cursor and a list of keys.
This command is similar to the SCAN command but is designed to work in a cluster environment. For each iteration, a new cursor object should be used to continue the scan. Using the same cursor object for multiple iterations will result in the same keys or unexpected behavior. For more information about the Cluster Scan implementation, see https://glide.valkey.io/concepts/client-features/cluster-scan/.
Like the SCAN command, the method can be used to iterate over the keys in the database, returning all keys the database has from when the scan started until the scan ends. The same key can be returned in multiple scan iterations.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. cursor - The [ClusterScanCursor] object that wraps the scan state. To start a new scan, create a new empty `ClusterScanCursor` using [models.NewClusterScanCursor()].
Returns:
An object which holds the next cursor and the subset of the hash held by `key`. The cursor will return `false` from `IsFinished()` method on the last iteration of the subset. The data array in the result is always an array of matched keys from the database.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
keysToSet := map[string]string{
"key1": "value1",
"key2": "value2",
"key3": "value3",
}
_, err := client.MSet(context.Background(), keysToSet)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
cursor := models.NewClusterScanCursor()
allKeys := []string{}
for !cursor.IsFinished() {
result, err := client.Scan(context.Background(), cursor)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
allKeys = append(allKeys, result.Keys...)
cursor = result.Cursor
}
// Elements will contain values [key1 key2 key3] but because order
// can vary, we just check the length
fmt.Println(len(allKeys))
Output: 3
func (*ClusterClient) ScanWithOptions ¶
func (client *ClusterClient) ScanWithOptions( ctx context.Context, cursor models.ClusterScanCursor, opts options.ClusterScanOptions, ) (models.ClusterScanResult, error)
Incrementally iterates over the keys in the cluster. The method returns a list containing the next cursor and a list of keys.
This command is similar to the SCAN command but is designed to work in a cluster environment. For each iteration, a new cursor object should be used to continue the scan. Using the same cursor object for multiple iterations will result in the same keys or unexpected behavior. For more information about the Cluster Scan implementation, see https://glide.valkey.io/concepts/client-features/cluster-scan/.
Like the SCAN command, the method can be used to iterate over the keys in the database, returning all keys the database has from when the scan started until the scan ends. The same key can be returned in multiple scan iterations.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. cursor - The [ClusterScanCursor] object that wraps the scan state. To start a new scan, create a new empty `ClusterScanCursor` using [models.NewClusterScanCursor()]. opts - The scan options. Can specify MATCH, COUNT, and TYPE configurations.
Returns:
An object which holds the next cursor and the subset of the hash held by `key`. The cursor will return `false` from `IsFinished()` method on the last iteration of the subset. The data array in the result is always an array of matched keys from the database.
Example (Count) ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
keysToSet := map[string]string{
"key1": "value1",
"key2": "value2",
"key3": "value3",
}
_, err := client.MSet(context.Background(), keysToSet)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
cursor := models.NewClusterScanCursor()
opts := options.NewClusterScanOptions().SetCount(10)
allKeys := []string{}
for !cursor.IsFinished() {
result, err := client.ScanWithOptions(context.Background(), cursor, *opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
allKeys = append(allKeys, result.Keys...)
cursor = result.Cursor
}
// Elements will contain values [key1 key2 key3] but because order
// can vary, we just check the length
fmt.Println(len(allKeys))
Output: 3
Example (Match) ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
keysToSet := map[string]string{
"key-1": "value1",
"key-2": "value2",
"key3": "value3",
"nonPatternKey": "value4",
}
_, err := client.MSet(context.Background(), keysToSet)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
_, err = client.SAdd(context.Background(), "someKey", []string{"value"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
cursor := models.NewClusterScanCursor()
opts := options.NewClusterScanOptions().SetMatch("key-*")
allKeys := []string{}
for !cursor.IsFinished() {
result, err := client.ScanWithOptions(context.Background(), cursor, *opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
allKeys = append(allKeys, result.Keys...)
cursor = result.Cursor
}
// Elements will contain values [key-1 key-2] but because order
// can vary, we just check the length
fmt.Println(len(allKeys))
Output: 2
Example (MatchNonUTF8) ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
keysToSet := map[string]string{
"key\xc0\xc1-1": "value1",
"key-2": "value2",
"key\xf9\xc1-3": "value3",
}
_, err := client.MSet(context.Background(), keysToSet)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
_, err = client.SAdd(context.Background(), "someKey", []string{"value"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
cursor := models.NewClusterScanCursor()
opts := options.NewClusterScanOptions().SetMatch("key\xc0\xc1-*")
allKeys := []string{}
for !cursor.IsFinished() {
result, err := client.ScanWithOptions(context.Background(), cursor, *opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
allKeys = append(allKeys, result.Keys...)
cursor = result.Cursor
}
// Elements will contain value [key\xc0\xc1-1] but since it is
// an invalid utf8 character, we just check the length
fmt.Println(len(allKeys))
Output: 1
Example (Type) ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
keysToSet := map[string]string{
"key1": "value1",
"key2": "value2",
"key3": "value3",
}
_, err := client.MSet(context.Background(), keysToSet)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
_, err = client.SAdd(context.Background(), "someKey", []string{"value"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
cursor := models.NewClusterScanCursor()
opts := options.NewClusterScanOptions().SetType(constants.ObjectTypeSet)
allKeys := []string{}
for !cursor.IsFinished() {
result, err := client.ScanWithOptions(context.Background(), cursor, *opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
allKeys = append(allKeys, result.Keys...)
cursor = result.Cursor
}
fmt.Println(allKeys)
Output: [someKey]
func (*ClusterClient) ScriptExists ¶
Checks existence of scripts in the script cache by their SHA1 digest.
Note:
The command will be routed to all primary nodes by default.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. sha1s - SHA1 digests of Lua scripts to be checked.
Return value:
An array of boolean values indicating the existence of each script.
Example ¶
client := getExampleClusterClient()
// Invoke a script
script := options.NewScript("return 'Hello World!'")
client.InvokeScript(context.Background(), *script)
response, err := client.ScriptExists(context.Background(), []string{script.GetHash()})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
fmt.Println(response)
// Cleanup
script.Close()
Output: [true]
func (*ClusterClient) ScriptExistsWithRoute ¶
func (client *ClusterClient) ScriptExistsWithRoute( ctx context.Context, sha1s []string, route options.RouteOption, ) ([]bool, error)
Checks existence of scripts in the script cache by their SHA1 digest.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. sha1s - SHA1 digests of Lua scripts to be checked. route - Specifies the routing configuration for the command. The client will route the command to the nodes defined by `route`.
Return value:
An array of boolean values indicating the existence of each script.
Example ¶
client := getExampleClusterClient()
route := options.RouteOption{Route: config.NewSlotKeyRoute(config.SlotTypePrimary, "1")}
// Invoke a script
script := options.NewScript("return 'Hello World!'")
client.InvokeScriptWithRoute(context.Background(), *script, route)
response, err := client.ScriptExistsWithRoute(context.Background(), []string{script.GetHash()}, route)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
fmt.Println(response)
// Cleanup
script.Close()
Output: [true]
func (*ClusterClient) ScriptFlush ¶
func (client *ClusterClient) ScriptFlush(ctx context.Context) (string, error)
Removes all the scripts from the script cache. The command will be routed to all nodes.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
OK on success.
Example ¶
client := getExampleClusterClient()
// First, load a script
script := options.NewScript("return 'Hello World!'")
_, err := client.InvokeScript(context.Background(), *script)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
// Verify script exists
exists, err := client.ScriptExists(context.Background(), []string{script.GetHash()})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
fmt.Println("Script exists before flush:", exists[0])
// Flush all scripts
result, err := client.ScriptFlush(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
fmt.Println("Flush result:", result)
// Verify script no longer exists
exists, err = client.ScriptExists(context.Background(), []string{script.GetHash()})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
fmt.Println("Script exists after flush:", exists[0])
// Cleanup
script.Close()
Output: Script exists before flush: true Flush result: OK Script exists after flush: false
func (*ClusterClient) ScriptFlushWithMode ¶
func (client *ClusterClient) ScriptFlushWithMode(ctx context.Context, mode options.FlushMode) (string, error)
Removes all the scripts from the script cache with the specified flush mode. The mode can be either SYNC or ASYNC.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. mode - The flush mode (SYNC or ASYNC).
Return value:
OK on success.
Example ¶
client := getExampleClusterClient()
// First, load a script
script := options.NewScript("return 'Hello World!'")
_, err := client.InvokeScript(context.Background(), *script)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
// Verify script exists
exists, err := client.ScriptExists(context.Background(), []string{script.GetHash()})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
fmt.Println("Script exists before flush:", exists[0])
// Flush all scripts with ASYNC mode
result, err := client.ScriptFlushWithMode(context.Background(), options.ASYNC)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
fmt.Println("Flush result:", result)
// Verify script no longer exists
exists, err = client.ScriptExists(context.Background(), []string{script.GetHash()})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
fmt.Println("Script exists after flush:", exists[0])
// Cleanup
script.Close()
Output: Script exists before flush: true Flush result: OK Script exists after flush: false
func (*ClusterClient) ScriptFlushWithOptions ¶
func (client *ClusterClient) ScriptFlushWithOptions( ctx context.Context, options options.ScriptFlushOptions, ) (string, error)
Removes all the scripts from the script cache with the specified route options.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. options - The ScriptFlushOptions containing the flush mode and route. The mode can be either SYNC or ASYNC.
Return value:
OK on success.
Example ¶
client := getExampleClusterClient()
route := options.RouteOption{Route: config.AllPrimaries}
// First, load a script on all primaries
script := options.NewScript("return 'Hello World!'")
_, err := client.InvokeScriptWithRoute(context.Background(), *script, route)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
// Verify script exists
exists, err := client.ScriptExistsWithRoute(context.Background(), []string{script.GetHash()}, route)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
fmt.Println("Script exists before flush:", exists[0])
// Flush all scripts on all primaries with ASYNC mode
scriptFlushOptions := options.NewScriptFlushOptions().WithMode(options.ASYNC).WithRoute(&route)
result, err := client.ScriptFlushWithOptions(context.Background(), *scriptFlushOptions)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
fmt.Println("Flush result:", result)
// Verify script no longer exists
exists, err = client.ScriptExistsWithRoute(context.Background(), []string{script.GetHash()}, route)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
fmt.Println("Script exists after flush:", exists[0])
// Cleanup
script.Close()
Output: Script exists before flush: true Flush result: OK Script exists after flush: false
func (*ClusterClient) ScriptKill ¶
Kills the currently executing Lua script, assuming no write operation was yet performed by the script.
Note:
When in cluster mode, this command will be routed to all nodes.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
`OK` if script is terminated. Otherwise, throws an error.
Example (WithRoute) ¶
key := "{randomkey}1"
client := getExampleClusterClient()
// Create a route with our specified key
route := options.RouteOption{
Route: config.NewSlotKeyRoute(config.SlotTypePrimary, key),
}
// Try to kill scripts when no scripts are running
_, err := client.ScriptKillWithRoute(context.Background(), route)
if err != nil {
fmt.Println("Expected error:", err)
}
Output: Expected error: An error was signalled by the server: - NotBusy: No scripts in execution right now.
Example (WithoutRoute) ¶
client := getExampleClusterClient()
// Try to kill scripts when no scripts are running
_, err := client.ScriptKill(context.Background())
if err != nil {
fmt.Println("Expected error:", err)
}
Output: Expected error: An error was signalled by the server: - NotBusy: No scripts in execution right now.
func (*ClusterClient) ScriptKillWithRoute ¶
func (client *ClusterClient) ScriptKillWithRoute(ctx context.Context, route options.RouteOption) (string, error)
Kills the currently executing Lua script, assuming no write operation was yet performed by the script.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution.
route - Specifies the routing configuration for the command. The client will route the
command to the nodes defined by `route`.
Return value:
`OK` if script is terminated. Otherwise, throws an error.
func (*ClusterClient) ScriptShow ¶
ScriptShow returns the original source code of a script in the script cache.
Since:
Valkey 8.0.0
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. sha1 - The SHA1 digest of the script.
Return value:
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.
Example ¶
client := getExampleClusterClient()
// First, create and invoke a script
scriptText := "return 'Hello World'"
script := options.NewScript(scriptText)
_, err := client.InvokeScript(context.Background(), *script)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
// Now show the script source using ScriptShow
scriptSource, err := client.ScriptShow(context.Background(), script.GetHash())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
fmt.Println(scriptSource)
Output: return 'Hello World'
func (*ClusterClient) Select ¶ added in v2.1.1
Select changes the currently selected database.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. index - The index of the database to select.
Return value:
A simple `"OK"` response.
func (*ClusterClient) Set ¶
Set the given key with the given value. The return value is a response from Valkey containing the string "OK".
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to store. value - The value to store with the given key.
Return value:
`"OK"` response on success.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.Set(context.Background(), "my_key", "my_value")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*ClusterClient) SetBit ¶
func (client *ClusterClient) SetBit(ctx context.Context, key string, offset int64, value int64) (int64, error)
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`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the string. offset - The index of the bit to be set. value - The bit value to set at offset The value must be `0` or `1`.
Return value:
The bit value that was previously stored at offset.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.SetBit(context.Background(), "my_key", 1, 1) // initialize bit 1 with a value of 1
result, err := client.SetBit(context.Background(), "my_key", 1, 1) // set bit should return the previous value of bit 1
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 1
func (*ClusterClient) SetRange ¶
func (client *ClusterClient) SetRange(ctx context.Context, key string, offset int, value string) (int64, error)
Overwrites part of the string stored at key, starting at the specified byte's 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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the string to update. offset - The position in the string where value should be written. value - The string written with offset.
Return value:
The length of the string stored at `key` after it was modified.
Example (One) ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.Set(context.Background(), "my_key", "my_value")
result, err := client.SetRange(context.Background(), "my_key", 3, "example")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
value, _ := client.Get(context.Background(), "my_key")
fmt.Println(value.Value())
Output: 10 my_example
Example (Two) ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.Set(context.Background(), "my_key", "愛") // "愛" is a single character in UTF-8, but 3 bytes long
result, err := client.SetRange(context.Background(), "my_key", 1, "a")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 3
func (*ClusterClient) SetWithOptions ¶
func (client *ClusterClient) SetWithOptions( ctx context.Context, key string, value string, options options.SetOptions, ) (models.Result[string], error)
SetWithOptions sets the given key with the given value using the given options. The return value is dependent on the passed options. If the value is successfully set, "OK" is returned. If value isn't set because of constants.OnlyIfExists or constants.OnlyIfDoesNotExist conditions, models.CreateNilStringResult() is returned. If constants.ReturnOldValue is set, the old value is returned.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to store. value - The value to store with the given key. options - The [options.SetOptions].
Return value:
If the value is successfully set, return models.Result[string] containing "OK". If value isn't set because of ConditionalSet.OnlyIfExists or ConditionalSet.OnlyIfDoesNotExist or ConditionalSet.OnlyIfEquals conditions, return models.CreateNilStringResult(). If SetOptions.returnOldValue is set, return the old value as a String.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
options := options.NewSetOptions().
SetExpiry(options.NewExpiryIn(5 * time.Second))
result, err := client.SetWithOptions(context.Background(), "my_key", "my_value", *options)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.Value())
Output: OK
func (*ClusterClient) Sort ¶
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 the Client.SortStore or ClusterClient.SortStore function.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list, set, or sorted set to be sorted.
Return value:
An Array of sorted elements.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.LPush(context.Background(), "key1", []string{"1", "3", "2", "4"})
result1, err := client.Sort(context.Background(), "key1")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 4 [{1 false} {2 false} {3 false} {4 false}]
func (*ClusterClient) SortReadOnly ¶
func (client *ClusterClient) SortReadOnly(ctx context.Context, key string) ([]models.Result[string], error)
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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list, set, or sorted set to be sorted.
Return value:
An Array of sorted elements.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.LPush(context.Background(), "key1", []string{"1", "3", "2", "4"})
result1, err := client.SortReadOnly(context.Background(), "key1")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 4 [{1 false} {2 false} {3 false} {4 false}]
func (*ClusterClient) SortReadOnlyWithOptions ¶
func (client *ClusterClient) SortReadOnlyWithOptions( ctx context.Context, key string, options options.SortOptions, ) ([]models.Result[string], error)
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.
Note:
In cluster mode, if `key` 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. The use of SortOptions.byPattern and SortOptions.getPatterns in cluster mode is supported since Valkey version 8.0.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list, set, or sorted set to be sorted. sortOptions - The SortOptions type.
Return value:
An Array of sorted elements.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
opts := options.NewSortOptions().SetIsAlpha(false).SetOrderBy(options.ASC)
result, err := client.LPush(context.Background(), "key1", []string{"3", "1", "2"})
result1, err := client.SortReadOnlyWithOptions(context.Background(), "key1", *opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 3 [{1 false} {2 false} {3 false}]
func (*ClusterClient) SortStore ¶
func (client *ClusterClient) SortStore(ctx context.Context, key string, destination string) (int64, error)
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, apply transformations on sorted elements, and store the result in a new key. The SortStore command can be used to sort elements based on different criteria and apply transformations on sorted elements. To get the sort result without storing it into a key, see the Client.Sort and ClusterClient.Sort or Client.SortReadOnly and ClusterClient.SortReadOnly function.
Note:
In cluster mode, if `key` and `destination` 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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list, set, or sorted set to be sorted. destination - The key where the sorted result will be stored.
Return value:
The number of elements in the sorted key stored at destination.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.LPush(context.Background(), "{key}1", []string{"1", "3", "2", "4"})
result1, err := client.SortStore(context.Background(), "{key}1", "{key}2")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 4 4
func (*ClusterClient) SortStoreWithOptions ¶
func (client *ClusterClient) SortStoreWithOptions( ctx context.Context, key string, destination string, opts options.SortOptions, ) (int64, error)
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, apply transformations on sorted elements, and store the result in a new key. The SortStore command can be used to sort elements based on different criteria and apply transformations on sorted elements. To get the sort result without storing it into a key, see the Client.SortWithOptions and ClusterClient.SortWithOptions or Client.SortReadOnlyWithOptions and ClusterClient.SortReadOnlyWithOptions function.
Note:
In cluster mode, if `key` and `destination` 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. The use of SortOptions.byPattern and SortOptions.getPatterns in cluster mode is supported since Valkey version 8.0.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list, set, or sorted set to be sorted. destination - The key where the sorted result will be stored.
opts - The options.SortOptions type.
Return value:
The number of elements in the sorted key stored at destination.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
opts := options.NewSortOptions().SetIsAlpha(false).SetOrderBy(options.ASC)
result, err := client.LPush(context.Background(), "{key}1", []string{"3", "1", "2"})
result1, err := client.SortStoreWithOptions(context.Background(), "{key}1", "{key}2", *opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 3 3
func (*ClusterClient) SortWithOptions ¶
func (client *ClusterClient) SortWithOptions( ctx context.Context, key string, options options.SortOptions, ) ([]models.Result[string], error)
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 the Client.SortStoreWithOptions or ClusterClient.SortStoreWithOptions function.
Note:
In cluster mode, if `key` 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. The use of SortOptions.byPattern and SortOptions.getPatterns in cluster mode is supported since Valkey version 8.0.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the list, set, or sorted set to be sorted. sortOptions - The SortOptions type.
Return value:
An Array of sorted elements.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
opts := options.NewSortOptions().SetIsAlpha(false).SetOrderBy(options.ASC)
result, err := client.LPush(context.Background(), "key1", []string{"3", "1", "2"})
result1, err := client.SortWithOptions(context.Background(), "key1", *opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 3 [{1 false} {2 false} {3 false}]
func (*ClusterClient) Strlen ¶
Returns the length of the string value stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key to check its length.
Return value:
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 ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.Set(context.Background(), "my_key", "my_value")
result, err := client.Strlen(context.Background(), "my_key")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 8
func (*ClusterClient) Subscribe ¶ added in v2.3.0
Subscribe subscribes the client to the specified channels (blocking). This command updates the client's internal desired subscription state and waits for server confirmation.
Parameters:
ctx - The context for the operation.
channels - A slice of channel names to subscribe to.
timeoutMs - Maximum time in milliseconds to wait for server confirmation.
A value of 0 blocks indefinitely until confirmation.
Return value:
An error if the operation fails or times out.
Example:
err := client.Subscribe(ctx, []string{"channel1"}, 5000)
Subscribe subscribes the client to the specified channels (blocking). This command updates the client's internal desired subscription state and waits for server confirmation.
Parameters:
ctx - The context for the operation.
channels - A slice of channel names to subscribe to.
timeoutMs - Maximum time in milliseconds to wait for server confirmation.
A value of 0 blocks indefinitely until confirmation.
Return value:
An error if the operation fails or times out.
Example:
err := client.Subscribe(ctx, []string{"channel1", "channel2"}, 0)
func (*ClusterClient) SubscribeLazy ¶ added in v2.3.0
SubscribeLazy subscribes the client to the specified channels (non-blocking). This command updates the client's internal desired subscription state without waiting for server confirmation. It returns immediately after updating the local state. The client will attempt to subscribe asynchronously in the background.
Note: Use GetSubscriptions() to verify the actual server-side subscription state.
Parameters:
ctx - The context for the operation. channels - A slice of channel names to subscribe to.
Return value:
An error if the operation fails.
Example:
err := client.SubscribeLazy(ctx, []string{"channel1", "channel2"})
func (*ClusterClient) TTL ¶
TTL returns the remaining time to live of key that has a timeout, in seconds.
Parameters:
ctx - The context for controlling the command execution. key - The key to return its timeout.
Return value:
Returns TTL in seconds, `-2` if key does not exist, or `-1` if key exists but has no associated expiration.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.Set(context.Background(), "key", "someValue")
result1, err := client.TTL(context.Background(), "key")
_, err = client.ExpireAt(
context.Background(),
"key",
time.Now().Add(10*time.Second),
) // TTL("key") returns proper TTL in seconds
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK -1
func (*ClusterClient) Time ¶
Returns the server time.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
The current server time as a String array with two elements: A UNIX TIME and the amount of microseconds already elapsed in the current second. The returned array is in a [UNIX TIME, Microseconds already elapsed] format.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
timeMargin := int64(5)
clientTime := time.Now().Unix()
result, err := client.Time(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
serverTime, _ := strconv.ParseInt(result[0], 10, 64)
fmt.Println((serverTime - clientTime) < timeMargin)
Output: true
func (*ClusterClient) TimeWithOptions ¶
func (client *ClusterClient) TimeWithOptions( ctx context.Context, opts options.RouteOption, ) (models.ClusterValue[[]string], error)
Returns the server time. The command will be routed to a random node, unless Route in opts is provided.
See [valkey.io] for details.
Parameters:
ctx - The context for controlling the command execution. options - The [RouteOption] type.
Return value:
The current server time as a String array with two elements: A UNIX TIME and the amount of microseconds already elapsed in the current second. The returned array is in a [UNIX TIME, Microseconds already elapsed] format. [valkey.io]: https://valkey.io/commands/time/
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
route := config.Route(config.RandomRoute)
opts := options.RouteOption{
Route: route,
}
clusterResponse, err := client.TimeWithOptions(context.Background(), opts) // gives: {1 [1738714595 942076] map[]}
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(len(clusterResponse.SingleValue()) == 2)
Output: true
func (*ClusterClient) Touch ¶
Alters the last access time of a key(s). A key is ignored if it does not exist.
Note:
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.
Parameters:
ctx - The context for controlling the command execution. keys - The keys to update last access time.
Return value:
The number of keys that were updated.
[valkey.io]: Https://valkey.io/commands/touch/
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.Set(context.Background(), "key1", "someValue")
result1, err := client.Set(context.Background(), "key2", "someValue")
result2, err := client.Touch(context.Background(), []string{"key1", "key2", "key3"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: OK OK 2
func (*ClusterClient) Type ¶
Type returns the string representation of the type of the value stored at key. The different types that can be returned are: `"string"`, `"list"`, `"set"`, `"zset"`, `"hash"` and `"stream"`.
Parameters:
ctx - The context for controlling the command execution. key - The `key` to check its data type.
Return value:
If the `key` exists, the type of the stored value is returned. Otherwise, a `"none"` string is returned.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.Set(context.Background(), "key1", "someValue")
result1, err := client.Type(context.Background(), "key1")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: OK string
func (*ClusterClient) Unlink ¶
Unlink (delete) multiple keys from the database. A key is ignored if it does not exist. This command, similar to Client.Del and ClusterClient.Del, however, this command does not block the server.
Note:
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.
Parameters:
ctx - The context for controlling the command execution. keys - One or more keys to unlink.
Return value:
Return the number of keys that were unlinked.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.Set(context.Background(), "key1", "someValue")
result1, err := client.Set(context.Background(), "key2", "someValue")
result2, err := client.Unlink(context.Background(), []string{"key1", "key2", "key3"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: OK OK 2
func (*ClusterClient) Unsubscribe ¶ added in v2.3.0
func (client *ClusterClient) Unsubscribe(ctx context.Context, channels []string, timeoutMs int) error
Unsubscribe unsubscribes the client from the specified channels (blocking). This command updates the client's internal desired subscription state and waits for server confirmation. If no channels are specified (nil or empty slice), unsubscribes from all exact channels.
Parameters:
ctx - The context for the operation.
channels - A slice of channel names to unsubscribe from. Pass nil to unsubscribe from all.
timeoutMs - Maximum time in milliseconds to wait for server confirmation.
A value of 0 blocks indefinitely until confirmation.
Return value:
An error if the operation fails or times out.
Example:
err := client.Unsubscribe(ctx, []string{"channel1"}, 5000)
err := client.Unsubscribe(ctx, nil, 5000) // Unsubscribe from all
func (*ClusterClient) UnsubscribeLazy ¶ added in v2.3.0
UnsubscribeLazy unsubscribes the client from the specified channels (non-blocking). This command updates the client's internal desired subscription state without waiting for server confirmation. It returns immediately after updating the local state. If no channels are specified (nil), unsubscribes from all exact channels.
Parameters:
ctx - The context for the operation. channels - A slice of channel names to unsubscribe from. Pass nil to unsubscribe from all.
Return value:
An error if the operation fails.
Example:
err := client.UnsubscribeLazy(ctx, []string{"channel1"})
err := client.UnsubscribeLazy(ctx, nil) // Unsubscribe from all
func (*ClusterClient) Unwatch ¶
func (client *ClusterClient) Unwatch(ctx context.Context) (string, error)
Flushes all the previously watched keys for a transaction. Executing a transaction will automatically flush all previously watched keys. The command will be routed to all primary nodes.
See valkey.io and Valkey GLIDE Documentation for details.
Parameters:
ctx - The context for controlling the command execution.
Return value:
A simple "OK" response.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.Unwatch(context.Background())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*ClusterClient) UnwatchWithOptions ¶
func (client *ClusterClient) UnwatchWithOptions(ctx context.Context, route options.RouteOption) (string, error)
Flushes all the previously watched keys for a transaction. Executing a transaction will automatically flush all previously watched keys.
See valkey.io and Valkey GLIDE Documentation for details.
Parameters:
ctx - The context for controlling the command execution.
route - Specifies the routing configuration for the command. The client will route the
command to the nodes defined by `route`.
Return value:
A simple "OK" response.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.UnwatchWithOptions(context.Background(), options.RouteOption{Route: config.AllNodes})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: OK
func (*ClusterClient) UpdateConnectionPassword ¶
func (client *ClusterClient) UpdateConnectionPassword(ctx context.Context, password string, immediateAuth bool) (string, error)
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.
Note:
This method updates the client's internal password configuration and does not perform password rotation on the server side.
Parameters:
ctx - The context for controlling the command execution. password - The new password to update the connection with. immediateAuth - immediateAuth A boolean flag. If true, the client will authenticate immediately with the new password against all connections, Using AUTH command. If password supplied is an empty string, the client will not perform auth and a warning will be returned. The default is `false`.
Return value:
`"OK"` response on success.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
response, err := client.UpdateConnectionPassword(context.Background(), "", false)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(response)
Output: OK
func (*ClusterClient) Wait ¶
func (client *ClusterClient) Wait(ctx context.Context, numberOfReplicas int64, timeout time.Duration) (int64, error)
Wait blocks the current client until all the previous write commands are successfully transferred and acknowledged by at least the specified number of replicas or if the timeout is reached, whichever is earlier.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. numberOfReplicas - The number of replicas to reach. timeout - The timeout value. A value of `0` will block indefinitely.
Return value:
The number of replicas reached by all the writes performed in the context of the current connection.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.Set(context.Background(), "key1", "someValue")
result, err := client.Wait(context.Background(), 2, 1*time.Second)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result < 10)
Output: true
func (*ClusterClient) Watch ¶
Marks the given keys to be watched for conditional execution of an atomic batch (Transaction). Transactions will only execute commands if the watched keys are not modified before execution of the transaction.
See valkey.io and Valkey GLIDE Documentation for details.
Note:
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.
Parameters:
ctx - The context for controlling the command execution. keys - The keys to watch.
Return value:
A simple "OK" response.
Example (ChangedKey) ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
// Example 1: key is changed before transaction and transaction didn't execute
result, err := client.Watch(context.Background(), []string{"sampleKey"})
fmt.Println("Watch result: ", result)
result, err = client.Set(context.Background(), "sampleKey", "foobar")
fmt.Println("Set result: ", result)
transaction := pipeline.NewClusterBatch(true)
transaction.Set("sampleKey", "value")
// Set command retry parameters
result1, err := client.Exec(context.Background(), *transaction, false)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Transaction result is `nil`, it is not executed at all
fmt.Printf("Transation result: %#v", result1)
Output: Watch result: OK Set result: OK Transation result: []interface {}(nil)
Example (UnchangedKey) ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
// Example 2: key is unchanged before transaction
result, err := client.Watch(context.Background(), []string{"sampleKey"})
fmt.Println("Watch result: ", result)
transaction := pipeline.NewClusterBatch(true)
transaction.Set("sampleKey", "value")
// Set command retry parameters
result1, err := client.Exec(context.Background(), *transaction, false)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println("Transation result: ", result1)
Output: Watch result: OK Transation result: [OK]
func (*ClusterClient) XAck ¶
func (client *ClusterClient) XAck(ctx context.Context, key string, group string, ids []string) (int64, error)
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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. group - he consumer group name. ids - Stream entry IDs to acknowledge and purge messages.
Return value:
The number of messages that were successfully acknowledged.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "12345"
group := "g12345"
consumer := "c12345"
streamId, _ := client.XAdd(
context.Background(),
key,
[]models.FieldValue{
{Field: "entry1_field1", Value: "entry1_value1"},
{Field: "entry1_field2", Value: "entry1_value2"},
},
)
client.XGroupCreate(context.Background(), key, group, "0")
client.XGroupCreateConsumer(context.Background(), key, group, consumer)
client.XReadGroup(context.Background(), group, consumer, map[string]string{key: ">"})
count, err := client.XAck(
context.Background(),
key,
group,
[]string{streamId},
) // ack the message and remove it from the pending list
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(count)
Output: 1
func (*ClusterClient) XAdd ¶
func (client *ClusterClient) XAdd(ctx context.Context, key string, values []models.FieldValue) (string, error)
Adds an entry to the specified stream stored at `key`. If the `key` doesn't exist, the stream is created.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. values - Field-value pairs to be added to the entry.
Return value:
The id of the added entry.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.XAdd(context.Background(), "mystream", []models.FieldValue{
{Field: "key1", Value: "value1"},
{Field: "key2", Value: "value2"},
})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
matches, _ := regexp.Match(
`^\d{13}-0$`,
[]byte(result),
) // matches a number that is 13 digits long followed by "-0"
fmt.Println(matches)
Output: true
func (*ClusterClient) XAddWithOptions ¶
func (client *ClusterClient) XAddWithOptions( ctx context.Context, key string, values []models.FieldValue, options options.XAddOptions, ) (models.Result[string], error)
Adds an entry to the specified stream stored at `key`. If the `key` doesn't exist, the stream is created.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. values - Field-value pairs to be added to the entry. options - Stream add options.
Return value:
The id of the added entry, or `nil` if [options.XAddOptions.MakeStream] is set to `false` and no stream with the matching `key` exists.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
options := options.NewXAddOptions().SetId("1000-50")
values := []models.FieldValue{
{Field: "key1", Value: "value1"},
{Field: "key2", Value: "value2"},
}
result, err := client.XAddWithOptions(context.Background(), "mystream", values, *options)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result.Value())
Output: 1000-50
func (*ClusterClient) XAutoClaim ¶
func (client *ClusterClient) XAutoClaim( ctx context.Context, key string, group string, consumer string, minIdleTime time.Duration, start string, ) (models.XAutoClaimResponse, error)
Transfers ownership of pending stream entries that match the specified criteria.
Since:
Valkey 6.2.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. group - The consumer group name. consumer - The group consumer. minIdleTime - The minimum idle time for the message to be claimed. start - Filters the claimed entries to those that have an ID equal or greater than the specified value.
Return value:
An object 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 array of the claimed entries as `[]models.StreamEntry`.
- If you are using Valkey 7.0.0 or above, the response will also include an array 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.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := uuid.NewString()
group := uuid.NewString()
consumer := uuid.NewString()
client.XGroupCreateWithOptions(context.Background(), key, group, "0", *options.NewXGroupCreateOptions().SetMakeStream())
client.XGroupCreateConsumer(context.Background(), key, group, consumer)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{
{Field: "entry1_field1", Value: "entry1_value1"},
{Field: "entry1_field2", Value: "entry1_value2"},
},
*options.NewXAddOptions().SetId("0-1"),
)
client.XAddWithOptions(context.Background(),
key,
[]models.FieldValue{{Field: "entry2_field1", Value: "entry2_value1"}},
*options.NewXAddOptions().SetId("0-2"),
)
client.XReadGroup(context.Background(), group, consumer, map[string]string{key: ">"})
response, err := client.XAutoClaim(context.Background(), key, group, consumer, 0, "0-1")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(response)
Output: {0-0 [{0-1 [{entry1_field1 entry1_value1} {entry1_field2 entry1_value2}]} {0-2 [{entry2_field1 entry2_value1}]}] []}
func (*ClusterClient) XAutoClaimJustId ¶
func (client *ClusterClient) XAutoClaimJustId( ctx context.Context, key string, group string, consumer string, minIdleTime time.Duration, start string, ) (models.XAutoClaimJustIdResponse, error)
Transfers ownership of pending stream entries that match the specified criteria.
Since:
Valkey 6.2.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. group - The consumer group name. consumer - The group consumer. minIdleTime - The minimum idle time for the message to be claimed. start - Filters the claimed entries to those that have an ID equal or greater than the specified value.
Return value:
An object 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.
- An array of IDs for the claimed entries.
- If you are using Valkey 7.0.0 or above, the response will also include an array 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.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := uuid.NewString()
group := uuid.NewString()
consumer := uuid.NewString()
client.XGroupCreateWithOptions(context.Background(), key, group, "0", *options.NewXGroupCreateOptions().SetMakeStream())
client.XGroupCreateConsumer(context.Background(), key, group, consumer)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{
{Field: "entry1_field1", Value: "entry1_value1"},
{Field: "entry1_field2", Value: "entry1_value2"},
},
*options.NewXAddOptions().SetId("0-1"),
)
client.XAddWithOptions(context.Background(),
key,
[]models.FieldValue{{Field: "entry2_field1", Value: "entry2_value1"}},
*options.NewXAddOptions().SetId("0-2"),
)
client.XReadGroup(context.Background(), group, consumer, map[string]string{key: ">"})
response, err := client.XAutoClaimJustId(context.Background(), key, group, consumer, 0, "0-0")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(response)
Output: {0-0 [0-1 0-2] []}
func (*ClusterClient) XAutoClaimJustIdWithOptions ¶
func (client *ClusterClient) XAutoClaimJustIdWithOptions( ctx context.Context, key string, group string, consumer string, minIdleTime time.Duration, start string, opts options.XAutoClaimOptions, ) (models.XAutoClaimJustIdResponse, error)
Transfers ownership of pending stream entries that match the specified criteria.
Since:
Valkey 6.2.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. group - The consumer group name. consumer - The group consumer. minIdleTime - The minimum idle time for the message to be claimed. start - Filters the claimed entries to those that have an ID equal or greater than the specified value. opts - Options detailing how to read the stream. Count has a default value of 100.
Return value:
An object 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.
- An array of IDs for the claimed entries.
- If you are using Valkey 7.0.0 or above, the response will also include an array 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.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := uuid.NewString()
group := uuid.NewString()
consumer := uuid.NewString()
client.XGroupCreateWithOptions(context.Background(), key, group, "0", *options.NewXGroupCreateOptions().SetMakeStream())
client.XGroupCreateConsumer(context.Background(), key, group, consumer)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{
{Field: "entry1_field1", Value: "entry1_value1"},
{Field: "entry1_field2", Value: "entry1_value2"},
},
*options.NewXAddOptions().SetId("0-1"),
)
client.XAddWithOptions(context.Background(),
key,
[]models.FieldValue{{Field: "entry2_field1", Value: "entry2_value1"}},
*options.NewXAddOptions().SetId("0-2"),
)
client.XReadGroup(context.Background(), group, consumer, map[string]string{key: ">"})
options := options.NewXAutoClaimOptions().SetCount(1)
response, err := client.XAutoClaimJustIdWithOptions(context.Background(), key, group, consumer, 0, "0-1", *options)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(response)
Output: {0-2 [0-1] []}
func (*ClusterClient) XAutoClaimWithOptions ¶
func (client *ClusterClient) XAutoClaimWithOptions( ctx context.Context, key string, group string, consumer string, minIdleTime time.Duration, start string, options options.XAutoClaimOptions, ) (models.XAutoClaimResponse, error)
Transfers ownership of pending stream entries that match the specified criteria.
Since:
Valkey 6.2.0 and above.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. group - The consumer group name. consumer - The group consumer. minIdleTime - The minimum idle time for the message to be claimed. start - Filters the claimed entries to those that have an ID equal or greater than the specified value. options - Options detailing how to read the stream. Count has a default value of 100.
Return value:
An object 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 array of the claimed entries as `[]models.StreamEntry`.
- If you are using Valkey 7.0.0 or above, the response will also include an array 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.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := uuid.NewString()
group := uuid.NewString()
consumer := uuid.NewString()
client.XGroupCreateWithOptions(context.Background(), key, group, "0", *options.NewXGroupCreateOptions().SetMakeStream())
client.XGroupCreateConsumer(context.Background(), key, group, consumer)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{
{Field: "entry1_field1", Value: "entry1_value1"},
{Field: "entry1_field2", Value: "entry1_value2"},
},
*options.NewXAddOptions().SetId("0-1"),
)
client.XAddWithOptions(context.Background(),
key,
[]models.FieldValue{{Field: "entry2_field1", Value: "entry2_value1"}},
*options.NewXAddOptions().SetId("0-2"),
)
client.XReadGroup(context.Background(), group, consumer, map[string]string{key: ">"})
options := options.NewXAutoClaimOptions().SetCount(1)
response, err := client.XAutoClaimWithOptions(context.Background(), key, group, consumer, 0, "0-1", *options)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(response)
Output: {0-2 [{0-1 [{entry1_field1 entry1_value1} {entry1_field2 entry1_value2}]}] []}
func (*ClusterClient) XClaim ¶
func (client *ClusterClient) XClaim( ctx context.Context, key string, group string, consumer string, minIdleTime time.Duration, ids []string, ) (map[string]models.XClaimResponse, error)
Changes the ownership of a pending message.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. group - The name of the consumer group. consumer - The name of the consumer. minIdleTime - The minimum idle time. ids - The ids of the entries to claim.
Return value:
A map[string]models.XClaimResponse where: - Each key is a message/entry ID - Each value is an XClaimResponse containing: - Fields: []FieldValue array of field-value pairs for the claimed entry
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "12345"
streamId := "12345-1"
group := "g12345"
consumer1 := "c12345-1"
consumer2 := "c12345-2"
client.XGroupCreateWithOptions(context.Background(), key, group, "0", *options.NewXGroupCreateOptions().SetMakeStream())
client.XGroupCreateConsumer(context.Background(), key, group, consumer1)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{
{Field: "entry1_field1", Value: "entry1_value1"},
{Field: "entry1_field2", Value: "entry1_value2"},
},
*options.NewXAddOptions().SetId(streamId),
)
client.XReadGroup(context.Background(), group, consumer1, map[string]string{key: ">"})
result, err := client.XPendingWithOptions(context.Background(),
key,
group,
*options.NewXPendingOptions("-", "+", 10).SetConsumer(consumer1),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
if len(result) == 0 {
fmt.Println("No pending messages")
return
}
response, err := client.XClaim(
context.Background(),
key,
group,
consumer2,
time.Duration(result[0].IdleTime)*time.Millisecond,
[]string{result[0].Id},
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Printf("Claimed %d message\n", len(response))
// Access fields from the claimed message
for id, claimResponse := range response {
fmt.Printf("Message ID: %s has %d fields\n", id, len(claimResponse.Fields))
}
Output: Claimed 1 message Message ID: 12345-1 has 2 fields
func (*ClusterClient) XClaimJustId ¶
func (client *ClusterClient) XClaimJustId( ctx context.Context, key string, group string, consumer string, minIdleTime time.Duration, ids []string, ) ([]string, error)
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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. group - The name of the consumer group. consumer - The name of the consumer. minIdleTime - The minimum idle time. ids - The ids of the entries to claim. options - Stream claim options.
Return value:
An array of the ids of the entries that were claimed by the consumer.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "12345"
streamId := "12345-1"
group := "g12345"
consumer1 := "c12345-1"
consumer2 := "c12345-2"
client.XGroupCreateWithOptions(context.Background(), key, group, "0", *options.NewXGroupCreateOptions().SetMakeStream())
client.XGroupCreateConsumer(context.Background(), key, group, consumer1)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{
{Field: "entry1_field1", Value: "entry1_value1"},
{Field: "entry1_field2", Value: "entry1_value2"},
},
*options.NewXAddOptions().SetId(streamId),
)
client.XReadGroup(context.Background(), group, consumer1, map[string]string{key: ">"})
result, err := client.XPendingWithOptions(context.Background(),
key,
group,
*options.NewXPendingOptions("-", "+", 10).SetConsumer(consumer1),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
if len(result) == 0 {
fmt.Println("No pending messages")
return
}
response, err := client.XClaimJustId(
context.Background(),
key,
group,
consumer2,
time.Duration(result[0].IdleTime)*time.Millisecond,
[]string{result[0].Id},
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(response)
Output: [12345-1]
func (*ClusterClient) XClaimJustIdWithOptions ¶
func (client *ClusterClient) XClaimJustIdWithOptions( ctx context.Context, key string, group string, consumer string, minIdleTime time.Duration, ids []string, opts options.XClaimOptions, ) ([]string, error)
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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. group - The name of the consumer group. consumer - The name of the consumer. minIdleTime - The minimum idle time. ids - The ids of the entries to claim. options - Stream claim options.
Return value:
An array of the ids of the entries that were claimed by the consumer.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "12345"
streamId := "12345-1"
group := "g12345"
consumer1 := "c12345-1"
consumer2 := "c12345-2"
client.XGroupCreateWithOptions(context.Background(), key, group, "0", *options.NewXGroupCreateOptions().SetMakeStream())
client.XGroupCreateConsumer(context.Background(), key, group, consumer1)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{
{Field: "entry1_field1", Value: "entry1_value1"},
{Field: "entry1_field2", Value: "entry1_value2"},
},
*options.NewXAddOptions().SetId(streamId),
)
client.XReadGroup(context.Background(), group, consumer1, map[string]string{key: ">"})
result, err := client.XPendingWithOptions(context.Background(),
key,
group,
*options.NewXPendingOptions("-", "+", 10).SetConsumer(consumer1),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
if len(result) == 0 {
fmt.Println("No pending messages")
return
}
opts := options.NewXClaimOptions().SetRetryCount(3)
response, err := client.XClaimJustIdWithOptions(
context.Background(),
key,
group,
consumer2,
time.Duration(result[0].IdleTime)*time.Millisecond,
[]string{result[0].Id},
*opts,
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(response)
Output: [12345-1]
func (*ClusterClient) XClaimWithOptions ¶
func (client *ClusterClient) XClaimWithOptions( ctx context.Context, key string, group string, consumer string, minIdleTime time.Duration, ids []string, opts options.XClaimOptions, ) (map[string]models.XClaimResponse, error)
Changes the ownership of a pending message.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. group - The name of the consumer group. consumer - The name of the consumer. minIdleTime - The minimum idle time. ids - The ids of the entries to claim. options - Stream claim options.
Return value:
A map[string]models.XClaimResponse where: - Each key is a message/entry ID - Each value is an XClaimResponse containing: - Fields: []FieldValue array of field-value pairs for the claimed entry
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "12345"
streamId := "12345-1"
group := "g12345"
consumer1 := "c12345-1"
consumer2 := "c12345-2"
client.XGroupCreateWithOptions(context.Background(), key, group, "0", *options.NewXGroupCreateOptions().SetMakeStream())
client.XGroupCreateConsumer(context.Background(), key, group, consumer1)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{
{Field: "entry1_field1", Value: "entry1_value1"},
{Field: "entry1_field2", Value: "entry1_value2"},
},
*options.NewXAddOptions().SetId(streamId),
)
client.XReadGroup(context.Background(), group, consumer1, map[string]string{key: ">"})
result, err := client.XPendingWithOptions(context.Background(),
key,
group,
*options.NewXPendingOptions("-", "+", 10).SetConsumer(consumer1),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
if len(result) == 0 {
fmt.Println("No pending messages")
return
}
opts := options.NewXClaimOptions().SetRetryCount(3)
response, err := client.XClaimWithOptions(
context.Background(),
key,
group,
consumer2,
time.Duration(result[0].IdleTime)*time.Millisecond,
[]string{result[0].Id},
*opts,
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Printf("Claimed %d message\n", len(response))
// Access fields from the claimed message
for id, claimResponse := range response {
fmt.Printf("Message ID: %s with retry count: %d\n", id, 3)
// Print a sample field if available
if len(claimResponse.Fields) > 0 {
for _, pair := range claimResponse.Fields {
fmt.Printf("Field: %s, Value: %s\n", pair.Field, pair.Value)
break // Just print the first field as an example
}
}
}
Output: Claimed 1 message Message ID: 12345-1 with retry count: 3 Field: entry1_field1, Value: entry1_value1
func (*ClusterClient) XDel ¶
Removes the specified entries by id from a stream, and returns the number of entries deleted.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. ids - An array of entry ids.
Return value:
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.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "12345"
client.XAddWithOptions(context.Background(),
key,
[]models.FieldValue{{Field: "field1", Value: "value1"}, {Field: "field2", Value: "value2"}},
*options.NewXAddOptions().SetId("0-1"),
)
count, err := client.XDel(context.Background(), key, []string{"0-1", "0-2", "0-3"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(count)
Output: 1
func (*ClusterClient) XGroupCreate ¶
func (client *ClusterClient) XGroupCreate(ctx context.Context, key string, group string, id string) (string, error)
Creates a new consumer group uniquely identified by `group` for the stream stored at `key`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
key - The key of the stream.
group - The newly created consumer group name.
id - 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.
Return value:
`"OK"`.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "12345"
streamId := "12345-1"
group := "g12345"
client.XAddWithOptions(context.Background(),
key,
[]models.FieldValue{{Field: "field1", Value: "value1"}, {Field: "field2", Value: "value2"}},
*options.NewXAddOptions().SetId(streamId),
) // This will create the stream if it does not exist
response, err := client.XGroupCreate(context.Background(), key, group, "0") // create the group (no MKSTREAM needed)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(response)
Output: OK
func (*ClusterClient) XGroupCreateConsumer ¶
func (client *ClusterClient) XGroupCreateConsumer( ctx context.Context, key string, group string, consumer string, ) (bool, error)
XGroupCreateConsumer creates a consumer named `consumer` in the consumer group `group` for the stream stored at `key`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. group - The consumer group name. consumer - The newly created consumer.
Return value:
Returns `true` if the consumer is created. Otherwise, returns `false`.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "12345"
group := "g12345"
consumer := "c12345"
opts := options.NewXGroupCreateOptions().SetMakeStream()
client.XGroupCreateWithOptions(context.Background(), key, group, "0", *opts) // create the group (no MKSTREAM needed)
success, err := client.XGroupCreateConsumer(context.Background(), key, group, consumer)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(success)
Output: true
func (*ClusterClient) XGroupCreateWithOptions ¶
func (client *ClusterClient) XGroupCreateWithOptions( ctx context.Context, key string, group string, id string, opts options.XGroupCreateOptions, ) (string, error)
Creates a new consumer group uniquely identified by `group` for the stream stored at `key`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
key - The key of the stream.
group - The newly created consumer group name.
id - 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.
opts - The options for the command. See [options.XGroupCreateOptions] for details.
Return value:
`"OK"`.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "12345"
group := "g12345"
opts := options.NewXGroupCreateOptions().SetMakeStream()
response, err := client.XGroupCreateWithOptions(
context.Background(),
key,
group,
"0",
*opts,
) // create the group (no MKSTREAM needed)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(response)
Output: OK
func (*ClusterClient) XGroupDelConsumer ¶
func (client *ClusterClient) XGroupDelConsumer( ctx context.Context, key string, group string, consumer string, ) (int64, error)
XGroupDelConsumer deletes a consumer named `consumer` in the consumer group `group`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. group - The consumer group name. consumer - The consumer to delete.
Return value:
The number of pending messages the `consumer` had before it was deleted.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "12345"
group := "g12345"
consumer := "c12345"
streamId := "12345-1"
client.XAddWithOptions(context.Background(),
key,
[]models.FieldValue{{Field: "field1", Value: "value1"}, {Field: "field2", Value: "value2"}},
*options.NewXAddOptions().SetId(streamId),
)
client.XGroupCreate(context.Background(), key, group, "0")
client.XGroupCreateConsumer(context.Background(), key, group, consumer)
client.XReadGroup(context.Background(), group, consumer, map[string]string{key: ">"})
count, err := client.XGroupDelConsumer(context.Background(), key, group, consumer)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println("Consumer deleted. Messages pending:", count)
Output: Consumer deleted. Messages pending: 1
func (*ClusterClient) XGroupDestroy ¶
func (client *ClusterClient) XGroupDestroy(ctx context.Context, key string, group string) (bool, error)
Destroys the consumer group `group` for the stream stored at `key`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. group - The consumer group name to delete.
Return value:
`true` if the consumer group is destroyed. Otherwise, `false`.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "12345"
group := "g12345"
opts := options.NewXGroupCreateOptions().SetMakeStream()
client.XGroupCreateWithOptions(context.Background(), key, group, "0", *opts) // create the group (no MKSTREAM needed)
success, err := client.XGroupDestroy(context.Background(), key, group) // destroy the group
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(success)
Output: true
func (*ClusterClient) XGroupSetId ¶
func (client *ClusterClient) XGroupSetId(ctx context.Context, key string, group string, id string) (string, error)
Sets the last delivered ID for a consumer group.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. group - The consumer group name. id - The stream entry ID that should be set as the last delivered ID for the consumer group.
Return value:
`"OK"`.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "12345"
streamId := "12345-1"
group := "g12345"
consumer := "c12345"
client.XGroupCreateWithOptions(context.Background(), key, group, "0", *options.NewXGroupCreateOptions().SetMakeStream())
client.XGroupCreateConsumer(context.Background(), key, group, consumer)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{
{Field: "entry1_field1", Value: "entry1_value1"},
{Field: "entry1_field2", Value: "entry1_value2"},
},
*options.NewXAddOptions().SetId(streamId),
)
client.XReadGroup(context.Background(), group, consumer, map[string]string{key: ">"})
client.XAck(context.Background(), key, group, []string{streamId}) // ack the message and remove it from the pending list
client.XGroupSetId(
context.Background(),
key,
group,
"0-0",
) // reset the last acknowledged message to 0-0
client.XReadGroup(context.Background(), group, consumer, map[string]string{key: ">"}) // read the group again
summary, err := client.XPending(
context.Background(),
key,
group,
) // get the pending messages, which should include the entry we previously acked
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
jsonSummary, _ := json.Marshal(summary)
fmt.Println(string(jsonSummary))
Output: {"NumOfMessages":1,"StartId":{},"EndId":{},"ConsumerMessages":[{"ConsumerName":"c12345","MessageCount":1}]}
func (*ClusterClient) XGroupSetIdWithOptions ¶
func (client *ClusterClient) XGroupSetIdWithOptions( ctx context.Context, key string, group string, id string, opts options.XGroupSetIdOptions, ) (string, error)
Sets the last delivered ID for a consumer group.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. group - The consumer group name. id - The stream entry ID that should be set as the last delivered ID for the consumer group. opts - The options for the command. See [options.XGroupSetIdOptions] for details.
Return value:
`"OK"`.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "12345"
streamId1 := "12345-1"
streamId2 := "12345-2"
group := "g12345"
consumer := "c12345"
client.XGroupCreateWithOptions(context.Background(), key, group, "0", *options.NewXGroupCreateOptions().SetMakeStream())
client.XGroupCreateConsumer(context.Background(), key, group, consumer)
client.XAddWithOptions(context.Background(),
key,
[]models.FieldValue{{Field: "field1", Value: "value1"}, {Field: "field2", Value: "value2"}},
*options.NewXAddOptions().SetId(streamId1),
)
client.XAddWithOptions(context.Background(),
key,
[]models.FieldValue{{Field: "field3", Value: "value3"}, {Field: "field4", Value: "value4"}},
*options.NewXAddOptions().SetId(streamId2),
)
client.XReadGroup(context.Background(), group, consumer, map[string]string{key: ">"})
client.XAck(
context.Background(),
key,
group,
[]string{streamId1, streamId2},
) // ack the message and remove it from the pending list
opts := options.NewXGroupSetIdOptionsOptions().SetEntriesRead(1)
client.XGroupSetIdWithOptions(
context.Background(),
key,
group,
"0-0",
*opts,
) // reset the last acknowledged message to 0-0
client.XReadGroup(context.Background(), group, consumer, map[string]string{key: ">"}) // read the group again
summary, err := client.XPending(
context.Background(),
key,
group,
) // get the pending messages, which should include the entry we previously acked
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
jsonSummary, _ := json.Marshal(summary)
fmt.Println(string(jsonSummary))
Output: {"NumOfMessages":2,"StartId":{},"EndId":{},"ConsumerMessages":[{"ConsumerName":"c12345","MessageCount":2}]}
func (*ClusterClient) XInfoConsumers ¶
func (client *ClusterClient) XInfoConsumers(ctx context.Context, key string, group string) ([]models.XInfoConsumerInfo, error)
Returns the list of all consumers and their attributes for the given consumer group of the stream stored at `key`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. group - The consumer group name.
Return value:
An array of [models.XInfoConsumerInfo], where each element contains the attributes of a consumer for the given consumer group of the stream at `key`.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := uuid.NewString()
group := "myGroup"
consumer := "myConsumer"
// create an empty stream with a group
client.XGroupCreateWithOptions(context.Background(), key, group, "0-0", *options.NewXGroupCreateOptions().SetMakeStream())
// add couple of entries
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{{Field: "e1_f1", Value: "e1_v1"}, {Field: "e1_f2", Value: "e1_v2"}},
*options.NewXAddOptions().SetId("0-1"),
)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{{Field: "e2_f1", Value: "e2_v1"}, {Field: "e2_f2", Value: "e2_v2"}},
*options.NewXAddOptions().SetId("0-2"),
)
// read them
client.XReadGroupWithOptions(
context.Background(),
group,
consumer,
map[string]string{key: ">"},
*options.NewXReadGroupOptions().SetCount(1),
)
// get the info
time.Sleep(100 * time.Millisecond)
response, err := client.XInfoConsumers(context.Background(), key, group)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Expanded:
fmt.Printf("Consumer name: %s\n", response[0].Name)
fmt.Printf("PEL count: %d\n", response[0].Pending)
// exact values of `Idle` and `Inactive` depend on timing
fmt.Printf("Idle > 0: %t\n", response[0].Idle > 0)
fmt.Printf("Inactive > 0: %t\n", response[0].Inactive.Value() > 0) // Added in version 7.0.0
Output: Consumer name: myConsumer PEL count: 1 Idle > 0: true Inactive > 0: true
func (*ClusterClient) XInfoGroups ¶
func (client *ClusterClient) XInfoGroups(ctx context.Context, key string) ([]models.XInfoGroupInfo, error)
Returns the list of all consumer groups and their attributes for the stream stored at `key`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream.
Return value:
An array of [models.XInfoGroupInfo], where each element represents the attributes of a consumer group for the stream at `key`.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := uuid.NewString()
group := "myGroup"
// create an empty stream with a group
client.XGroupCreateWithOptions(context.Background(), key, group, "0-0", *options.NewXGroupCreateOptions().SetMakeStream())
// add couple of entries
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{{Field: "e1_f1", Value: "e1_v1"}, {Field: "e1_f2", Value: "e1_v2"}},
*options.NewXAddOptions().SetId("0-1"),
)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{{Field: "e2_f1", Value: "e2_v1"}, {Field: "e2_f2", Value: "e2_v2"}},
*options.NewXAddOptions().SetId("0-2"),
)
// read them
client.XReadGroup(context.Background(), group, "myConsumer", map[string]string{key: ">"})
// get the info
response, err := client.XInfoGroups(context.Background(), key)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(response)
// Expanded:
fmt.Printf("Group name: %s\n", response[0].Name)
fmt.Printf("Consumers count: %d\n", response[0].Consumers)
fmt.Printf("PEL count: %d\n", response[0].Pending)
fmt.Printf("Last delivered message: %s\n", response[0].LastDeliveredId)
fmt.Printf("Entries read: %d\n", response[0].EntriesRead.Value()) // Added in version 7.0.0
fmt.Printf("Lag: %d\n", response[0].Lag.Value()) // Added in version 7.0.0
Output: [{myGroup 1 2 0-2 {2 false} {0 false}}] Group name: myGroup Consumers count: 1 PEL count: 2 Last delivered message: 0-2 Entries read: 2 Lag: 0
func (*ClusterClient) XInfoStream ¶
func (client *ClusterClient) XInfoStream(ctx context.Context, key string) (models.XInfoStreamResponse, error)
Returns information about the stream stored at `key`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream.
Return value:
A [models.XInfoStreamResponse] containing information about the stream stored at key: - Length: the number of entries in the stream - RadixTreeKeys: the number of keys in the underlying radix data structure - RadixTreeNodes: the number of nodes in the underlying radix data structure - Groups: the number of consumer groups defined for the stream - LastGeneratedID: the ID of the least-recently entry that was added to the stream - MaxDeletedEntryID: the maximal entry ID that was deleted from the stream - EntriesAdded: the count of all entries added to the stream during its lifetime - FirstEntry: the ID and field-value tuples of the first entry in the stream - LastEntry: the ID and field-value tuples of the last entry in the stream
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "12345"
streamId1 := "12345-1"
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{{Field: "field1", Value: "value1"}},
*options.NewXAddOptions().SetId(streamId1),
)
response, err := client.XInfoStream(context.Background(), key)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Response Structure is as follows:
// {
// "entries-added": 1,
// "first-entry": [
// "12345-1",
// [
// "field1",
// "value1"
// ]
// ],
// "groups": 0,
// "last-entry": [
// "12345-1",
// [
// "field1",
// "value1"
// ]
// ],
// "last-generated-id": "12345-1",
// "length": 1,
// "max-deleted-entry-id": "0-0",
// "radix-tree-keys": 1,
// "radix-tree-nodes": 2,
// "recorded-first-entry-id": "12345-1"
// }
// Output a few entries from the return object.
fmt.Printf("Entries Added: %d\n", response.EntriesAdded.Value())
fmt.Printf("Groups: %d\n", response.Groups)
fmt.Printf("Last generated Id: %s\n", response.LastGeneratedID)
fmt.Printf("Length: %d\n", response.Length)
Output: Entries Added: 1 Groups: 0 Last generated Id: 12345-1 Length: 1
func (*ClusterClient) XInfoStreamFullWithOptions ¶
func (client *ClusterClient) XInfoStreamFullWithOptions( ctx context.Context, key string, opts options.XInfoStreamOptions, ) (models.XInfoStreamFullOptionsResponse, error)
Returns detailed information about the stream stored at `key`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. opts - Stream info options.
Return value:
A detailed stream information for the given `key`. See the example for a sample response.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "12345"
for i := 1; i <= 5; i++ {
field := fmt.Sprintf("field%d", i)
value := fmt.Sprintf("value%d", i)
streamId := fmt.Sprintf("%s-%d", key, i)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{{Field: field, Value: value}},
*options.NewXAddOptions().SetId(streamId),
)
}
options := options.NewXInfoStreamOptions().SetCount(2)
response, err := client.XInfoStreamFullWithOptions(context.Background(), key, *options)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Print some of response values
fmt.Printf("Total entries: %d\n", len(response.Entries))
fmt.Printf("Entry 1 ID: %s\n", response.Entries[0].ID)
fmt.Printf("Entry 1 Field: %s\n", response.Entries[0].Fields[0])
fmt.Printf("Entry 2 ID: %s\n", response.Entries[1].ID)
fmt.Printf("Entry 2 Field: %s\n", response.Entries[1].Fields[0])
fmt.Printf("Last Generated Id: %s\n", response.LastGeneratedID)
fmt.Printf("Entries Added: %d\n", response.EntriesAdded.Value())
fmt.Printf("Length: %d\n", response.Length)
fmt.Printf("Max Deleted Entry id: %s\n", response.MaxDeletedEntryID.Value())
fmt.Printf("Radix Tree Keys: %d\n", response.RadixTreeKeys)
fmt.Printf("Radix Tree Nodes: %d\n", response.RadixTreeNodes)
fmt.Printf("Recorded First Entry Id: %s\n", response.RecordedFirstEntryId.Value())
Output: Total entries: 2 Entry 1 ID: 12345-1 Entry 1 Field: {field1 value1} Entry 2 ID: 12345-2 Entry 2 Field: {field2 value2} Last Generated Id: 12345-5 Entries Added: 5 Length: 5 Max Deleted Entry id: 0-0 Radix Tree Keys: 1 Radix Tree Nodes: 2 Recorded First Entry Id: 12345-1
func (*ClusterClient) XLen ¶
Returns the number of entries in the stream stored at `key`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream.
Return value:
The number of entries in the stream. If `key` does not exist, return 0.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.XAdd(
context.Background(),
"mystream",
[]models.FieldValue{{Field: "field1", Value: "foo4"}, {Field: "field2", Value: "bar4"}},
)
count, err := client.XLen(context.Background(), "mystream")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(count)
Output: 1
func (*ClusterClient) XPending ¶
func (client *ClusterClient) XPending(ctx context.Context, key string, group string) (models.XPendingSummary, error)
Returns stream message summary information for pending messages matching a stream and group.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. group - The consumer group name.
Return value:
An models.XPendingSummary struct that includes a summary with the following fields:
NumOfMessages - The total number of pending messages for this consumer group. StartId - The smallest ID among the pending messages or nil if no pending messages exist. EndId - The greatest ID among the pending messages or nil if no pending messages exists. GroupConsumers - An array of ConsumerPendingMessages with the following fields: ConsumerName - The name of the consumer. MessageCount - The number of pending messages for this consumer.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "12345"
streamId := "12345-1"
group := "g12345"
consumer := "c12345"
client.XGroupCreateWithOptions(context.Background(), key, group, "0", *options.NewXGroupCreateOptions().SetMakeStream())
client.XGroupCreateConsumer(context.Background(), key, group, consumer)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{
{Field: "entry1_field1", Value: "entry1_value1"},
{Field: "entry1_field2", Value: "entry1_value2"},
},
*options.NewXAddOptions().SetId(streamId),
)
client.XReadGroup(context.Background(), group, consumer, map[string]string{key: ">"})
summary, err := client.XPending(context.Background(), key, group)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
jsonSummary, _ := json.Marshal(summary)
fmt.Println(string(jsonSummary))
Output: {"NumOfMessages":1,"StartId":{},"EndId":{},"ConsumerMessages":[{"ConsumerName":"c12345","MessageCount":1}]}
func (*ClusterClient) XPendingWithOptions ¶
func (client *ClusterClient) XPendingWithOptions( ctx context.Context, key string, group string, opts options.XPendingOptions, ) ([]models.XPendingDetail, error)
Returns stream message summary information for pending messages matching a given range of IDs.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. group - The consumer group name. opts - The options for the command. See [options.XPendingOptions] for details.
Return value:
A slice of models.XPendingDetail structs, where each detail struct includes the following fields:
Id - The ID of the pending message. ConsumerName - The name of the consumer that fetched the message and has still to acknowledge it. IdleTime - The time in milliseconds since the last time the message was delivered to the consumer. DeliveryCount - The number of times this message was delivered.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "12345"
streamId := "12345-1"
group := "g12345"
consumer := "c12345"
client.XGroupCreateWithOptions(context.Background(), key, group, "0", *options.NewXGroupCreateOptions().SetMakeStream())
client.XGroupCreateConsumer(context.Background(), key, group, consumer)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{
{Field: "entry1_field1", Value: "entry1_value1"},
{Field: "entry1_field2", Value: "entry1_value2"},
},
*options.NewXAddOptions().SetId(streamId),
)
client.XReadGroup(context.Background(), group, consumer, map[string]string{key: ">"})
details, err := client.XPendingWithOptions(context.Background(),
key,
group,
*options.NewXPendingOptions("-", "+", 10).SetConsumer(consumer),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
jsonDetails, _ := json.Marshal(details)
// Since IdleTime can vary, check that output has all fields
fields := []string{"\"Id\"", "\"ConsumerName\"", "\"IdleTime\"", "\"DeliveryCount\""}
hasFields := true
jsonStr := string(jsonDetails)
for _, field := range fields {
hasFields = strings.Contains(jsonStr, field)
if !hasFields {
break
}
}
fmt.Println(hasFields)
Output: true
func (*ClusterClient) XRange ¶
func (client *ClusterClient) XRange( ctx context.Context, key string, start options.StreamBoundary, end options.StreamBoundary, ) ([]models.StreamEntry, error)
Returns stream entries matching a given range of IDs.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
key - The key of the stream.
start - The start position.
Use `options.NewStreamBoundary()` to specify a stream entry ID and its inclusive/exclusive status.
Use `options.NewInfiniteStreamBoundary()` to specify an infinite stream boundary.
end - The end position.
Use `options.NewStreamBoundary()` to specify a stream entry ID and its inclusive/exclusive status.
Use `options.NewInfiniteStreamBoundary()` to specify an infinite stream boundary.
Return value:
An `array` of [models.StreamEntry], where entry data stores an array of pairings with format `[[field, entry], [field, entry], ...]`.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "12345"
streamId1 := "12345-1"
streamId2 := "12345-2"
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{{Field: "field1", Value: "value1"}},
*options.NewXAddOptions().SetId(streamId1),
)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{{Field: "field2", Value: "value2"}},
*options.NewXAddOptions().SetId(streamId2),
)
response, err := client.XRange(context.Background(), key,
options.NewInfiniteStreamBoundary(constants.NegativeInfinity),
options.NewInfiniteStreamBoundary(constants.PositiveInfinity))
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(response)
Output: [{12345-1 [{field1 value1}]} {12345-2 [{field2 value2}]}]
func (*ClusterClient) XRangeWithOptions ¶
func (client *ClusterClient) XRangeWithOptions( ctx context.Context, key string, start options.StreamBoundary, end options.StreamBoundary, opts options.XRangeOptions, ) ([]models.StreamEntry, error)
Returns stream entries matching a given range of IDs.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
key - The key of the stream.
start - The start position.
Use `options.NewStreamBoundary()` to specify a stream entry ID and its inclusive/exclusive status.
Use `options.NewInfiniteStreamBoundary()` to specify an infinite stream boundary.
end - The end position.
Use `options.NewStreamBoundary()` to specify a stream entry ID and its inclusive/exclusive status.
Use `options.NewInfiniteStreamBoundary()` to specify an infinite stream boundary.
opts - Stream range options.
Return value:
An `array` of [models.StreamEntry], where entry data stores an array of pairings with format `[[field, entry], [field, entry], ...]`. Returns `nil` if `count` is non-positive.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "12345"
streamId1, _ := client.XAdd(context.Background(), key, []models.FieldValue{{Field: "field1", Value: "value1"}})
streamId2, _ := client.XAdd(context.Background(), key, []models.FieldValue{{Field: "field2", Value: "value2"}})
response, err := client.XRangeWithOptions(context.Background(), key,
options.NewStreamBoundary(streamId1, true),
options.NewStreamBoundary(streamId2, true),
*options.NewXRangeOptions().SetCount(1))
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(len(response))
Output: 1
func (*ClusterClient) XRead ¶
func (client *ClusterClient) XRead(ctx context.Context, keysAndIds map[string]string) (map[string]models.StreamResponse, error)
Reads entries from the given streams.
Note:
When in cluster mode, all keys in `keysAndIds` must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keysAndIds - A map of keys and entry IDs to read from.
Return value:
A map[string]models.StreamResponse where:
- Each key is a stream name
- Each value is a StreamResponse containing:
- Entries: []StreamEntry, where each StreamEntry has:
- ID: The unique identifier of the entry
- Fields: []FieldValue array of field-value pairs for the entry.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "12345"
streamId := "12345-1"
client.XAddWithOptions(context.Background(),
key,
[]models.FieldValue{{Field: "field1", Value: "value1"}, {Field: "field2", Value: "value2"}},
*options.NewXAddOptions().SetId(streamId),
)
response, err := client.XRead(context.Background(), map[string]string{key: "0-0"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Check that we have the stream with the correct name in the map
streamResponse, exists := response[key]
if exists {
fmt.Printf("Stream exists: %v\n", exists)
fmt.Printf("Number of entries: %d\n", len(streamResponse.Entries))
if len(streamResponse.Entries) > 0 {
entry := streamResponse.Entries[0]
fmt.Printf("Entry ID: %s\n", entry.ID)
fmt.Printf("Entry fields: %v\n", entry.Fields)
}
} else {
fmt.Println("Stream does not exist")
}
Output: Stream exists: true Number of entries: 1 Entry ID: 12345-1 Entry fields: [{field1 value1} {field2 value2}]
func (*ClusterClient) XReadGroup ¶
func (client *ClusterClient) XReadGroup( ctx context.Context, group string, consumer string, keysAndIds map[string]string, ) (map[string]models.StreamResponse, error)
Reads entries from the given streams owned by a consumer group.
Note:
When in cluster mode, all keys in `keysAndIds` must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. group - The consumer group name. consumer - The group consumer. keysAndIds - A map of keys and entry IDs to read from.
Return value:
A map[string]models.StreamResponse where:
- Each key is a stream name
- Each value is a StreamResponse containing:
- Entries: []StreamEntry, where each StreamEntry has:
- ID: The unique identifier of the entry
- Fields: map[string]string of field-value pairs for the entry
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "12345"
streamId := "12345-1"
group := uuid.NewString()
consumer := uuid.NewString()
client.XGroupCreateWithOptions(context.Background(), key, group, "0", *options.NewXGroupCreateOptions().SetMakeStream())
client.XGroupCreateConsumer(context.Background(), key, group, consumer)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{
{Field: "entry1_field1", Value: "entry1_value1"},
{Field: "entry1_field2", Value: "entry1_value2"},
},
*options.NewXAddOptions().SetId(streamId),
)
response, err := client.XReadGroup(context.Background(), group, consumer, map[string]string{key: "0"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Check that we have the stream with the correct name in the map
streamResponse, exists := response[key]
if exists {
fmt.Printf("Stream exists: %v\n", exists)
fmt.Printf("Number of entries: %d\n", len(streamResponse.Entries))
} else {
fmt.Println("Stream does not exist")
}
Output: Stream exists: true Number of entries: 0
func (*ClusterClient) XReadGroupWithOptions ¶
func (client *ClusterClient) XReadGroupWithOptions( ctx context.Context, group string, consumer string, keysAndIds map[string]string, opts options.XReadGroupOptions, ) (map[string]models.StreamResponse, error)
Reads entries from the given streams owned by a consumer group.
Note:
When in cluster mode, all keys in `keysAndIds` must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. group - The consumer group name. consumer - The group consumer. keysAndIds - A map of keys and entry IDs to read from. opts - Options detailing how to read the stream.
Return value:
A map[string]models.StreamResponse where:
- Each key is a stream name
- Each value is a StreamResponse containing:
- Entries: []StreamEntry, where each StreamEntry has:
- ID: The unique identifier of the entry
- Fields: map[string]string of field-value pairs for the entry
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "12345"
streamId := "12345-1"
group := uuid.NewString()
consumer := uuid.NewString()
client.XGroupCreateWithOptions(context.Background(), key, group, "0", *options.NewXGroupCreateOptions().SetMakeStream())
client.XGroupCreateConsumer(context.Background(), key, group, consumer)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{
{Field: "entry1_field1", Value: "entry1_value1"},
{Field: "entry1_field2", Value: "entry1_value2"},
},
*options.NewXAddOptions().SetId(streamId),
)
options := options.NewXReadGroupOptions().SetNoAck()
response, err := client.XReadGroupWithOptions(context.Background(), group, consumer, map[string]string{key: ">"}, *options)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Check that we have the stream with the correct name in the map
streamResponse, exists := response[key]
if exists {
fmt.Printf("Stream exists: %v\n", exists)
fmt.Printf("Number of entries: %d\n", len(streamResponse.Entries))
if len(streamResponse.Entries) > 0 {
entry := streamResponse.Entries[0]
fmt.Printf("Entry ID: %s\n", entry.ID)
fmt.Printf("Entry fields: %v\n", entry.Fields)
}
} else {
fmt.Println("Stream does not exist")
}
Output: Stream exists: true Number of entries: 1 Entry ID: 12345-1 Entry fields: [{entry1_field1 entry1_value1} {entry1_field2 entry1_value2}]
func (*ClusterClient) XReadWithOptions ¶
func (client *ClusterClient) XReadWithOptions( ctx context.Context, keysAndIds map[string]string, opts options.XReadOptions, ) (map[string]models.StreamResponse, error)
Reads entries from the given streams.
Note:
When in cluster mode, all keys in `keysAndIds` must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keysAndIds - A map of keys and entry IDs to read from. opts - Options detailing how to read the stream.
Return value:
A map[string]models.StreamResponse where:
- Each key is a stream name
- Each value is a StreamResponse containing:
- Entries: []StreamEntry, where each StreamEntry has:
- ID: The unique identifier of the entry
- Fields: []FieldValue array of field-value pairs for the entry
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "12345"
streambase := 1
genStreamId := func(key string, base int, offset int) string { return fmt.Sprintf("%s-%d", key, base+offset) } // helper function to generate stream ids
client.XAddWithOptions(context.Background(),
key,
[]models.FieldValue{{Field: "field1", Value: "value1"}, {Field: "field2", Value: "value2"}},
*options.NewXAddOptions().SetId(genStreamId(key, streambase, 0)),
)
client.XAddWithOptions(context.Background(),
key,
[]models.FieldValue{{Field: "field3", Value: "value3"}, {Field: "field4", Value: "value4"}},
*options.NewXAddOptions().SetId(genStreamId(key, streambase, 1)),
)
response, err := client.XReadWithOptions(context.Background(),
map[string]string{key: genStreamId(key, streambase, 0)},
*options.NewXReadOptions().SetCount(1),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// Check that we have the stream with the correct name in the map
streamResponse, exists := response[key]
if exists {
fmt.Printf("Stream exists: %v\n", exists)
fmt.Printf("Number of entries: %d\n", len(streamResponse.Entries))
if len(streamResponse.Entries) > 0 {
entry := streamResponse.Entries[0]
fmt.Printf("Entry ID: %s\n", entry.ID)
fmt.Printf("Entry fields: %v\n", entry.Fields)
}
} else {
fmt.Println("Stream does not exist")
}
Output: Stream exists: true Number of entries: 1 Entry ID: 12345-2 Entry fields: [{field3 value3} {field4 value4}]
func (*ClusterClient) XRevRange ¶
func (client *ClusterClient) XRevRange( ctx context.Context, key string, start options.StreamBoundary, end options.StreamBoundary, ) ([]models.StreamEntry, error)
Returns stream entries matching a given range of IDs in reverse order. Equivalent to `XRange` but returns entries in reverse order.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
key - The key of the stream.
start - The start position.
Use `options.NewStreamBoundary()` to specify a stream entry ID and its inclusive/exclusive status.
Use `options.NewInfiniteStreamBoundary()` to specify an infinite stream boundary.
end - The end position.
Use `options.NewStreamBoundary()` to specify a stream entry ID and its inclusive/exclusive status.
Use `options.NewInfiniteStreamBoundary()` to specify an infinite stream boundary.
Return value:
An `array` of [models.StreamEntry], where entry data stores an array of pairings with format `[[field, entry], [field, entry], ...]`.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "12345"
streamId1 := "12345-1"
streamId2 := "12345-2"
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{{Field: "field1", Value: "value1"}},
*options.NewXAddOptions().SetId(streamId1),
)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{{Field: "field2", Value: "value2"}},
*options.NewXAddOptions().SetId(streamId2),
)
response, err := client.XRevRange(context.Background(), key,
options.NewStreamBoundary(streamId2, true),
options.NewStreamBoundary(streamId1, true))
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(response)
Output: [{12345-2 [{field2 value2}]} {12345-1 [{field1 value1}]}]
func (*ClusterClient) XRevRangeWithOptions ¶
func (client *ClusterClient) XRevRangeWithOptions( ctx context.Context, key string, start options.StreamBoundary, end options.StreamBoundary, opts options.XRangeOptions, ) ([]models.StreamEntry, error)
Returns stream entries matching a given range of IDs in reverse order. Equivalent to `XRange` but returns entries in reverse order.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
key - The key of the stream.
start - The start position.
Use `options.NewStreamBoundary()` to specify a stream entry ID and its inclusive/exclusive status.
Use `options.NewInfiniteStreamBoundary()` to specify an infinite stream boundary.
end - The end position.
Use `options.NewStreamBoundary()` to specify a stream entry ID and its inclusive/exclusive status.
Use `options.NewInfiniteStreamBoundary()` to specify an infinite stream boundary.
opts - Stream range options.
Return value:
An `array` of [models.StreamEntry], where entry data stores an array of pairings with format `[[field, entry], [field, entry], ...]`. Returns `nil` if `count` is non-positive.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key := "12345"
streamId1 := "12345-1"
streamId2 := "12345-2"
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{{Field: "field1", Value: "value1"}},
*options.NewXAddOptions().SetId(streamId1),
)
client.XAddWithOptions(
context.Background(),
key,
[]models.FieldValue{{Field: "field2", Value: "value2"}},
*options.NewXAddOptions().SetId(streamId2),
)
response, err := client.XRevRangeWithOptions(context.Background(), key,
options.NewStreamBoundary(streamId2, true),
options.NewStreamBoundary(streamId1, true),
*options.NewXRangeOptions().SetCount(2))
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(response)
Output: [{12345-2 [{field2 value2}]} {12345-1 [{field1 value1}]}]
func (*ClusterClient) XTrim ¶
func (client *ClusterClient) XTrim(ctx context.Context, key string, options options.XTrimOptions) (int64, error)
Trims the stream by evicting older entries.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the stream. options - Stream trim options
Return value:
The number of entries deleted from the stream.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.XAdd(
context.Background(),
"mystream",
[]models.FieldValue{{Field: "field1", Value: "foo4"}, {Field: "field2", Value: "bar4"}},
)
client.XAdd(
context.Background(),
"mystream",
[]models.FieldValue{{Field: "field3", Value: "foo4"}, {Field: "field4", Value: "bar4"}},
)
count, err := client.XTrim(context.Background(), "mystream", *options.NewXTrimOptionsWithMaxLen(0).SetExactTrimming())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(count)
Output: 2
func (*ClusterClient) ZAdd ¶
func (client *ClusterClient) ZAdd( ctx context.Context, key string, membersScoreMap map[string]float64, ) (int64, error)
Adds one or more members to a sorted set, or updates their scores. Creates the key if it doesn't exist.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the set. membersScoreMap - A map of members to their scores.
Return value:
The number of members added to the set.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.ZAdd(context.Background(), "key1", map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 3
func (*ClusterClient) ZAddIncr ¶
func (client *ClusterClient) ZAddIncr( ctx context.Context, key string, member string, increment float64, ) (float64, error)
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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. member - A member in the sorted set to increment. increment - The score to increment the member.
Return value:
The new score of the member.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.ZAddIncr(context.Background(), "key1", "one", 1.0)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 1
func (*ClusterClient) ZAddIncrWithOptions ¶
func (client *ClusterClient) ZAddIncrWithOptions( ctx context.Context, key string, member string, increment float64, opts options.ZAddOptions, ) (models.Result[float64], error)
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.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. member - A member in the sorted set to increment. increment - The score to increment the member. opts - The options for the command. See [ZAddOptions] for details.
Return value:
The new score of the member. If there was a conflict with the options, the operation aborts and `nil` is returned.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
opts, err := options.NewZAddOptions().SetChanged(true) // should return an error
result, err := client.ZAddIncrWithOptions(context.Background(), "key1", "one", 1.0, *opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: Glide example failed with an error: incr cannot be set when changed is true {0 true}
func (*ClusterClient) ZAddWithOptions ¶
func (client *ClusterClient) ZAddWithOptions( ctx context.Context, key string, membersScoreMap map[string]float64, opts options.ZAddOptions, ) (int64, error)
Adds one or more members to a sorted set, or updates their scores. Creates the key if it doesn't exist.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the set. membersScoreMap - A map of members to their scores. opts - The options for the command. See [Client.ZAddOptions] [ClusterClient.ZAddOptions] for details.
Return value:
The number of members added to the set. If `CHANGED` is set, the number of members that were updated.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
opts, err := options.NewZAddOptions().SetChanged(true)
result, err := client.ZAddWithOptions(context.Background(),
"key1",
map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0},
*opts,
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 3
func (*ClusterClient) ZCard ¶
Returns the cardinality (number of elements) of the sorted set stored at `key`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the set.
Return value:
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`. If `key` holds a value that is not a sorted set, an error is returned.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.ZAdd(context.Background(), "key1", map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0})
result1, err := client.ZCard(context.Background(), "key1")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 3 3
func (*ClusterClient) ZCount ¶
func (client *ClusterClient) ZCount(ctx context.Context, key string, rangeOptions options.ZCountRange) (int64, error)
Returns the number of members in the sorted set stored at `key` with scores between `min` and `max` score.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the set. rangeOptions - Contains `min` and `max` score. `min` contains the minimum score to count from. `max` contains the maximum score to count up to. Can be positive/negative infinity, or specific score and inclusivity.
Return value:
The number of members in the specified score range.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
zCountRange := options.NewZCountRange(
options.NewInclusiveScoreBoundary(2.0),
options.NewInfiniteScoreBoundary(constants.PositiveInfinity),
)
result, err := client.ZAdd(
context.Background(),
"key1",
map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0, "four": 4.0},
)
result1, err := client.ZCount(context.Background(), "key1", *zCountRange)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 4 3
func (*ClusterClient) ZDiff ¶
Returns the difference between the first sorted set and all the successive sorted sets. To get the elements with their scores, see Client.ZDiffWithScores or ClusterClient.ZDiffWithScores.
Note:
When in cluster mode, all `keys` must map to the same hash slot.
Since:
Valkey 6.2.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - The keys of the sorted sets.
Return value:
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.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.ZAdd(context.Background(), "{key}1", map[string]float64{"a": 1.0, "b": 2.5, "c": 3.0, "d": 4.0})
client.ZAdd(context.Background(), "{key}2", map[string]float64{"b": 1.0, "c": 2.5, "d": 3.0, "e": 4.0})
result, err := client.ZDiff(context.Background(), []string{"{key}1", "{key}2"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [a]
func (*ClusterClient) ZDiffStore ¶
func (client *ClusterClient) ZDiffStore(ctx context.Context, destination string, keys []string) (int64, error)
Calculates the difference between the first sorted set and all the successive sorted sets at `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.
Note:
When in cluster mode, `destination` and all `keys` must map to the same hash slot.
Since:
Valkey 6.2.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. destination - The key for the resulting sorted set. keys - The keys of the sorted sets to compare.
Return value:
The number of members in the resulting sorted set stored at `destination`.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.ZAdd(context.Background(), "{key}1", map[string]float64{"a": 1.0, "b": 2.5, "c": 3.0, "d": 4.0})
client.ZAdd(context.Background(), "{key}2", map[string]float64{"b": 1.0, "c": 2.5, "d": 3.0, "e": 4.0})
result, err := client.ZDiffStore(context.Background(), "{key}dest", []string{"{key}1", "{key}2"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 1
func (*ClusterClient) ZDiffWithScores ¶
func (client *ClusterClient) ZDiffWithScores(ctx context.Context, keys []string) ([]models.MemberAndScore, error)
Returns the difference between the first sorted set and all the successive sorted sets.
Note:
When in cluster mode, all `keys` must map to the same hash slot.
Since:
Valkey 6.2.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - The keys of the sorted sets.
Return value:
An array 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.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.ZAdd(context.Background(), "{key}1", map[string]float64{"a": 1.0, "b": 2.5, "c": 3.0, "d": 4.0})
client.ZAdd(context.Background(), "{key}2", map[string]float64{"b": 1.0, "c": 2.5, "d": 3.0, "e": 4.0})
result, err := client.ZDiffWithScores(context.Background(), []string{"{key}1", "{key}2"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [{a 1}]
func (*ClusterClient) ZIncrBy ¶
func (client *ClusterClient) ZIncrBy(ctx context.Context, key string, increment float64, member string) (float64, error)
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 with the specified member as its sole member is created.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. increment - The score increment. member - A member of the sorted set.
Return value:
The new score of member.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.ZAdd(context.Background(), "key1", map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0})
result1, err := client.ZIncrBy(context.Background(), "key1", 3.0, "two")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 3 5
func (*ClusterClient) ZInter ¶
Returns the intersection of members from sorted sets specified by the given `keys`. To get the elements with their scores, see Client.ZInterWithScores or ClusterClient.ZInterWithScores.
Note:
When in cluster mode, all keys must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - The keys of the sorted sets, see - [options.KeyArray].
Return value:
The resulting sorted set from the intersection.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.ZAdd(context.Background(), "{key}1", map[string]float64{"a": 1.0, "b": 2.5, "c": 3.0, "d": 4.0})
client.ZAdd(context.Background(), "{key}2", map[string]float64{"b": 1.0, "c": 2.5, "d": 3.0, "e": 4.0})
result, err := client.ZInter(context.Background(), options.KeyArray{
Keys: []string{"{key}1", "{key}2"},
})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [b c d]
func (*ClusterClient) ZInterCard ¶
Returns the cardinality of the intersection of the sorted sets specified by `keys`.
Note:
When in cluster mode, all keys must map to the same hash slot.
Since:
Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - The keys of the sorted sets.
Return value:
The cardinality of the intersection of the sorted sets.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key1 := "{testkey}-1"
key2 := "{testkey}-2"
client.ZAdd(context.Background(), key1, map[string]float64{"a": 1.0, "b": 2.0, "c": 3.0, "d": 4.0})
client.ZAdd(context.Background(), key2, map[string]float64{"a": 1.0, "b": 2.0, "c": 3.0, "e": 4.0})
res, err := client.ZInterCard(context.Background(), []string{key1, key2})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(res)
Output: 3
func (*ClusterClient) ZInterCardWithOptions ¶
func (client *ClusterClient) ZInterCardWithOptions( ctx context.Context, keys []string, options options.ZInterCardOptions, ) (int64, error)
Returns the cardinality of the intersection of the sorted sets specified by `keys`. If the intersection cardinality reaches `options.limit` partway through the computation, the algorithm will exit early and yield `options.limit` as the cardinality.
Note:
When in cluster mode, all keys must map to the same hash slot.
Since:
Valkey 7.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - The keys of the sorted sets. options - The options for the ZInterCard command, see - [options.ZInterCardOptions].
Return value:
The cardinality of the intersection of the sorted sets.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
key1 := "{testkey}-1"
key2 := "{testkey}-2"
client.ZAdd(context.Background(), key1, map[string]float64{"a": 1.0, "b": 2.0, "c": 3.0, "d": 4.0})
client.ZAdd(context.Background(), key2, map[string]float64{"a": 1.0, "b": 2.0, "c": 3.0, "e": 4.0})
res, err := client.ZInterCardWithOptions(context.Background(),
[]string{key1, key2},
*options.NewZInterCardOptions().SetLimit(5),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(res)
Output: 3
func (*ClusterClient) ZInterStore ¶
func (client *ClusterClient) ZInterStore( ctx context.Context, destination string, keysOrWeightedKeys options.KeysOrWeightedKeys, ) (int64, error)
Computes the intersection of sorted sets given by the specified `keysOrWeightedKeys` and stores the result in `destination`. If `destination` already exists, it is overwritten. Otherwise, a new sorted set will be created.
Note:
When in cluster mode, `destination` and all keys in `keysOrWeightedKeys` must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
destination - The destination key for the result.
keysOrWeightedKeys - The keys or weighted keys of the sorted sets, see - [options.KeysOrWeightedKeys].
- Use `options.NewKeyArray()` for keys only.
- Use `options.NewWeightedKeys()` for weighted keys with score multipliers.
Return value:
The number of elements in the resulting sorted set stored at `destination`.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.ZAdd(context.Background(), "{key}1", map[string]float64{"a": 1.0, "b": 2.5, "c": 3.0, "d": 4.0})
client.ZAdd(context.Background(), "{key}2", map[string]float64{"b": 1.0, "c": 2.5, "d": 3.0, "e": 4.0})
result, err := client.ZInterStore(context.Background(), "{key}dest", options.KeyArray{
Keys: []string{"{key}1", "{key}2"},
})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 3
func (*ClusterClient) ZInterStoreWithOptions ¶
func (client *ClusterClient) ZInterStoreWithOptions( ctx context.Context, destination string, keysOrWeightedKeys options.KeysOrWeightedKeys, zInterOptions options.ZInterOptions, ) (int64, error)
Computes the intersection of sorted sets given by the specified `keysOrWeightedKeys` and stores the result in `destination`. If `destination` already exists, it is overwritten. Otherwise, a new sorted set will be created.
Note:
When in cluster mode, `destination` and all keys in `keysOrWeightedKeys` must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
destination - The destination key for the result.
keysOrWeightedKeys - The keys or weighted keys of the sorted sets, see - [options.KeysOrWeightedKeys].
- Use `options.NewKeyArray()` for keys only.
- Use `options.NewWeightedKeys()` for weighted keys with score multipliers.
options - The options for the ZInterStore command, see - [options.ZInterOptions].
Optional `aggregate` option specifies the aggregation strategy to apply when combining the scores of
elements.
Return value:
The number of elements in the resulting sorted set stored at `destination`.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.ZAdd(context.Background(), "{key}1", map[string]float64{"a": 1.0, "b": 2.5, "c": 3.0, "d": 4.0})
client.ZAdd(context.Background(), "{key}2", map[string]float64{"b": 1.0, "c": 2.5, "d": 3.0, "e": 4.0})
result, err := client.ZInterStoreWithOptions(context.Background(),
"{key}dest",
options.KeyArray{
Keys: []string{"{key}1", "{key}2"},
},
*options.NewZInterOptions().SetAggregate(options.AggregateSum),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 3
func (*ClusterClient) ZInterWithScores ¶
func (client *ClusterClient) ZInterWithScores( ctx context.Context, keysOrWeightedKeys options.KeysOrWeightedKeys, zInterOptions options.ZInterOptions, ) ([]models.MemberAndScore, error)
Returns the intersection of members and their scores from sorted sets specified by the given `keysOrWeightedKeys`.
Note:
When in cluster mode, all keys in `keysOrWeightedKeys` must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
keysOrWeightedKeys - The keys or weighted keys of the sorted sets, see - [options.KeysOrWeightedKeys].
- Use `options.NewKeyArray()` for keys only.
- Use `options.NewWeightedKeys()` for weighted keys with score multipliers.
options - The options for the ZInter command, see - [options.ZInterOptions].
Optional `aggregate` option specifies the aggregation strategy to apply when combining the scores of
elements.
Return value:
An array of `models.MemberAndScore` objects, 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.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.ZAdd(context.Background(), "{key}1", map[string]float64{"a": 1.0, "b": 2.5, "c": 3.0, "d": 4.0})
client.ZAdd(context.Background(), "{key}2", map[string]float64{"b": 1.0, "c": 2.5, "d": 3.0, "e": 4.0})
result, err := client.ZInterWithScores(context.Background(),
options.KeyArray{
Keys: []string{"{key}1", "{key}2"},
},
*options.NewZInterOptions().SetAggregate(options.AggregateSum),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: [{b 3.5} {c 5.5} {d 7}]
func (*ClusterClient) ZLexCount ¶
func (client *ClusterClient) ZLexCount(ctx context.Context, key string, rangeQuery options.RangeByLex) (int64, error)
Returns the number of elements in the sorted set at key with a value between min and max.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. rangeQuery - The range query to apply to the sorted set.
Return value:
The number of elements in the sorted set at key with a value between min and max.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.ZAdd(context.Background(), "key1", map[string]float64{"a": 1.0, "b": 2.0, "c": 3.0, "d": 4.0})
result, err := client.ZLexCount(context.Background(), "key1",
*options.NewRangeByLexQuery(
options.NewLexBoundary("a", false),
options.NewLexBoundary("c", true),
),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 2
func (*ClusterClient) ZMPop ¶
func (client *ClusterClient) ZMPop( ctx context.Context, keys []string, scoreFilter constants.ScoreFilter, ) (models.Result[models.KeyWithArrayOfMembersAndScores], error)
Pops one or more member-score pairs from the first non-empty sorted set, with the given keys being checked in the order provided.
Note:
When in cluster mode, all keys must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - An array of keys to check for elements. scoreFilter - Pop criteria - either [constants.MIN] or [constants.MAX] to pop members with the lowest/highest scores.
Return value:
A `models.KeyWithArrayOfMembersAndScores` struct containing: - The key from which the elements were popped. - An array of member-score pairs of the popped elements. Returns `nil` if no member could be popped.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
// Add members to a sorted set
client.ZAdd(context.Background(), "{key}sortedSet", map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0})
// Pop the lowest-score member
res, err := client.ZMPop(context.Background(), []string{"{key}sortedSet"}, constants.MIN)
if err != nil {
fmt.Println("Glide example failed with an error:", err)
return
}
value := res.Value()
fmt.Printf("{Key: %q, MembersAndScores: [", value.Key)
for i, member := range value.MembersAndScores {
if i > 0 {
fmt.Print(", ")
}
fmt.Printf("{Member: %q, Score: %.1f}", member.Member, member.Score)
}
fmt.Println("]}")
Output: {Key: "{key}sortedSet", MembersAndScores: [{Member: "one", Score: 1.0}]}
func (*ClusterClient) ZMPopWithOptions ¶
func (client *ClusterClient) ZMPopWithOptions( ctx context.Context, keys []string, scoreFilter constants.ScoreFilter, opts options.ZMPopOptions, ) (models.Result[models.KeyWithArrayOfMembersAndScores], error)
Removes and returns up to `count` members from the first non-empty sorted set among the provided `keys`, based on the specified `scoreFilter` criteria.
Note:
When in cluster mode, all keys must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - A list of keys representing sorted sets to check for elements. scoreFilter - Pop criteria - either [constants.MIN] or [constants.MAX] to pop members with the lowest/highest scores. opts - Additional options, such as specifying the maximum number of elements to pop.
Return value:
A `Result` containing a `models.KeyWithArrayOfMembersAndScores` object. If no elements could be popped from the provided keys, returns `nil`.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.ZAdd(context.Background(), "{key}SortedSet", map[string]float64{"p": 10.0, "q": 20.0, "r": 30.0})
opts := *options.NewZMPopOptions().SetCount(2)
res, err := client.ZMPopWithOptions(context.Background(), []string{"{key}SortedSet"}, constants.MAX, opts)
if err != nil {
fmt.Println("Glide example failed with an error:", err)
return
}
value := res.Value()
// Ensure sorting of results for deterministic comparison
sort.Slice(value.MembersAndScores, func(i, j int) bool {
return value.MembersAndScores[i].Score > value.MembersAndScores[j].Score
})
fmt.Printf("{Key: %q, MembersAndScores: [", value.Key)
for i, member := range value.MembersAndScores {
if i > 0 {
fmt.Print(", ")
}
fmt.Printf("{Member: %q, Score: %.1f}", member.Member, member.Score)
}
fmt.Println("]}")
Output: {Key: "{key}SortedSet", MembersAndScores: [{Member: "r", Score: 30.0}, {Member: "q", Score: 20.0}]}
func (*ClusterClient) ZMScore ¶
func (client *ClusterClient) ZMScore(ctx context.Context, key string, members []string) ([]models.Result[float64], error)
Returns the scores associated with the specified `members` in the sorted set stored at `key`.
Since:
Valkey 6.2.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. members - A list of members in the sorted set.
Return value:
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 `nil`.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.ZAdd(context.Background(), "key1", map[string]float64{"a": 1.0, "b": 2.5, "c": 3.0, "d": 4.0})
result, err := client.ZMScore(context.Background(), "key1", []string{"c", "b", "e"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// If the key does not exist, an empty string is returned
fmt.Println(result)
Output: [{3 false} {2.5 false} {0 true}]
func (*ClusterClient) ZPopMax ¶
Removes and returns the member with the highest score from the sorted set stored at the specified `key`.
see valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set.
Return value:
A map containing the removed member and its corresponding score. If `key` doesn't exist, it will be treated as an empty sorted set and the command returns an empty map.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.ZAdd(context.Background(), "key1", map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0})
result1, err := client.ZPopMax(context.Background(), "key1")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 3 map[three:3]
func (*ClusterClient) ZPopMaxWithOptions ¶
func (client *ClusterClient) ZPopMaxWithOptions( ctx context.Context, key string, options options.ZPopOptions, ) (map[string]float64, error)
Removes and returns up to `count` members with the highest scores from the sorted set stored at the specified `key`.
see valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. count - The number of members to remove.
Return value:
A map containing the removed members and their corresponding scores. If `key` doesn't exist, it will be treated as an empty sorted set and the command returns an empty map.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.ZAdd(context.Background(), "key1", map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0})
opts := options.NewZPopOptions().SetCount(2)
result1, err := client.ZPopMaxWithOptions(context.Background(), "key1", *opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 3 map[three:3 two:2]
func (*ClusterClient) ZPopMin ¶
Removes and returns the member with the lowest score from the sorted set stored at the specified `key`.
see valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set.
Return value:
A map containing the removed member and its corresponding score. If `key` doesn't exist, it will be treated as an empty sorted set and the command returns an empty map.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.ZAdd(context.Background(), "key1", map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0})
result1, err := client.ZPopMin(context.Background(), "key1")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 3 map[one:1]
func (*ClusterClient) ZPopMinWithOptions ¶
func (client *ClusterClient) ZPopMinWithOptions( ctx context.Context, key string, options options.ZPopOptions, ) (map[string]float64, error)
Removes and returns multiple members with the lowest scores from the sorted set stored at the specified `key`.
see valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. options - Pop options, see [options.ZPopOptions].
Return value:
A map containing the removed members and their corresponding scores. If `key` doesn't exist, it will be treated as an empty sorted set and the command returns an empty map.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.ZAdd(context.Background(), "key1", map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0})
opts := options.NewZPopOptions().SetCount(2)
result1, err := client.ZPopMinWithOptions(context.Background(), "key1", *opts)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 3 map[one:1 two:2]
func (*ClusterClient) ZRandMember ¶
func (client *ClusterClient) ZRandMember(ctx context.Context, key string) (models.Result[string], error)
Returns a random member from the sorted set stored at `key`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set.
Return value:
A string representing a random member from the sorted set. If the sorted set does not exist or is empty, the response will be `nil`.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.ZAdd(context.Background(), "key1", map[string]float64{"a": 1.0, "b": 2.0, "c": 3.0, "d": 4.0})
result, err := client.ZRandMember(context.Background(), "key2")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// If the key does not exist, an empty string is returned
fmt.Println(result.Value() == "")
Output: true
func (*ClusterClient) ZRandMemberWithCount ¶
func (client *ClusterClient) ZRandMemberWithCount(ctx context.Context, key string, count int64) ([]string, error)
Returns multiple random members from the sorted set stored at `key`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. count - The number of field names to return. If `count` is positive, returns unique elements. If negative, allows for duplicates.
Return value:
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.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.ZAdd(context.Background(), "key1", map[string]float64{"a": 1.0, "b": 2.0, "c": 3.0, "d": 4.0})
result, err := client.ZRandMemberWithCount(context.Background(), "key1", 4)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// If the key does not exist, an empty string is returned
fmt.Println(result)
Output: [d c b a]
func (*ClusterClient) ZRandMemberWithCountWithScores ¶
func (client *ClusterClient) ZRandMemberWithCountWithScores( ctx context.Context, key string, count int64, ) ([]models.MemberAndScore, error)
Returns random members with scores from the sorted set stored at key.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. count - The number of field names to return. If `count` is positive, returns unique elements. If negative, allows for duplicates.
Return value:
An array of `models.MemberAndScore` objects, 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.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.ZAdd(context.Background(), "key1", map[string]float64{"a": 1.0, "b": 2.0, "c": 3.0, "d": 4.0})
result, err := client.ZRandMemberWithCountWithScores(context.Background(), "key1", 4)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
// If the key does not exist, an empty string is returned
fmt.Println(result)
Output: [{d 4} {c 3} {b 2} {a 1}]
func (*ClusterClient) ZRange ¶
func (client *ClusterClient) ZRange(ctx context.Context, key string, rangeQuery options.ZRangeQuery) ([]string, error)
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 Client.ZRangeWithScores and ClusterClient.ZRangeWithScores.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. rangeQuery - The range query object representing the type of range query to perform. - For range queries by index (rank), use [RangeByIndex]. - For range queries by lexicographical order, use [RangeByLex]. - For range queries by score, use [RangeByScore].
Return value:
An array 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 ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.ZAdd(context.Background(), "key1", map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0})
result1, err := client.ZRange(context.Background(), "key1", options.NewRangeByIndexQuery(0, -1)) // Ascending order
// Retrieve members within a score range in descending order
query := options.NewRangeByScoreQuery(
options.NewScoreBoundary(3, false),
options.NewInfiniteScoreBoundary(constants.NegativeInfinity)).SetReverse()
result2, err := client.ZRange(context.Background(), "key1", query)
// `result` contains members which have scores within the range of negative infinity to 3, in descending order
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: 3 [one two three] [two one]
func (*ClusterClient) ZRangeStore ¶
func (client *ClusterClient) ZRangeStore( ctx context.Context, destination string, key string, rangeQuery options.ZRangeQuery, ) (int64, error)
Stores a specified range of elements from the sorted set at `key`, into a new sorted set at `destination`. If `destination` doesn't exist, a new sorted set is created; if it exists, it's overwritten.
Note:
When in cluster mode, all keys must map to the same hash slot.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. destination - The key for the destination sorted set. key - The key of the source sorted set. rangeQuery - The range query object representing the type of range query to perform. - For range queries by index (rank), use [RangeByIndex]. - For range queries by lexicographical order, use [RangeByLex]. - For range queries by score, use [RangeByScore].
Return value:
The number of elements in the resulting sorted set.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.ZAdd(context.Background(), "{key}1", map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0})
query := options.NewRangeByScoreQuery(
options.NewScoreBoundary(3, false),
options.NewInfiniteScoreBoundary(constants.NegativeInfinity)).SetReverse()
result, err := client.ZRangeStore(context.Background(), "{key}dest", "{key}1", query)
// `result` contains members which have scores within the range of negative infinity to 3, in descending order
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
Output: 2
func (*ClusterClient) ZRangeWithScores ¶
func (client *ClusterClient) ZRangeWithScores( ctx context.Context, key string, rangeQuery options.ZRangeQueryWithScores, ) ([]models.MemberAndScore, error)
Returns the specified range of elements with their scores 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.
See valkey.io for more details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. rangeQuery - The range query object representing the type of range query to perform. - For range queries by index (rank), use [RangeByIndex]. - For range queries by score, use [RangeByScore].
Return value:
An array 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 array.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.ZAdd(context.Background(), "key1", map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0})
result1, err := client.ZRangeWithScores(context.Background(), "key1", options.NewRangeByIndexQuery(0, -1))
query := options.NewRangeByScoreQuery(
options.NewScoreBoundary(3, false),
options.NewInfiniteScoreBoundary(constants.NegativeInfinity)).SetReverse()
result2, err := client.ZRangeWithScores(context.Background(), "key1", query)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
fmt.Println(result2)
Output: 3 [{one 1} {two 2} {three 3}] [{two 2} {one 1}]
func (*ClusterClient) ZRank ¶
func (client *ClusterClient) ZRank(ctx context.Context, key string, member string) (models.Result[int64], error)
Returns the rank of `member` in the sorted set stored at `key`, with scores ordered from low to high, starting from `0`. To get the rank of `member` with its score, see Client.ZRankWithScore and ClusterClient.ZRankWithScore.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. member - The member to get the rank of.
Return value:
The rank of `member` in the sorted set. If `key` doesn't exist, or if `member` is not present in the set, an empty [models.Result] will be returned.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.ZAdd(context.Background(), "key1", map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0})
result1, err := client.ZRank(context.Background(), "key1", "two")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 3 {1 false}
func (*ClusterClient) ZRankWithScore ¶
func (client *ClusterClient) ZRankWithScore( ctx context.Context, key string, member string, ) (models.Result[models.RankAndScore], error)
Returns the rank of `member` in the sorted set stored at `key` with its score, where scores are ordered from the lowest to highest, starting from `0`.
Since:
Valkey 7.2.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. member - The member to get the rank of.
Return value:
A [models.Result[models.RankAndScore]] containing the rank of `member` and its score. If `key` doesn't exist, or if `member` is not present in the set, an empty [models.Result] will be returned.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.ZAdd(context.Background(), "key1", map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0})
res, err := client.ZRankWithScore(context.Background(), "key1", "two")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(res.Value().Rank)
fmt.Println(res.Value().Score)
Output: 3 1 2
func (*ClusterClient) ZRem ¶
Removes the specified members from the sorted set stored at `key`. Specified members that are not a member of this set are ignored.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. members - The members to remove.
Return value:
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 ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.ZAdd(context.Background(), "key1", map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0})
result1, err := client.ZRem(context.Background(), "key1", []string{"one", "two", "nonMember"})
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 3 2
func (*ClusterClient) ZRemRangeByLex ¶
func (client *ClusterClient) ZRemRangeByLex(ctx context.Context, key string, rangeQuery options.RangeByLex) (int64, error)
Removes all elements in the sorted set stored at `key` with a lexicographical order between `rangeQuery.Start` and `rangeQuery.End`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. rangeQuery - The range query object representing the minimum and maximum bound of the lexicographical range.
Return value:
The number of members removed from the sorted set. If `key` does not exist, it is treated as an empty sorted set, and the command returns `0`. If `rangeQuery.Start` is greater than `rangeQuery.End`, `0` is returned.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.ZAdd(context.Background(), "key1", map[string]float64{"a": 1.0, "b": 2.0, "c": 3.0, "d": 4.0})
result1, err := client.ZRemRangeByLex(context.Background(),
"key1",
*options.NewRangeByLexQuery(options.NewLexBoundary("a", false), options.NewLexBoundary("c", true)),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 4 2
func (*ClusterClient) ZRemRangeByRank ¶
func (client *ClusterClient) ZRemRangeByRank(ctx context.Context, key string, start int64, stop int64) (int64, error)
Removes all elements in the sorted set stored at `key` with a rank between `start` and `stop`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. start - The start rank. stop - The stop rank.
Return value:
The number of members removed from the sorted set. If `key` does not exist, it is treated as an empty sorted set, and the command returns `0`. If `start` is greater than `stop`, `0` is returned.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.ZAdd(context.Background(), "key1", map[string]float64{"a": 1.0, "b": 2.0, "c": 3.0, "d": 4.0})
result1, err := client.ZRemRangeByRank(context.Background(), "key1", 1, 3)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 4 3
func (*ClusterClient) ZRemRangeByScore ¶
func (client *ClusterClient) ZRemRangeByScore(ctx context.Context, key string, rangeQuery options.RangeByScore) (int64, error)
Removes all elements in the sorted set stored at `key` with a score between `rangeQuery.Start` and `rangeQuery.End`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. rangeQuery - The range query object representing the minimum and maximum bound of the score range. can be an implementation of [options.RangeByScore].
Return value:
The number of members removed from the sorted set. If `key` does not exist, it is treated as an empty sorted set, and the command returns `0`. If `rangeQuery.Start` is greater than `rangeQuery.End`, `0` is returned.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.ZAdd(context.Background(), "key1", map[string]float64{"a": 1.0, "b": 2.0, "c": 3.0, "d": 4.0})
result1, err := client.ZRemRangeByScore(context.Background(), "key1", *options.NewRangeByScoreQuery(
options.NewInfiniteScoreBoundary(constants.NegativeInfinity),
options.NewInfiniteScoreBoundary(constants.PositiveInfinity),
))
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 4 4
func (*ClusterClient) ZRevRank ¶
func (client *ClusterClient) ZRevRank(ctx context.Context, key string, member string) (models.Result[int64], error)
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 Client.ZRevRankWithScore and ClusterClient.ZRevRankWithScore.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. member - The member to get the rank of.
Return value:
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, an empty [models.Result] will be returned.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.ZAdd(
context.Background(),
"key1",
map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0, "four": 4.0},
)
result1, err := client.ZRevRank(context.Background(), "key1", "two")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 4 {2 false}
func (*ClusterClient) ZRevRankWithScore ¶
func (client *ClusterClient) ZRevRankWithScore( ctx context.Context, key string, member string, ) (models.Result[models.RankAndScore], error)
Returns the rank of `member` in the sorted set stored at `key`, where scores are ordered from the highest to lowest, starting from `0`.
Since:
Valkey 7.2.0 and above.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. member - The member to get the rank of.
Return value:
A [models.Result[models.RankAndScore]] containing the rank of `member` and its score. If `key` doesn't exist, or if `member` is not present in the set, an empty [models.Result] will be returned.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.ZAdd(
context.Background(),
"key1",
map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0, "four": 4.0},
)
res, err := client.ZRevRankWithScore(context.Background(), "key1", "two")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(res.Value().Rank)
fmt.Println(res.Value().Score)
Output: 4 2 2
func (*ClusterClient) ZScan ¶
func (client *ClusterClient) ZScan(ctx context.Context, key string, cursor models.Cursor) (models.ScanResult, error)
Iterates incrementally over a sorted set.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
key - The key of the sorted set.
cursor - The cursor that points to the next iteration of results.
A value of `"0"` indicates the start of the search.
For Valkey 8.0 and above, negative cursors are treated like the initial cursor("0").
Return value:
An object which holds the next cursor and the subset of the hash held by `key`. The cursor will return `false` from `IsFinished()` method on the last iteration of the subset. The data array in the result is always an array of the subset of the sorted set held in `key`. The array is a flattened series of `string` pairs, where the value is at even indices and the score is at odd indices.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.ZAdd(
context.Background(),
"key1",
map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0, "four": 4.0},
)
result, err := client.ZScan(context.Background(), "key1", models.NewCursor())
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println("Cursor:", result.Cursor)
fmt.Println("Collection:", result.Data)
Output: Cursor: 0 Collection: [one 1 two 2 three 3 four 4]
func (*ClusterClient) ZScanWithOptions ¶
func (client *ClusterClient) ZScanWithOptions( ctx context.Context, key string, cursor models.Cursor, options options.ZScanOptions, ) (models.ScanResult, error)
Iterates incrementally over a sorted set.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. cursor - The cursor that points to the next iteration of results. options - The options for the command. See [options.ZScanOptions] for details.
Return value:
An object which holds the next cursor and the subset of the hash held by `key`. The cursor will return `false` from `IsFinished()` method on the last iteration of the subset. The data array in the result is always an array of the subset of the sorted set held in `key`. The array is a flattened series of `string` pairs, where the value is at even indices and the score is at odd indices.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
client.ZAdd(
context.Background(),
"key1",
map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0, "four": 4.0},
)
result, err := client.ZScanWithOptions(
context.Background(),
"key1",
models.NewCursor(),
*options.NewZScanOptions().SetMatch("*"),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println("Cursor:", result.Cursor)
fmt.Println("Collection:", result.Data)
Output: Cursor: 0 Collection: [one 1 two 2 three 3 four 4]
func (*ClusterClient) ZScore ¶
func (client *ClusterClient) ZScore(ctx context.Context, key string, member string) (models.Result[float64], error)
Returns the score of `member` in the sorted set stored at `key`.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. key - The key of the sorted set. member - The member whose score is to be retrieved.
Return value:
The score of the member. If `member` does not exist in the sorted set, `nil` is returned. If `key` does not exist, `nil` is returned.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
result, err := client.ZAdd(
context.Background(),
"key1",
map[string]float64{"one": 1.0, "two": 2.0, "three": 3.0, "four": 4.0},
)
result1, err := client.ZScore(context.Background(), "key1", "three")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(result)
fmt.Println(result1)
Output: 4 {3 false}
func (*ClusterClient) ZUnion ¶
Returns the union of members from sorted sets specified by the given `keys`. To get the elements with their scores, see Client.ZUnionWithScores or ClusterClient.ZUnionWithScores.
Since:
Valkey 6.2.0 and above.
Note:
When in cluster mode, all keys must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution. keys - The keys of the sorted sets.
Return Value:
The resulting sorted set from the union.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
memberScoreMap1 := map[string]float64{
"one": 1.0,
"two": 2.0,
}
memberScoreMap2 := map[string]float64{
"two": 3.5,
"three": 3.0,
}
client.ZAdd(context.Background(), "{key}1", memberScoreMap1)
client.ZAdd(context.Background(), "{key}2", memberScoreMap2)
zUnionResult, _ := client.ZUnion(context.Background(), options.KeyArray{Keys: []string{"{key}1", "{key}2"}})
fmt.Println(zUnionResult)
Output: [one three two]
func (*ClusterClient) ZUnionStore ¶
func (client *ClusterClient) ZUnionStore( ctx context.Context, destination string, keysOrWeightedKeys options.KeysOrWeightedKeys, ) (int64, error)
Computes the union of sorted sets given by the specified `KeysOrWeightedKeys`, and stores the result in `destination`. If `destination` already exists, it is overwritten. Otherwise, a new sorted set will be created.
Note:
When in cluster mode, `destination` and all keys in `keysOrWeightedKeys` must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
destination - The key of the destination sorted set.
keysOrWeightedKeys - The keys or weighted keys of the sorted sets, see - [options.KeysOrWeightedKeys].
- Use `options.NewKeyArray()` for keys only.
- Use `options.NewWeightedKeys()` for weighted keys with score multipliers.
Return Value:
The number of elements in the resulting sorted set stored at `destination`.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
memberScoreMap1 := map[string]float64{
"one": 1.0,
"two": 2.0,
}
memberScoreMap2 := map[string]float64{
"two": 3.5,
"three": 3.0,
}
client.ZAdd(context.Background(), "{key}1", memberScoreMap1)
client.ZAdd(context.Background(), "{key}2", memberScoreMap2)
zUnionStoreResult, err := client.ZUnionStore(context.Background(),
"{key}dest",
options.KeyArray{Keys: []string{"{key}1", "{key}2"}},
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(zUnionStoreResult)
Output: 3
func (*ClusterClient) ZUnionStoreWithOptions ¶
func (client *ClusterClient) ZUnionStoreWithOptions( ctx context.Context, destination string, keysOrWeightedKeys options.KeysOrWeightedKeys, zUnionOptions options.ZUnionOptions, ) (int64, error)
Computes the union of sorted sets given by the specified `KeysOrWeightedKeys`, and stores the result in `destination`. If `destination` already exists, it is overwritten. Otherwise, a new sorted set will be created.
Note:
When in cluster mode, `destination` and all keys in `keysOrWeightedKeys` must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
destination - The key of the destination sorted set.
keysOrWeightedKeys - The keys or weighted keys of the sorted sets, see - [options.KeysOrWeightedKeys].
- Use `options.NewKeyArray()` for keys only.
- Use `options.NewWeightedKeys()` for weighted keys with score multipliers.
zUnionOptions - The options for the ZUnionStore command, see - [options.ZUnionOptions].
Optional `aggregate` option specifies the aggregation strategy to apply when
combining the scores of elements.
Return Value:
The number of elements in the resulting sorted set stored at `destination`.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
memberScoreMap1 := map[string]float64{
"one": 1.0,
"two": 2.0,
}
memberScoreMap2 := map[string]float64{
"two": 3.5,
"three": 3.0,
}
client.ZAdd(context.Background(), "{key}1", memberScoreMap1)
client.ZAdd(context.Background(), "{key}2", memberScoreMap2)
zUnionStoreWithOptionsResult, err := client.ZUnionStoreWithOptions(context.Background(),
"{key}dest",
options.KeyArray{Keys: []string{"{key}1", "{key}2"}},
*options.NewZUnionOptions().SetAggregate(options.AggregateSum),
)
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
}
fmt.Println(zUnionStoreWithOptionsResult)
Output: 3
func (*ClusterClient) ZUnionWithScores ¶
func (client *ClusterClient) ZUnionWithScores( ctx context.Context, keysOrWeightedKeys options.KeysOrWeightedKeys, zUnionOptions options.ZUnionOptions, ) ([]models.MemberAndScore, error)
Returns the union of members and their scores from sorted sets specified by the given `keysOrWeightedKeys`.
Since:
Valkey 6.2.0 and above.
Note:
When in cluster mode, all keys in `keysOrWeightedKeys` must map to the same hash slot.
See valkey.io for details.
Parameters:
ctx - The context for controlling the command execution.
keysOrWeightedKeys - The keys of the sorted sets with possible formats:
- Use `KeyArray` for keys only.
- Use `WeightedKeys` for weighted keys with score multipliers.
zUnionOptions - The options for the ZUnionStore command, see - [options.ZUnionOptions].
Optional `aggregate` option specifies the aggregation strategy to apply when
combining the scores of elements.
Return Value:
The resulting sorted set from the union.
Example ¶
var client *ClusterClient = getExampleClusterClient() // example helper function
memberScoreMap1 := map[string]float64{
"one": 1.0,
"two": 2.0,
}
memberScoreMap2 := map[string]float64{
"two": 3.5,
"three": 3.0,
}
client.ZAdd(context.Background(), "{key}1", memberScoreMap1)
client.ZAdd(context.Background(), "{key}2", memberScoreMap2)
zUnionResult, _ := client.ZUnionWithScores(context.Background(),
options.KeyArray{Keys: []string{"{key}1", "{key}2"}},
*options.NewZUnionOptions().SetAggregate(options.AggregateSum),
)
fmt.Println(zUnionResult)
Output: [{one 1} {three 3} {two 5.5}]
type ConfigurationError ¶
type ConfigurationError struct {
// contains filtered or unexported fields
}
ConfigurationError is a client error that occurs when there is an issue with client configuration.
func NewConfigurationError ¶
func NewConfigurationError(message string) *ConfigurationError
func (*ConfigurationError) Error ¶
func (e *ConfigurationError) Error() string
type ConnectionError ¶
type ConnectionError struct {
// contains filtered or unexported fields
}
ConnectionError is a client error that occurs when there is an error while connecting or when a connection disconnects.
func NewConnectionError ¶
func NewConnectionError(message string) *ConnectionError
func (*ConnectionError) Error ¶
func (e *ConnectionError) Error() string
type DisconnectError ¶
type DisconnectError struct {
// contains filtered or unexported fields
}
DisconnectError is a client error that indicates a connection problem between Glide and server.
func NewDisconnectError ¶
func NewDisconnectError(message string) *DisconnectError
func (*DisconnectError) Error ¶
func (e *DisconnectError) Error() string
type ExecAbortError ¶
type ExecAbortError struct {
// contains filtered or unexported fields
}
ExecAbortError is a client error that occurs when a transaction is aborted.
func NewExecAbortError ¶
func NewExecAbortError(message string) *ExecAbortError
func (*ExecAbortError) Error ¶
func (e *ExecAbortError) Error() string
type MessageCallbackError ¶
type MessageCallbackError struct {
// contains filtered or unexported fields
}
func (*MessageCallbackError) Cause ¶
func (e *MessageCallbackError) Cause() error
func (*MessageCallbackError) Error ¶
func (e *MessageCallbackError) Error() string
type MessageHandler ¶
type MessageHandler struct {
// contains filtered or unexported fields
}
func NewMessageHandler ¶
func NewMessageHandler(callback config.MessageCallback, context any) *MessageHandler
func (*MessageHandler) GetQueue ¶
func (handler *MessageHandler) GetQueue() *PubSubMessageQueue
type OpenTelemetry ¶
type OpenTelemetry struct{}
OpenTelemetry provides functionality for OpenTelemetry integration.
This struct provides a centralized way to initialize OpenTelemetry and control sampling behavior at runtime.
Example usage:
import "github.com/valkey-io/valkey-glide/go/v2"
config := glide.OpenTelemetryConfig{
Traces: &glide.OpenTelemetryTracesConfig{
Endpoint: "http://localhost:4318/v1/traces",
SamplePercentage: 10, // Optional, defaults to 1. Can also be changed at runtime via `SetSamplePercentage()`
},
Metrics: &glide.OpenTelemetryMetricsConfig{
Endpoint: "http://localhost:4318/v1/metrics",
},
FlushIntervalMs: &interval, // Optional, defaults to 5000, e.g. interval := int64(1000)
}
err := glide.GetOtelInstance().Init(config)
if err != nil {
log.Fatalf("Failed to initialize OpenTelemetry: %v", err)
}
Note: OpenTelemetry can only be initialized once per process. Subsequent calls to Init() will be ignored. This is by design, as OpenTelemetry is a global resource that should be configured once at application startup.
Example ¶
ExampleOpenTelemetry demonstrates creating parent spans and using them with Valkey commands
// Initialize OpenTelemetry with file exporter for demonstration
config := OpenTelemetryConfig{
Traces: &OpenTelemetryTracesConfig{
Endpoint: "file:///tmp/glide_traces.json",
SamplePercentage: 100, // Sample all requests for demo
},
SpanFromContext: DefaultSpanFromContext,
}
err := GetOtelInstance().Init(config)
if err != nil {
// OpenTelemetry may already be initialized from previous examples
// This is expected behavior in the test environment
}
// Create a parent span for the user operation
spanPtr, err := GetOtelInstance().CreateSpan("user-operation")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
defer GetOtelInstance().EndSpan(spanPtr)
// Get a Valkey client
client := getExampleClient()
// Add the span to context - this creates parent-child relationship
ctx := WithSpan(context.Background(), spanPtr)
// Execute a Valkey command - this will create a child span under "user-operation"
result, err := client.Set(ctx, "example:key", "example_value")
if err != nil {
fmt.Println("Glide example failed with an error: ", err)
return
}
fmt.Println(result)
func GetOtelInstance ¶
func GetOtelInstance() *OpenTelemetry
GetOtelInstance returns the singleton OpenTelemetry instance.
func (*OpenTelemetry) CreateSpan ¶ added in v2.1.0
func (o *OpenTelemetry) CreateSpan(name string) (uint64, error)
CreateSpan creates a new OpenTelemetry span with the given name and returns a pointer to the span. This is a PUBLIC API for users to create parent spans that can be used with command execution.
Parameters:
- name: The name of the span to create
Returns:
- uint64: A pointer to the created span (0 on failure)
- error: An error if the span creation fails or OpenTelemetry is not initialized
Example usage:
spanPtr, err := glide.GetOtelInstance().CreateSpan("user-operation")
if err != nil {
log.Printf("Failed to create span: %v", err)
return
}
defer glide.GetOtelInstance().EndSpan(spanPtr)
Note: The caller is responsible for calling EndSpan() to properly clean up the span.
func (*OpenTelemetry) EndSpan ¶ added in v2.1.0
func (o *OpenTelemetry) EndSpan(spanPtr uint64)
EndSpan ends and drops an OpenTelemetry span given its pointer. This is a PUBLIC API for users to properly clean up spans created with CreateSpan().
Parameters:
- spanPtr: A pointer to the span to end (obtained from CreateSpan)
Note: This method is safe to call with a zero pointer (no-op). It is the caller's responsibility to ensure the span pointer is valid.
Example usage:
spanPtr, err := glide.GetOtelInstance().CreateSpan("user-operation")
if err != nil {
log.Printf("Failed to create span: %v", err)
return
}
defer glide.GetOtelInstance().EndSpan(spanPtr)
func (*OpenTelemetry) GetSamplePercentage ¶
func (o *OpenTelemetry) GetSamplePercentage() int32
GetSamplePercentage returns the sample percentage for traces only if OpenTelemetry is initialized and the traces config is set, otherwise returns 0.
func (*OpenTelemetry) Init ¶
func (o *OpenTelemetry) Init(openTelemetryConfig OpenTelemetryConfig) error
Init initializes the OpenTelemetry instance with the provided configuration. It can only be called once per process. Subsequent calls will be ignored.
func (*OpenTelemetry) IsInitialized ¶
func (o *OpenTelemetry) IsInitialized() bool
IsInitialized returns true if the OpenTelemetry instance is initialized, false otherwise.
func (*OpenTelemetry) SetSamplePercentage ¶
func (o *OpenTelemetry) SetSamplePercentage(percentage int32) error
SetSamplePercentage sets the percentage of requests to be sampled and traced. Must be a value between 0 and 100. This setting only affects traces, not metrics.
type OpenTelemetryConfig ¶
type OpenTelemetryConfig struct {
// Traces configuration for exporting trace data. If nil, trace data will not be exported.
Traces *OpenTelemetryTracesConfig
// Metrics configuration for exporting metrics data. If nil, metrics data will not be exported.
Metrics *OpenTelemetryMetricsConfig
// (Optional)FlushIntervalMs is the interval in milliseconds between consecutive exports of telemetry data.
// If not specified, defaults to 5000.
FlushIntervalMs *int64
// (Optional) SpanFromContext is a function that extracts parent span information from a context.Context.
// When provided, Glide will use this function to create child spans under existing parent spans,
// enabling end-to-end tracing across your application and database operations.
//
// The function should return:
// - spanPtr: A span pointer (uint64) obtained from CreateSpan() or 0 if no parent span is found
//
// If this function is not provided or returns 0, Glide will create independent spans
// as it currently does. If the function panics, Glide will gracefully fallback to creating
// independent spans.
//
// Example implementation:
// SpanFromContext: func(ctx context.Context) uint64 {
// if spanPtr, ok := ctx.Value(glide.SpanContextKey).(uint64); ok && spanPtr != 0 {
// return spanPtr
// }
// return 0
// }
//
// Note: This function must be thread-safe as it may be called concurrently from multiple goroutines.
SpanFromContext func(ctx context.Context) (spanPtr uint64)
}
OpenTelemetryConfig represents the configuration for OpenTelemetry integration. It allows configuring how telemetry data (traces and metrics) is exported to an OpenTelemetry collector.
Example usage:
import "github.com/valkey-io/valkey-glide/go/v2"
config := glide.OpenTelemetryConfig{
Traces: &glide.OpenTelemetryTracesConfig{
Endpoint: "http://localhost:4318/v1/traces",
SamplePercentage: 10, // Optional, defaults to 1. Can also be changed at runtime via `SetSamplePercentage()`
},
Metrics: &glide.OpenTelemetryMetricsConfig{
Endpoint: "http://localhost:4318/v1/metrics",
},
FlushIntervalMs: &interval, // Optional, defaults to 5000, e.g. interval := int64(1000)
SpanFromContext: func(ctx context.Context) uint64 {
// Extract span pointer from context for parent-child span relationships
if spanPtr, ok := ctx.Value(glide.SpanContextKey).(uint64); ok && spanPtr != 0 {
return spanPtr
}
return 0
},
}
err := glide.GetOtelInstance().Init(config)
if err != nil {
log.Fatalf("Failed to initialize OpenTelemetry: %v", err)
}
type OpenTelemetryMetricsConfig ¶
type OpenTelemetryMetricsConfig struct {
Endpoint string
}
OpenTelemetryMetricsConfig represents the configuration for exporting OpenTelemetry metrics.
- Endpoint: The endpoint to which metrics data will be exported. Expected format:
- For gRPC: `grpc://host:port`
- For HTTP: `http://host:port` or `https://host:port`
- For file exporter: `file:///absolute/path/to/folder/file.json`
type OpenTelemetryTracesConfig ¶
OpenTelemetryTracesConfig represents the configuration for exporting OpenTelemetry traces.
Endpoint: The endpoint to which trace data will be exported. Expected format:
- For gRPC: `grpc://host:port`
- For HTTP: `http://host:port` or `https://host:port`
- For file exporter: `file:///absolute/path/to/folder/file.json`
SamplePercentage: The percentage of requests to sample and create a span for, used to measure command duration.
- Must be between 0 and 100. If not specified, defaults to 1.
Note: There is a tradeoff between sampling percentage and performance. Higher sampling percentages will provide more detailed telemetry data but will impact performance. It is recommended to keep this number low (1-5%) in production environments unless you have specific needs for higher sampling rates.
type PubSubMessageQueue ¶
type PubSubMessageQueue struct {
// contains filtered or unexported fields
}
func NewPubSubMessageQueue ¶
func NewPubSubMessageQueue() *PubSubMessageQueue
func (*PubSubMessageQueue) Pop ¶
func (queue *PubSubMessageQueue) Pop() *models.PubSubMessage
func (*PubSubMessageQueue) Push ¶
func (queue *PubSubMessageQueue) Push(message *models.PubSubMessage)
func (*PubSubMessageQueue) RegisterSignalChannel ¶
func (queue *PubSubMessageQueue) RegisterSignalChannel(ch chan struct{})
func (*PubSubMessageQueue) UnregisterSignalChannel ¶
func (queue *PubSubMessageQueue) UnregisterSignalChannel(ch chan struct{})
func (*PubSubMessageQueue) WaitForMessage ¶
func (queue *PubSubMessageQueue) WaitForMessage() <-chan *models.PubSubMessage
type TimeoutError ¶
type TimeoutError struct {
// contains filtered or unexported fields
}
TimeoutError is a client error that occurs when a request times out.
func NewTimeoutError ¶
func NewTimeoutError(message string) *TimeoutError
func (*TimeoutError) Error ¶
func (e *TimeoutError) Error() string
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package config provides client configuration options for Valkey GLIDE.
|
Package config provides client configuration options for Valkey GLIDE. |
|
Package constants defines common constants used throughout Valkey GLIDE.
|
Package constants defines common constants used throughout Valkey GLIDE. |
|
Package integTest contains integration tests for Valkey GLIDE clients.
|
Package integTest contains integration tests for Valkey GLIDE clients. |
|
Package models defines data structures and response types for Valkey GLIDE.
|
Package models defines data structures and response types for Valkey GLIDE. |
|
Package options provides command options and configuration structures for Valkey GLIDE operations.
|
Package options provides command options and configuration structures for Valkey GLIDE operations. |
|
Package pipeline provides batch command execution capabilities for Valkey GLIDE clients.
|
Package pipeline provides batch command execution capabilities for Valkey GLIDE clients. |
|
rustbin
|
|
|
aarch64-apple-darwin
Package rustbin_aarch64_apple_darwin exists solely to ensure this directory is included when using 'go mod vendor'.
|
Package rustbin_aarch64_apple_darwin exists solely to ensure this directory is included when using 'go mod vendor'. |
|
aarch64-unknown-linux-gnu
Package rustbin_aarch64_unknown_linux_gnu exists solely to ensure this directory is included when using 'go mod vendor'.
|
Package rustbin_aarch64_unknown_linux_gnu exists solely to ensure this directory is included when using 'go mod vendor'. |
|
aarch64-unknown-linux-musl
Package rustbin_aarch64_unknown_linux_musl exists solely to ensure this directory is included when using 'go mod vendor'.
|
Package rustbin_aarch64_unknown_linux_musl exists solely to ensure this directory is included when using 'go mod vendor'. |
|
x86_64-apple-darwin
Package rustbin_x86_64_apple_darwin exists solely to ensure this directory is included when using 'go mod vendor'.
|
Package rustbin_x86_64_apple_darwin exists solely to ensure this directory is included when using 'go mod vendor'. |
|
x86_64-unknown-linux-gnu
Package rustbin_x86_64_unknown_linux_gnu exists solely to ensure this directory is included when using 'go mod vendor'.
|
Package rustbin_x86_64_unknown_linux_gnu exists solely to ensure this directory is included when using 'go mod vendor'. |
|
x86_64-unknown-linux-musl
Package rustbin_x86_64_unknown_linux_musl exists solely to ensure this directory is included when using 'go mod vendor'.
|
Package rustbin_x86_64_unknown_linux_musl exists solely to ensure this directory is included when using 'go mod vendor'. |