Redis Commands and Data Structures Cheat Sheet
Redis Authentication and Instance Initialization
Client Connection Invocation:
- The command-line interface is launched using the command:
bash $ redis-cli - The default local connection endpoint resolves to IP address
127.0.0.1and TCP port.
- The command-line interface is launched using the command:
Server Health Verification:
127.0.0.1:6379> ping- Used to ping the Redis daemon to verify if the server is alive and actively accepting connections.
Instance Authentication:
127.0.0.1:6379> auth mypassword- Authenticates the current connection session against the Redis server using the password
mypassword.
Database Instance Selection:
127.0.0.1:6379> select 17- Switches the logical context to database index
. - Upon selection, the interactive CLI prompt reflects the active database identifier:
127.0.0.1:6379[17]>.
Meta and Administrative Commands
Key Discovery and Pattern Matching:
KEYS *retrieves all keys stored within the active database instance.KEYS "pattern with *'s"filters keys matching an expression; asterisks (*) act as multi-character wildcards.
Data Type Introspection:
TYPE keyreturns the underlying data structure type of the specifiedkey.
Key Eviction:
DEL keydeletes the designatedkeyand its mapped value from the instance.
Instance-Level Flushing:
FLUSHDBdeletes all keys from the entire current database instance.- This operation is irreversible and must be used with extreme caution.
Atomic Scalar and Numeric Commands
String Key-Value Management:
SET key valassigns the string valuevaltokey.MSET key val [key2 val2 key3 val3 ...]atomically sets multiple key-value pairs simultaneously.GET keyretrieves the value mapped tokey.MGET key [key2 key3 ...]atomically retrieves values for all listed keys.
Existence Verification:
EXISTS keyverifies whether a specifiedkeyis present in the current database instance.
Substring Retrieval:
GETRANGE key i1 i2extracts a substring from the string stored atkeyfrom indexto.- Index boundaries are inclusive.
- Negative index values count backwards from the end of the string (e.g., index
represents the final character).
Numeric Modifications (Numeric Values Only):
INCR keyincrements the integer value stored atkeyby.DECR keydecrements the integer value stored atkeyby.INCRBY key numincrements the integer value stored atkeyby the specified integer.DECRBY key numdecrements the integer value stored atkeyby the specified integer.INCRBYFLOAT key numincrements the numeric value stored atkeyby the floating-point value.
Set Data Structures
Basic Set Mutations and Queries:
SADD setname elem1 [elem2 elem3 ...]adds one or more unique member elements tosetname.SREM setname elemremoves a specified member elementelemfromsetname.SMEMBERS setnamereturns all member elements belonging tosetname.SCARD setnamereturns the cardinality (total count of elements) ofsetname.SPOP setnameremoves and returns a random member element fromsetname.SRANDMEMBER setnamereturns a random member element fromsetnamewithout removing it.
Set Algebraic Operators and Persistence:
SDIFF setname1 setname2performs set difference, returning members present insetname1but not insetname2.SDIFFSTORE newsetname setname1 setname2performs set difference betweensetname1andsetname2and stores the resulting set intonewsetname.SINTER setname1 setname2performs set intersection, returning members common to bothsetname1andsetname2.SINTERSTORE newsetname setname1 setname2computes the intersection ofsetname1andsetname2and saves the resulting set intonewsetname.SUNION setname1 setname2performs set union, aggregating all unique elements fromsetname1andsetname2.SUNIONSTORE newsetname setname1 setname2computes the union ofsetname1andsetname2and saves the resulting set intonewsetname.
Linked List Data Structures
Push and Pop Operations:
LPUSH listname val1 [val2 val3 ...]inserts one or multiple values onto the left boundary (head) oflistname.RPUSH listname val1 [val2 val3 ...]inserts one or multiple values onto the right boundary (tail) oflistname.LPOP listnameremoves and returns the first element from the left (head) oflistname.RPOP listnameremoves and returns the first element from the right (tail) oflistname.
List Inspection, Slicing, and Modification:
LRANGE listname i1 i2displays list elements residing between indexand index(inclusive).LTRIM listname i1 i2permanently trims and cropslistnameto retain only the elements within the inclusive index rangethrough.LLEN listnamereturns the total length (count of elements) oflistname.LINDEX listname indexretrieves an element by its positional offsetindex.LSET listname index valsets the list element at offsetindexto the new valueval.LREM listname cnt valremoves matches ofvalfromlistname, targeting up to the firstoccurrences.
Hash (Dictionary) Data Structures
Hash Field Manipulation:
HSET hashname key valuesets a fieldkeytovaluewithin the hash stored athashname.HGET hashname keyretrieves the value assigned to fieldkeywithinhashname.HEXISTS hashname keydetermines whether fieldkeyexists withinhashname.
Hash Inspection and Bulk Retrieval:
HLEN hashnamereturns the total number of distinct key-value field pairs inhashname.HKEYS hashnameretrieves all field keys present withinhashname.HVALS hashnameretrieves all values stored across all fields inhashname.HGETALL hashnamereturns all keys and their corresponding values in a single alternating list.
Sorted Sets (ZSets)
Conceptual Mechanics and Scoring:
- A sorted set is a collection of unique string members where each member is associated with a numeric floating-point score.
- By default, ranking mimics golf scoring: the item with the lowest score receives the top rank (rank
). - The item with the highest score receives the bottom rank: rank
, whereis the set's cardinality. - Adding
REVafter the letterZin range commands reverses this ordering convention, assigning rankto the member with the highest score.
Sorted Set Commands:
ZADD ssname score elemadds memberelemwith scorescoreto sorted setssname. The numeric score strictly precedes the member name in the command syntax.ZSCORE ssname elemreturns the current numeric score ofelem.ZRANK ssname elemreturns the -based rank ofelem, ordered from lowest score to highest.ZRANGEBYSCORE ssname score scorereturns member element(s) possessing the exact specifiedscore.ZINCRBY ssname increment elemincrements the score of memberelemby the amountincrement.ZCARD ssnamereturns the cardinality (total number of elements) inssname.ZCOUNT ssname min maxreturns the count of member elements having scores within the range.ZRANGE ssname min maxretrieves a range of elements ordered by rank from offsetto.ZRANGEBYSCORE ssname min maxretrieves elements whose scores fall within the numeric interval.- Appending
WITHSCORESas an argument toZRANGEorZRANGEBYSCOREreturns both the elements and their numeric scores. ZREM ssname elemdeletes memberelemfromssname.ZREMRANGEBYRANK ssname min maxexecutes a bulk deletion of members whose ranks fall betweenand.ZREMRANGEBYSCORE ssname min maxexecutes a bulk deletion of members whose scores fall within the interval.
Data Modeling Design Patterns
Hierarchical Key Naming for Entity Objects:
- When modeling entities using hashes (such as baseball players), use top-level keys structured with a colon-delimited naming convention (
entity:identifier).
- When modeling entities using hashes (such as baseball players), use top-level keys structured with a colon-delimited naming convention (
Entity Creation Examples:
127.0.0.1:6379> hmset player:ruth uni 3 pos OF team yanks- Defines player Ruth with uniform number
, position Outfield (OF), and team Yankees (yanks). 127.0.0.1:6379> hmset player:gwynn uni 19 pos OF team padres- Defines player Gwynn with uniform number
, position Outfield (OF), and team Padres (padres).
Entity Discovery:
KEYS player:*returns all keys belonging to the player namespace.
Python Redis Integration
Installation and Connection Configuration:
- Package installation via pip:
bash pip install redis
- Package installation via pip:
Driver initialization code: ```python import redis
r = redis.Redis( password="thepassword", decode_responses=True, db=17 ) ```
- Hostname, port, and additional networking parameters can also be configured during client initialization.
decode_responses=Trueensures Redis string replies are returned as native Python strings instead of raw byte arrays.db=17targets database instancedirectly.
Key and String Operations via Python:
r.keys()retrieves all keys contained across the database instance.r.keys("person:*")retrieves all keys matching the prefixperson:*.r.exists("name")returnsTrueif the key exists, otherwiseFalse.r.set("name", "stephen")assigns string value"stephen"to key"name".r.get("name")returns"stephen".r.getrange("name", 2, 3)extracts the substring spanning indicesthrough, yielding"ep".
Set Operations via Python:
r.sadd("davieses", "Stephen")inserts a single member into set"davieses".r.sadd("davieses", "Rae", "Lizzy", "TJ", "Marina")inserts multiple members into set"davieses".
List Operations via Python:
r.rpush("holidays", "halloween")pushes a single item to the tail of list"holidays".r.rpush("holidays", "thanksgiving", "christmas", "new years")pushes multiple items to the tail of list"holidays".r.lrange("holidays", 1, 3)retrieves an inclusive slice of elements between indexand index.r.ltrim("holidays", 1, 3)permanently crops the list, preserving only elements from indexthrough index.
Hash Operations via Python:
r.hset("soccer", "ball", "round")sets field"ball"to value"round"in hash"soccer".r.hget("soccer", "ball")returns"round".r.hkeys("soccer")returns all field keys of hash"soccer".r.hvals("soccer")returns all field values of hash"soccer".
Sorted Set Operations via Python:
r.zadd("golf", {'tiger': 63, 'xander': 67, 'phil': 66})adds members to sorted set"golf"with scoresfor tiger,for xander, andfor phil.r.zscore("golf", 'phil')returns phil's score ().r.zrank("golf", 'phil')calculates phil's rank starting from(lowest score).r.zincrby("golf", 3, 'xander')increments xander's score by.r.zrange("golf", 3, 6)retrieves players ranked from positionthrough.r.zrange("golf", 0, -1)retrieves all players sorted by rank in ascending order.r.zrange("golf", 0, -1, withscores=True)retrieves all players in rank order along with their numeric scores.