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.1 and TCP port 63796379.
  • 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 1717.
    • 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 key returns the underlying data structure type of the specified key.
  • Key Eviction:

    • DEL key deletes the designated key and its mapped value from the instance.
  • Instance-Level Flushing:

    • FLUSHDB deletes 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 val assigns the string value val to key.
    • MSET key val [key2 val2 key3 val3 ...] atomically sets multiple key-value pairs simultaneously.
    • GET key retrieves the value mapped to key.
    • MGET key [key2 key3 ...] atomically retrieves values for all listed keys.
  • Existence Verification:

    • EXISTS key verifies whether a specified key is present in the current database instance.
  • Substring Retrieval:

    • GETRANGE key i1 i2 extracts a substring from the string stored at key from index i1i_1 to i2i_2.
    • Index boundaries are inclusive.
    • Negative index values count backwards from the end of the string (e.g., index −1-1 represents the final character).
  • Numeric Modifications (Numeric Values Only):

    • INCR key increments the integer value stored at key by 11.
    • DECR key decrements the integer value stored at key by 11.
    • INCRBY key num increments the integer value stored at key by the specified integer numnum.
    • DECRBY key num decrements the integer value stored at key by the specified integer numnum.
    • INCRBYFLOAT key num increments the numeric value stored at key by the floating-point value numnum.

Set Data Structures

  • Basic Set Mutations and Queries:

    • SADD setname elem1 [elem2 elem3 ...] adds one or more unique member elements to setname.
    • SREM setname elem removes a specified member element elem from setname.
    • SMEMBERS setname returns all member elements belonging to setname.
    • SCARD setname returns the cardinality (total count of elements nn) of setname.
    • SPOP setname removes and returns a random member element from setname.
    • SRANDMEMBER setname returns a random member element from setname without removing it.
  • Set Algebraic Operators and Persistence:

    • SDIFF setname1 setname2 performs set difference, returning members present in setname1 but not in setname2.
    • SDIFFSTORE newsetname setname1 setname2 performs set difference between setname1 and setname2 and stores the resulting set into newsetname.
    • SINTER setname1 setname2 performs set intersection, returning members common to both setname1 and setname2.
    • SINTERSTORE newsetname setname1 setname2 computes the intersection of setname1 and setname2 and saves the resulting set into newsetname.
    • SUNION setname1 setname2 performs set union, aggregating all unique elements from setname1 and setname2.
    • SUNIONSTORE newsetname setname1 setname2 computes the union of setname1 and setname2 and saves the resulting set into newsetname.

Linked List Data Structures

  • Push and Pop Operations:

    • LPUSH listname val1 [val2 val3 ...] inserts one or multiple values onto the left boundary (head) of listname.
    • RPUSH listname val1 [val2 val3 ...] inserts one or multiple values onto the right boundary (tail) of listname.
    • LPOP listname removes and returns the first element from the left (head) of listname.
    • RPOP listname removes and returns the first element from the right (tail) of listname.
  • List Inspection, Slicing, and Modification:

    • LRANGE listname i1 i2 displays list elements residing between index i1i_1 and index i2i_2 (inclusive).
    • LTRIM listname i1 i2 permanently trims and crops listname to retain only the elements within the inclusive index range i1i_1 through i2i_2.
    • LLEN listname returns the total length (count of elements) of listname.
    • LINDEX listname index retrieves an element by its positional offset index.
    • LSET listname index val sets the list element at offset index to the new value val.
    • LREM listname cnt val removes matches of val from listname, targeting up to the first cntcnt occurrences.

Hash (Dictionary) Data Structures

  • Hash Field Manipulation:

    • HSET hashname key value sets a field key to value within the hash stored at hashname.
    • HGET hashname key retrieves the value assigned to field key within hashname.
    • HEXISTS hashname key determines whether field key exists within hashname.
  • Hash Inspection and Bulk Retrieval:

    • HLEN hashname returns the total number of distinct key-value field pairs in hashname.
    • HKEYS hashname retrieves all field keys present within hashname.
    • HVALS hashname retrieves all values stored across all fields in hashname.
    • HGETALL hashname returns 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 00).
    • The item with the highest score receives the bottom rank: rank n−1n - 1, where nn is the set's cardinality.
    • Adding REV after the letter Z in range commands reverses this ordering convention, assigning rank 00 to the member with the highest score.
  • Sorted Set Commands:

    • ZADD ssname score elem adds member elem with score score to sorted set ssname. The numeric score strictly precedes the member name in the command syntax.
    • ZSCORE ssname elem returns the current numeric score of elem.
    • ZRANK ssname elem returns the 00-based rank of elem, ordered from lowest score to highest.
    • ZRANGEBYSCORE ssname score score returns member element(s) possessing the exact specified score.
    • ZINCRBY ssname increment elem increments the score of member elem by the amount increment.
    • ZCARD ssname returns the cardinality (total number of elements nn) in ssname.
    • ZCOUNT ssname min max returns the count of member elements having scores within the range [min,max][\text{min}, \text{max}].
    • ZRANGE ssname min max retrieves a range of elements ordered by rank from offset minmin to maxmax.
    • ZRANGEBYSCORE ssname min max retrieves elements whose scores fall within the numeric interval [min,max][min, max].
    • Appending WITHSCORES as an argument to ZRANGE or ZRANGEBYSCORE returns both the elements and their numeric scores.
    • ZREM ssname elem deletes member elem from ssname.
    • ZREMRANGEBYRANK ssname min max executes a bulk deletion of members whose ranks fall between minmin and maxmax.
    • ZREMRANGEBYSCORE ssname min max executes a bulk deletion of members whose scores fall within the interval [min,max][min, max].

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).
  • Entity Creation Examples:

    • 127.0.0.1:6379> hmset player:ruth uni 3 pos OF team yanks
    • Defines player Ruth with uniform number 33, 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 1919, 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     
  • 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=True ensures Redis string replies are returned as native Python strings instead of raw byte arrays.
    • db=17 targets database instance 1717 directly.
  • Key and String Operations via Python:

    • r.keys() retrieves all keys contained across the database instance.
    • r.keys("person:*") retrieves all keys matching the prefix person:*.
    • r.exists("name") returns True if the key exists, otherwise False.
    • 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 indices 22 through 33, 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 index 11 and index 33.
    • r.ltrim("holidays", 1, 3) permanently crops the list, preserving only elements from index 11 through index 33.
  • 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 scores 6363 for tiger, 6767 for xander, and 6666 for phil.
    • r.zscore("golf", 'phil') returns phil's score (6666).
    • r.zrank("golf", 'phil') calculates phil's rank starting from 00 (lowest score).
    • r.zincrby("golf", 3, 'xander') increments xander's score by 33.
    • r.zrange("golf", 3, 6) retrieves players ranked from position 33 through 66.
    • 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.