Valkey Data Types
Updated: May 3, 2025
By: Joseph Horace
Table of Contents
Introduction
Valkey is a high-performance, in-memory data store and drop-in Redis replacement designed for speed, scalability, and extensibility. While it retains Redis's familiar interface, understanding how Valkey handles data types under the hood—and how to operate on them efficiently—is essential for building robust, real-time systems.
This guide provides a deep dive into each of Valkey’s core data types, from strings and lists to advanced structures like streams and HyperLogLogs.
Whether you're using Valkey for caching, queuing, pub/sub, analytics, or geospatial indexing, mastering these operations will help you write leaner, faster, and more predictable applications.
Strings
The most fundamental data type in Valkey, strings represent sequences of bytes. They are versatile, supporting operations like appending, substring manipulation, and numeric increments. Strings are ideal for storing simple values such as user profiles, counters, or cached content. Here are common operations and code examples in strings.
Basic Set/Get
SET key value – Sets the value of a key, replacing it if it already exists.
GET key – Retrieves the current value of a key.
SETNX key value – Sets the value only if the key does not already exist.
GETDEL key – Returns and deletes the value of a key in one atomic operation.
GETSET key value – Replaces the value and returns the old value in a single step.
STRLEN key – Returns the number of bytes in the string value.
Expiration Support
SETEX key seconds value – Sets a key with a value and a TTL in seconds.
PSETEX key milliseconds value – Sets a key with a value and a TTL in milliseconds.
SET key value EX seconds – Shorthand to set a key with an expiry using modifiers.
SET key value PX milliseconds – Sets key with expiry in milliseconds using PX modifier.
SET key value NX | XX – NX sets only if absent; XX sets only if present.
Numeric Operations
INCR key – Increments the integer value of a key by 1.
DECR key – Decrements the integer value of a key by 1.
INCRBY key increment – Increments the value by the specified integer.
DECRBY key decrement – Decrements the value by the specified integer.
INCRBYFLOAT key increment – Increments the value by a floating-point number.
Substring / Modification
APPEND key value – Appends the given value to the end of the existing string.
GETRANGE key start end – Returns a substring based on byte offsets.
SETRANGE key offset value – Overwrites part of the string starting at the given offset.
Bit Operations
SETBIT key offset value – Sets or clears a specific bit at the given offset.
GETBIT key offset – Gets the value of the bit at the given offset.
BITCOUNT key [start end] – Counts the number of bits set to 1 in a string or range.
BITOP operation destkey key [key ...] – Performs a bitwise operation (AND, OR, XOR, NOT) on multiple keys.
BITPOS key bit [start] [end] – Finds the first occurrence of the specified bit (0 or 1).
Multi-Key Operations
MSET key1 val1 key2 val2 ... – Sets multiple keys to their respective values.
MGET key1 key2 ... – Retrieves the values of multiple keys.
MSETNX key1 val1 ... – Sets multiple keys only if none of them exist.
Code Examples of String Operations in Valkey
SET user:name "Alice"
GET user:name
INCR user:visits
DECR user:credits
APPEND user:bio " is a developer."
GETRANGE user:bio 0 15
Lists
Valkey lists are ordered collections of string elements, similar to linked lists. They allow efficient insertion and removal from both ends and are ideal for queues, logs, task buffers, and message streams. Here are common operations and code examples in lists.
Pushing & Popping
- LPUSH key value [value ...] – Inserts one or more values at the head (left) of the list.
- RPUSH key value [value ...] – Inserts one or more values at the tail (right) of the list.
- LPOP key – Removes and returns the first element (leftmost) of the list.
- RPOP key – Removes and returns the last element (rightmost) of the list.
- LPOP key COUNT count – Pops multiple elements from the left.
- RPOP key COUNT count – Pops multiple elements from the right.
Blocking Pops
- BLPOP key [key ...] timeout – Blocks until a left pop is possible or timeout occurs.
- BRPOP key [key ...] timeout – Blocks until a right pop is possible or timeout occurs.
Indexing & Range
- LINDEX key index – Returns the element at the given index.
- LRANGE key start stop – Returns a sublist between the start and stop indexes.
- LLEN key – Returns the length of the list.
Modification
- LSET key index value – Sets the value at a specific index.
- LREM key count value – Removes elements matching the value (count defines how many).
- LTRIM key start stop – Trims the list to only the specified index range.
Atomic Transfer
- RPOPLPUSH source destination – Atomically pops from the tail of one list and pushes to the head of another.
BRPOPLPUSH source destination timeout – Blocking version of RPOPLPUSH.
Code Examples of List Operations in Valkey
LPUSH tasks "email" "code"
RPUSH tasks "review"
LPOP tasks
RPOP tasks
LRANGE tasks 0 -1
LLEN tasks
LSET tasks 1 "debug"
LREM tasks 0 "email"
LTRIM tasks 0 1
RPOPLPUSH tasks processing
Hashes
Valkey hashes are maps between string fields and string values—perfect for representing objects like user profiles, settings, or configuration data. They allow you to store multiple key-value pairs under a single key and manipulate individual fields without retrieving the entire structure. Here are common operations and code examples in hashes.
Set & Get Fields
- HSET key field value [field value ...] – Sets one or more field-value pairs in the hash.
- HGET key field – Retrieves the value associated with the specified field.
- HMSET key field value [field value ...](deprecated, use HSET instead) – Sets multiple fields at once.
- HMGET key field [field ...] – Retrieves values of one or more specified fields.
- HGETALL key – Retrieves all fields and values in the hash.
Existence & Removal
- HEXISTS key field – Checks if a field exists in the hash.
- HDEL key field [field ...] – Deletes one or more fields from the hash.
Length & Keys
- HLEN key – Returns the number of fields in the hash.
- HKEYS key – Returns all field names in the hash.
- HVALS key – Returns all values in the hash.
Numeric Operations
- HINCRBY key field increment – Increments the value of a field by an integer.
- HINCRBYFLOAT key field increment – Increments the value of a field by a floating-point number.
Code Examples of Hash Operations in Valkey
HSET user:1001 name "Alice" age "30"
HGET user:1001 name
HGETALL user:1001
HINCRBY user:1001 age 1
HDEL user:1001 age
HEXISTS user:1001 name
HLEN user:1001
HKEYS user:1001
HVALS user:1001
HMSET user:1001 country "US" status "active"
HMGET user:1001 name status
Sets
Valkey sets are unordered collections of unique strings. They are ideal for use cases like tags, followers, memberships, or presence tracking. Sets support efficient operations like union, intersection, and difference, making them perfect for mathematical set operations.Here are common operations and code examples in sets.
Add, Remove, and Check Membership
- SADD key member [member ...] – Adds one or more members to a set.
- SREM key member [member ...] – Removes one or more members from a set.
- SISMEMBER key member – Checks if a member exists in the set.
- SMISMEMBER key member [member ...] – Checks existence of multiple members.
- SCARD key – Returns the number of members in the set.
Retrieve Members
- SMEMBERS key – Returns all members in the set.
- SRANDMEMBER key [count] – Returns one or more random members from the set.
- SPOP key [count] – Removes and returns one or more random members.
Set Operations
- SUNION key [key ...] – Returns the union of all given sets.
- SINTER key [key ...] – Returns the intersection of all given sets.
- SDIFF key [key ...] – Returns the difference between the first set and all others.
- SUNIONSTORE destination key [key ...] – Stores the result of union into a new set.
- SINTERSTORE destination key [key ...] – Stores the result of intersection.
- SDIFFSTORE destination key [key ...] – Stores the result of difference.
SADD tags "nodejs" "redis" "api"
SREM tags "api"
SISMEMBER tags "redis"
SMISMEMBER tags "redis" "java"
SCARD tags
SMEMBERS tags
SRANDMEMBER tags 2
SPOP tags 1
SADD frontend "react" "vue"
SADD backend "nodejs" "spring"
SUNION frontend backend
SINTER frontend backend
SDIFF frontend backend
SUNIONSTORE all_tech frontend backend
SINTERSTORE common_tech frontend backend
SDIFFSTORE exclusive_frontend frontend backend
Sorted Sets (ZSets)
Valkey sorted sets are similar to regular sets but with an added score for each member, which is used to order the elements. They are useful for ranking systems, leaderboards, time-series data, and any use case that requires maintaining ordered collections. Here are common operations and code examples in zsets.
Add & Remove Members
- ZADD key score member [score member ...] – Adds one or more members with scores to the sorted set.
- ZREM key member [member ...] – Removes one or more members from the sorted set.
- ZINCRBY key increment member – Increments the score of a member in the sorted set.
Retrieve Members
- ZRANGE key start stop [WITHSCORES] – Returns members within a specific range, optionally with their scores.
- ZREVRANGE key start stop [WITHSCORES] – Returns members within a specific range, ordered by descending score.
- ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count] – Returns members within a score range, optionally with their scores.
- ZREVRANGEBYSCORE key max min [WITHSCORES] [LIMIT offset count] – Returns members within a score range, ordered by descending score.
- ZREVRANK key member – Returns the rank of a member in a sorted set, ordered by descending score.
- ZRANK key member – Returns the rank of a member in a sorted set, ordered by ascending score.
Set Size & Stats
- ZCARD key – Returns the number of members in the sorted set.
- ZSCORE key member – Returns the score of a member in the sorted set.
Set Operations
- ZUNIONSTORE destination numkeys key [key ...] WEIGHTS weight [weight ...] AGGREGATE SUM | MIN | MAX – Stores the union of multiple sorted sets into a destination.
- ZINTERSTORE destination numkeys key [key ...] WEIGHTS weight [weight ...] AGGREGATE SUM | MIN | MAX – Stores the intersection of multiple sorted sets into a destination.
ZADD leaderboard 100 "Alice" 150 "Bob" 90 "Charlie"
ZREM leaderboard "Charlie"
ZINCRBY leaderboard 10 "Alice"
ZRANGE leaderboard 0 -1 WITHSCORES
ZREVRANGE leaderboard 0 -1 WITHSCORES
ZRANGEBYSCORE leaderboard 100 200 WITHSCORES
ZREVRANGEBYSCORE leaderboard 200 100 WITHSCORES
ZRANK leaderboard "Bob"
ZREVRANK leaderboard "Bob"
ZCARD leaderboard
ZSCORE leaderboard "Alice"
ZUNIONSTORE top_players 2 leaderboard team_leaderboard AGGREGATE SUM
ZINTERSTORE top_players_common 2 leaderboard team_leaderboard AGGREGATE MAX
Bitmaps
Valkey bitmaps are a way to manipulate individual bits within a string. These operations are often used for tracking boolean states, flags, or counters. Each bit is treated as a 0 or 1, and Valkey allows you to perform bit-level operations efficiently. Bitmaps are ideal for scenarios like tracking user activity, online/offline status, or representing binary data. Here are common operations and code examples in bitmaps.
Set and Get Bits
- SETBIT key offset value – Sets or clears a specific bit at the given offset (1 for set, 0 for clear).
- GETBIT key offset – Gets the value of the bit at the given offset.
Count and Position Bits
- BITCOUNT key [start end] – Counts the number of bits set to 1 in a string or a specific range.
- BITPOS key bit [start] [end] – Finds the first occurrence of the specified bit (0 or 1) in the string or within the given range.
Bitwise Operations
- BITOP operation destkey key [key ...] – Performs a bitwise operation (AND, OR, XOR, NOT) on one or more keys and stores the result in a destination key.
Code Examples of Bitmap Operations in Valkey
SETBIT user:1 0 1
SETBIT user:1 1 0
GETBIT user:1 0
GETBIT user:1 1
BITCOUNT user:1
BITPOS user:1 1
BITOP AND result key1 key2
BITOP OR result key1 key2
BITOP XOR result key1 key2
HyperLogLogs
Valkey HyperLogLogs are used for approximating the count of unique elements in large datasets, offering a very space-efficient way to track cardinality. They are ideal for use cases where you need to estimate the number of unique items (like tracking unique visitors or IPs) without needing the exact count. HyperLogLogs use probabilistic algorithms, which provide an estimate with a small margin of error while consuming minimal memory.
Here are common operations and code examples in hyperloglog.
Add Elements
- PFADD key element [element ...] – Adds one or more elements to the HyperLogLog data structure.
Count Unique Elements
- PFCOUNT key [key ...] – Returns the approximated count of unique elements across one or more HyperLogLogs.
Merge HyperLogLogs
- PFMERGE destkey sourcekey [sourcekey ...] – Merges multiple HyperLogLogs into a single destination HyperLogLog.
Code Examples of HyperLogLog Operations in Valkey
PFADD unique_users "user1" "user2" "user3"
PFCOUNT unique_users
PFADD unique_users "user4"
PFCOUNT unique_users
PFMERGE merged_users unique_users other_users
PFCOUNT merged_users
Streams
Valkey Streams are an advanced data structure for handling real-time data, designed for logging, event sourcing, and message queues. They allow you to append messages to a stream, store them with unique IDs, and retrieve them in various ways. Streams provide rich capabilities for handling time-series data, event logs, and other real-time data scenarios where ordering and consumer management are essential. Here are common operations and code examples in streams.
Appending Messages
- XADD key ID field value [field value ...] – Appends a new entry to the stream with a unique ID and one or more fields and values.
Reading from Streams
- XREAD key [key ...] STREAMS key [ID] – Reads data from one or more streams starting from a given ID.
- XREADBLOCK key [key ...] BLOCK milliseconds STREAMS key [ID] – Reads data from streams with blocking support.
Pending Entries
- XPENDING key [group] – Returns information about pending messages in a stream.
- XCLAIM key group consumer min-idle-time ID [ID ...] – Claims pending messages from a stream for a specific consumer group.
Consumer Groups
- XGROUP CREATE key group ID [MKSTREAM] – Creates a consumer group for a stream.
- XGROUP SETID key group ID – Changes the consumer group's ID to a new stream entry.
- XACK key group ID [ID ...] – Acknowledges the consumption of a message by a consumer group.
Deleting Streams
- XDEL key ID [ID ...] – Deletes messages from the stream with the given IDs.
Code Examples of Stream Operations in Valkey
XADD mystream * message "Hello" timestamp "1633036800"
XADD mystream * message "Another message" timestamp "1633036860"
XREAD STREAMS mystream 0
XREADBLOCK STREAMS mystream 0 BLOCK 5000
XPENDING mystream group1
XCLAIM mystream group1 consumer1 15000 0
XGROUP CREATE mystream group1 0
XGROUP SETID mystream group1 1633036800
XACK mystream group1 1633036800
XDEL mystream 1633036800
Geospatial
Valkey Geospatial data structures enable storing, querying, and processing location-based data efficiently. These operations support use cases like finding distances between points, storing location-based data (e.g., user coordinates), and querying for nearby locations. Geospatial data types in Valkey support a range of spatial queries like radius searches, bounding box queries, and more. Here are common operations and code examples in geospatial data structure.
Adding Geospatial Data
- GEOADD key longitude latitude member [longitude latitude member ...] – Adds one or more geospatial items (latitude, longitude, and a unique member identifier) to a sorted set.
Retrieving Geospatial Data
- GEODIST key member1 member2 [unit] – Returns the distance between two members in the specified unit (meters, kilometers, miles, etc.).
- GEOPOS key member [member ...] – Returns the longitude and latitude of one or more members in a key.
- GEORADIUS key longitude latitude radius unit [WITHCOORD] [WITHDIST] [WITHHASH] – Returns members in a given radius around a point, with optional additional data (coordinates, distances, or hashes).
- GEORADIUSBYMEMBER key member radius unit [WITHCOORD] [WITHDIST] [WITHHASH] – Returns members within a radius of a given member, with optional additional data.
Geospatial Set Operations
- GEORADIUS key longitude latitude radius unit STORE key – Stores the members found in a radius search into a new key.
- GEORADIUSBYMEMBER key member radius unit STORE key – Stores the members found in a radius search by member into a new key.
Code Examples of Geospatial Operations in Valkey
GEOADD locations 13.361389 38.115556 "Palermo"
GEOADD locations 15.087269 37.502669 "Catania"
GEODIST locations "Palermo" "Catania" km
GEOPOS locations "Palermo"
GEORADIUS locations 15 37 100 km WITHCOORD WITHDIST
GEORADIUSBYMEMBER locations "Palermo" 100 km WITHCOORD WITHDIST
GEORADIUS locations 15 37 100 km STORE nearby
GEORADIUSBYMEMBER locations "Palermo" 100 km STORE nearby
Bloom Filters
Valkey Bloom Filters are a space-efficient probabilistic data structure used to test whether an element is a member of a set. The key feature of Bloom filters is that they can give false positives (i.e., they might incorrectly report that an element exists), but they will never give false negatives (i.e., if the filter says an element doesn’t exist, it definitely does not exist). This makes Bloom filters particularly useful for large datasets where exact membership testing might be too costly. Here are common operations and code examples in bloom filters.
Creating a Bloom Filter
- BF.RESERVE key error_rate capacity – Creates and reserves space for a Bloom filter with the specified error rate and expected capacity.
Adding Elements
- BF.ADD key element [element ...] – Adds one or more elements to the Bloom filter.
Checking Membership
- BF.EXISTS key element [element ...] – Checks whether one or more elements exist in the Bloom filter.
Counting Elements
- BF.COUNT key – Returns the approximate count of unique elements in the Bloom filter (if supported by the implementation).
Code Examples of Bloom Filter Operations in Valkey
BF.RESERVE myfilter 0.01 1000
BF.ADD myfilter "apple" "banana" "cherry"
BF.EXISTS myfilter "apple"
BF.EXISTS myfilter "orange"
BF.COUNT myfilter
Conclusion
In this article, we explored the essential data types and operations offered by Valkey, including Strings, Lists, Sets, Hashes, and more. By understanding these core operations, developers can efficiently manage large datasets and build scalable, high-performance applications. Valkey's rich set of features ensures optimal performance for real-time and complex use cases.
About the Author
Joseph Horace
Horace is a dedicated software developer with a deep passion for technology and problem-solving. With years of experience in developing robust and scalable applications, Horace specializes in building user-friendly solutions using cutting-edge technologies. His expertise spans across multiple areas of software development, with a focus on delivering high-quality code and seamless user experiences. Horace believes in continuous learning and enjoys sharing insights with the community through contributions and collaborations. When not coding, he enjoys exploring new technologies and staying updated on industry trends.