Introduction
Redis, an open-source, in-memory data structure store, is widely used for its high performance, versatility, and simplicity. It supports various data structures, including strings, hashes, lists, sets, and more. This cheatsheet serves as a comprehensive guide to Redis commands, complete with detailed explanations, output examples, and best practices. Whether you're a beginner or an experienced user, this guide will help you understand and effectively utilize Redis in your applications.
General Commands
1. SET key value [EX seconds | PX milliseconds] [NX | XX]
Description: Sets the value of a key with options for expiration and conditional set.
- NX: Set the key only if it does not exist.
- XX: Set the key only if it already exists.
Returns: OK if succeeded, nil if not.
Examples:
SET k1 500 NX
Sets k1 to 500 if k1 does not already exist.
SET k1 20 PX 5000
Sets k1 to 20 with an expiration of 5000 milliseconds.
2. GET key
Description: Returns the value of the given key.
Returns: The value of the key, or nil if the key does not exist.
Example:
GET k1
Returns the value stored at k1.
3. KEYS
Description: Returns all keys matching the pattern.
Note: This is a blocking operation and not recommended for production use.
Example:
KEYS *
Returns all keys in the database.
4. SCAN [cursor] [MATCH pattern] [COUNT count]
Description: Incrementally iterates through the keys space.
Example:
SCAN 0
Returns a cursor and a list of keys. Continue using the cursor to iterate.
SCAN 2
1) 2
2) 17
Returns a cursor 2 and keys.
5. DEL key
Description: Deletes the key and its value.
Returns: The number of keys that were removed.
Example:
DEL k1
Deletes k1.
6. UNLINK key
Description: Deletes the key asynchronously.
Returns: The number of keys that were removed.
Example:
UNLINK k1
Deletes k1 asynchronously.
7. EXISTS key
Description: Checks if a key exists.
Returns: 1 if the key exists, 0 if it does not.
Example:
EXISTS k1
Checks if k1 exists.
8. PEXPIRE key milliseconds
Description: Sets a key's expiration in milliseconds.
Example:
PEXPIRE k1 5000
Sets k1 to expire in 5000 milliseconds.
9. TTL key
Description: Returns the remaining time to live of a key in seconds.
Returns: TTL in seconds, -2 if the key does not exist, -1 if the key is persistent.
Example:
TTL k1
Returns the TTL of k1.
10. PERSIST key
Description: Removes the expiration from a key.
Example:
PERSIST k1
Makes k1 persistent (no expiration).
11. INCR key | INCRBY key increment
Description: Increments the integer value of a key by one or by the given increment.
Example:
INCR k1
Increments the value of k1 by 1.
INCRBY k1 10
Increments the value of k1 by 10.
12. TYPE key
Description: Returns the data type of the value stored at the key.
Example:
TYPE k1
Returns the type of k1.
13. OBJECT ENCODING key
Description: Returns the internal encoding of the value stored at the key.
Example:
OBJECT ENCODING k1
Returns the encoding type of k1.
14. DBSIZE
Description: Returns the number of keys in the selected database.
Example:
DBSIZE
Returns the number of keys.
15. APPEND key value
Description: Appends a value to the existing value of the key. Creates a new key if it does not exist.
Example:
APPEND k1 "World"
Appends "World" to the value of k1.
16. GETRANGE key start end
Description: Returns a substring of the value stored at the key.
Example:
GETRANGE k1 0 4
Returns the substring of k1 from index 0 to 4.
17. STRLEN key
Description: Returns the length of the string value stored at the key.
Example:
STRLEN k1
Returns the length of the value of k1.
18. FLUSHDB [ASYNC]
Description: Deletes all keys in the current database.
Example:
FLUSHDB
Deletes all keys in the current database.
19. FLUSHALL [ASYNC]
Description: Deletes all keys in all databases.
Example:
FLUSHALL
Deletes all keys in all databases.
20. EXPIRE key seconds
Description: Sets a key's expiration in seconds.
Example:
EXPIRE k1 10
Sets k1 to expire in 10 seconds.
List Commands
Redis lists are implemented as doubly linked lists.
RPUSH key value
Description: Pushes a value to the right of the list.
Example:
RPUSH mylist "World"
Adds "World" to the right end of mylist.
LPOP key
Description: Pops the first element from the left of the list.
Example:
LPOP mylist
Removes and returns the first element of mylist.
LRANGE key start end
Description: Returns a range of elements from the list.
Example:
LRANGE mylist 0 -1
Returns all elements in mylist.
LLEN key
Description: Returns the length of the list.
Example:
LLEN mylist
Returns the length of mylist.
LINDEX key index
Description: Returns the element at a specific index.
Example:
LINDEX mylist 0
Returns the first element of mylist.
LSET key index value
Description: Sets the list element at the specified index.
Example:
LSET mylist 0 "Hello"
Sets the first element of mylist to "Hello".
LINSERT key BEFORE | AFTER pivot value
Description: Inserts an element before or after the pivot element.
Example:
LINSERT mylist BEFORE "World" "Hello"
Inserts "Hello" before "World" in mylist.
LREM key count value
Description: Removes elements from the list.
Example:
LREM mylist 1 "World"
Removes one occurrence of "World" from mylist.
LTRIM key start end
Description: Trims the list to the specified range.
Example:
LTRIM mylist 0 1
Trims mylist to the first two elements.
Set Commands
Sets are unordered collections of unique strings.
SADD key value [value ...]
Description: Adds one or more members to a set.
Example:
SADD myset "Hello" "World"
Adds "Hello" and "World" to myset.
SCARD key
Description: Returns the number of members in a set.
Example:
SCARD myset
Returns the number of members in myset.
SISMEMBER key member
Description: Checks if a value is a member of the set.
Example:
SISMEMBER myset "Hello"
Returns 1 if "Hello" is a member of myset.
SINTER key [key ...]
Description: Returns the intersection of multiple sets.
Example:
SINTER myset1 myset2
Returns the intersection of myset1 and myset2.
SUNION key [key ...]
Description: Returns the union of multiple sets.
Example:
SUNION myset1 myset2
Returns the union of myset1 and myset2.
SDIFF key [key ...]
Description: Returns the difference between multiple sets.
Example:
SDIFF myset1 myset2
Returns the difference between myset1 and myset2.
SMEMBERS key
Description: Returns all members of the set.
Example:
SMEMBERS myset
Returns all members of myset.
SREM key member [member ...]
Description: Removes one or more members from a set.
Example:
SREM myset "Hello"
Removes "Hello" from myset.
SPOP key [count]
Description: Removes and returns one or more random members from the set.
Example:
SPOP myset
Removes and returns a random member from myset.
Sorted Set Commands
Sorted sets are collections of unique strings with associated floating-point scores.
ZADD key [NX|XX] [CH] [INCR] score member [score member ...]
Description: Adds one or more members to a sorted set, or updates the score if the member already exists.
Example:
ZADD myzset 1 "one" 2 "two"
Adds "one" with a score of 1 and "two" with a score of 2 to myzset.
ZINCRBY key increment member
Description: Increments the score of a member in the sorted set.
Example:
ZINCRBY myzset 2 "one"
Increments the score of "one" by 2.
ZRANGE key start stop [WITHSCORES]
Description: Returns a range of members in the sorted set, by index.
Example:
ZRANGE myzset 0 -1
Returns all members in myzset.
ZREVRANGE key start stop [WITHSCORES]
Description: Returns a range of members in the sorted set, by index, with scores ordered from high to low.
Example:
ZREVRANGE myzset 0 -1
Returns all members in myzset, ordered from high to low.
ZRANK key member
Description: Returns the rank of a member in the sorted set, with scores ordered from low to high.
Example:
ZRANK myzset "one"
Returns the rank of "one" in myzset.
ZSCORE key member
Description: Returns the score of a member in the sorted set.
Example:
ZSCORE myzset "one"
Returns the score of "one" in myzset.
Hash Commands
Hashes are maps between string fields and string values.
HSET key field value [field value ...]
Description: Sets field in the hash stored at key to value.
Example:
HSET myhash field1 "value1" field2 "value2"
Sets field1 to "value1" and field2 to "value2" in myhash.
HGETALL key
Description: Returns all fields and values of the hash stored at key.
Example:
HGETALL myhash
Returns all fields and values in myhash.
HGET key field
Description: Returns the value associated with field in the hash stored at key.
Example:
HGET myhash field1
Returns the value of field1 in myhash.
HDEL key field [field ...]
Description: Deletes one or more hash fields.
Example:
HDEL myhash field1
Deletes field1 from myhash.
HINCRBY key field increment
Description: Increments the integer value of a hash field by the given number.
Example:
HINCRBY myhash field1 10
Increments the value of field1 in myhash by 10.
HEXISTS key field
Description: Returns if field is an existing field in the hash.
Example:
HEXISTS myhash field1
Returns 1 if field1 exists in myhash.
Geospatial Commands
Geospatial indexes store latitude and longitude pairs.
GEOADD key longitude latitude member [longitude latitude member ...]
Description: Adds the specified geospatial items (latitude, longitude, name) to the specified key.
Example:
GEOADD mygeo 13.361389 38.115556 "Palermo"
Adds the coordinates of "Palermo" to mygeo.
GEORADIUS key longitude latitude radius m|km|ft|mi [WITHCOORD] [WITHDIST] [WITHHASH] [COUNT count] [ASC|DESC] [STORE key] [STOREDIST key]
Description: Returns members of a sorted set which are within the specified radius.
Example:
GEORADIUS mygeo 15 37 200 km WITHDIST
Returns members within 200 kilometers of the specified point.
GEODIST key member1 member2 [unit]
Description: Returns the distance between two members of a geospatial index.
Example:
GEODIST mygeo "Palermo" "Catania" km
Returns the distance between "Palermo" and "Catania" in kilometers.
Lua Scripting
Lua scripts allow for atomic operations in Redis.
EVAL script numkeys key [key ...] arg [arg ...]
Description: Evaluates a Lua script on the server.
Example:
EVAL "return redis.call('set', KEYS[1], ARGV[1])" 1 mykey "myvalue"
Sets mykey to myvalue using Lua.
EVALSHA sha1 numkeys key [key ...] arg [arg ...]
Description: Evaluates a script cached on the server by its SHA1 digest.
Example:
EVALSHA "d41d8cd98f00b204e9800998ecf8427e" 1 mykey "myvalue"
Evaluates the cached script with the given SHA1.
SCRIPT LOAD script
Description: Loads a script into the script cache.
Example:
SCRIPT LOAD "return redis.call('set', KEYS[1], ARGV[1])"
Caches the given script.
Publish/Subscribe Commands
Redis supports the publish/subscribe messaging paradigm.
PUBLISH channel message
Description: Posts a message to the given channel.
Example:
PUBLISH mychannel "hello world"
Publishes "hello world" to mychannel.
SUBSCRIBE channel [channel ...]
Description: Subscribes to the given channels.
Example:
SUBSCRIBE mychannel
Subscribes to mychannel.
Transaction Commands
Redis supports transactions through the MULTI, EXEC, and WATCH commands.
MULTI
Description: Marks the start of a transaction block.
Example:
MULTI
SET k1 10
INCR k1
EXEC
Starts a transaction, queues commands, and executes them atomically.
EXEC
Description: Executes all previously queued commands in a transaction.
Example:
EXEC
Executes all commands queued after MULTI.
DISCARD
Description: Discards all previously queued commands in a transaction.
Example:
DISCARD
Discards all commands queued after MULTI.
WATCH key [key ...]
Description: Watches the given keys to determine execution of the MULTI/EXEC block.
Example:
WATCH k1
MULTI
INCR k1
EXEC
Watches k1 and aborts the transaction if k1 is modified before EXEC.
Bitmap Commands
Bitmaps allow for bit-level operations on string values.
SETBIT key offset value
Description: Sets or clears the bit at offset in the string value stored at key.
Example:
SETBIT mykey 7 1
Sets the 7th bit of mykey to 1.
GETBIT key offset
Description: Returns the bit value at offset in the string value stored at key.
Example:
GETBIT mykey 7
Returns the value of the 7th bit of mykey.
BITCOUNT key [start] [end]
Description: Counts the number of set bits (population counting) in a string.
Example:
BITCOUNT mykey
Returns the number of bits set to 1 in mykey.
BITOP operation destkey key [key ...]
Description: Performs a bitwise operation between multiple keys (AND, OR, XOR, NOT).
Example:
BITOP AND resultkey key1 key2
Stores the result of a bitwise AND operation between key1 and key2 in resultkey.
BITFIELD key [GET type offset] [SET type offset value] [INCRBY type offset increment] [OVERFLOW WRAP|SAT|FAIL]
Description: Treats a string as a series of integers and allows access to specific integer fields.
Example:
BITFIELD mykey SET u8 0 100
Sets the first 8 bits of mykey to 100.
Detailed Explanation with Examples
Example: SET and GET Commands
SET Command:
SET k1 "Hello"
Sets the key k1 to "Hello". If k1 already exists, it will overwrite its value.
GET Command:
GET k1
Returns the value of k1, which is "Hello".
Example: RPUSH and LPOP Commands
RPUSH Command:
RPUSH mylist "World"
Adds "World" to the right end of the list mylist.
LPOP Command:
POP mylist
Removes and returns the first element of mylist, which is "World".
Example: ZADD and ZRANGE Commands
ZADD Command:
ZADD myzset 1 "one" 2 "two"
Adds "one" with a score of 1 and "two" with a score of 2 to the sorted set myzset.
ZRANGE Command:
ZRANGE myzset 0 -1
Returns all members in myzset, ordered from lowest to highest score.
Example: HSET and HGETALL Commands
HSET Command:
HSET myhash field1 "value1" field2 "value2"
Sets field1 to "value1" and field2 to "value2" in the hash myhash.
HGETALL Command:
HGETALL myhash
Returns all fields and values in myhash, which are field1: value1 and field2: value2.
Example: GEOADD and GEORADIUS Commands
GEOADD Command:
GEOADD mygeo 13.361389 38.115556 "Palermo"
Adds the coordinates of "Palermo" to the geospatial index mygeo.
GEORADIUS Command:
GEORADIUS mygeo 15 37 200 km WITHDIST
Returns members within 200 kilometers of the specified point, including their distances.
Example: Lua Scripting
EVAL Command:
EVAL "return redis.call('set', KEYS[1], ARGV[1])" 1 mykey "myvalue"
Sets mykey to myvalue using a Lua script.
Example: Transactions
MULTI and EXEC Commands:
MULTI
SET k1 10
INCR k1
EXEC
Starts a transaction, queues commands to set k1 to 10 and increment it, and executes them atomically.
This comprehensive guide covers the essential Redis commands, providing detailed explanations and examples to help you understand and utilize Redis effectively.
Summary
In this comprehensive Redis command cheatsheet, we've covered a wide range of Redis commands across various data structures. Here's a brief overview of what we discussed:
- String Commands: Setting, getting, appending, and manipulating string values, along with key expiration and persistence.
- List Commands: Operations on lists, including pushing and popping elements, trimming, and retrieving ranges of elements.
- Set Commands: Managing sets by adding, removing, and checking membership, as well as performing set operations like union, intersection, and difference.
- Sorted Set Commands: Handling sorted sets with commands for adding, removing, and querying elements by score and rank.
- Hash Commands: Working with hashes to store and retrieve key-value pairs efficiently.
- Geospatial Commands: Storing and querying geospatial data, leveraging Redis's ability to handle latitude and longitude pairs.
- Lua Scripting: Utilizing Lua scripts for atomic operations and complex data manipulations.
- Transaction Commands: Ensuring atomicity with transactions, allowing for the execution of multiple commands in a single, isolated operation.
- Publish/Subscribe Commands: Implementing messaging patterns with Redis's pub/sub capabilities.
- Bitmap Commands: Performing bit-level operations on string values for efficient data storage and manipulation.
This guide serves as a valuable resource for mastering Redis, providing detailed explanations and practical examples to help you utilize Redis effectively in your applications. Keep this cheatsheet handy to enhance your Redis experience and build more efficient, scalable systems.
Conclusion
Redis is a powerful, versatile tool that supports a wide range of data structures and operations. This comprehensive cheatsheet provides a detailed look at Redis commands, offering insights into their usage, output examples, and best practices. By mastering these commands, you can efficiently manage data, optimize performance, and leverage Redis's full potential in your applications. Whether you're dealing with simple key-value pairs, complex data structures, or advanced geospatial indexing, this guide serves as a valuable resource for maximizing your Redis experience. Keep this cheatsheet handy as you navigate the world of Redis, and you'll find yourself building more efficient and scalable systems in no time.