Redis
02 / 04

Data Structures & Commands

Data Structures & Commands

Strings

# Basic get/set
SET name "Alice"
GET name                  # "Alice"
DEL name
EXISTS name               # 0 or 1

# With expiry
SET session:abc "data" EX 3600      # expire in 3600 seconds
SET session:abc "data" PX 60000     # expire in 60000 milliseconds
SET session:abc "data" EXAT 1700000000   # expire at Unix timestamp
TTL session:abc           # seconds remaining (-1 = no expiry, -2 = gone)
PERSIST session:abc       # remove TTL

# NX / XX options
SET user:1 "Alice" NX     # set only if NOT exists (atomic "insert")
SET user:1 "Bob" XX       # set only if EXISTS (atomic "update")

# Numeric operations (atomic!)
SET counter 0
INCR counter              # 1
INCRBY counter 10         # 11
DECR counter              # 10
DECRBY counter 3          # 7
INCRBYFLOAT price 1.5

# Bulk operations
MSET k1 v1 k2 v2 k3 v3
MGET k1 k2 k3             # [v1, v2, v3]

# String operations
APPEND greeting "Hello"
APPEND greeting " World"
STRLEN greeting           # 11
GETSET key newvalue       # returns old, sets new
GETDEL key                # returns value, deletes key

Lists

# LPUSH/RPUSH — add to head/tail
LPUSH tasks "task1" "task2"    # task2 is now head
RPUSH tasks "task3"
LRANGE tasks 0 -1             # get all elements (0 to last)
LLEN tasks                    # length

# Pop from head or tail
LPOP tasks                    # remove + return head
RPOP tasks                    # remove + return tail
LPOP tasks 2                  # pop 2 elements

# Blocking pop (for queue workers — waits up to N seconds)
BLPOP queue:jobs 30           # blocks until item available or timeout

# Index access
LINDEX tasks 0                # get head without removing
LSET tasks 0 "updated-task"

# Trim
LTRIM logs 0 999              # keep only first 1000 items

# Use cases
# Stack: LPUSH + LPOP
# Queue: RPUSH + BLPOP
# Capped log: RPUSH + LTRIM 0 999

Sets & Sorted Sets

# Sets — unique, unordered
SADD tags "js" "ts" "react"
SREM tags "react"
SMEMBERS tags               # all members
SISMEMBER tags "js"         # 1 (true) or 0 (false)
SCARD tags                  # count
SMISMEMBER tags "js" "go"   # [1, 0]

# Set operations
SUNION set1 set2            # union
SINTER set1 set2            # intersection
SDIFF set1 set2             # difference (in set1, not in set2)
SUNIONSTORE dest set1 set2  # store result

# Sorted Sets — unique members with a score
ZADD leaderboard 1000 "alice" 850 "bob" 950 "carol"
ZINCRBY leaderboard 50 "bob"                    # bob score += 50
ZSCORE leaderboard "alice"                      # 1000
ZRANK leaderboard "alice"                       # 0-based rank (lowest score first)
ZREVRANK leaderboard "alice"                    # rank from highest score
ZRANGE leaderboard 0 -1                         # sorted by score asc
ZRANGE leaderboard 0 -1 REV                     # desc
ZRANGE leaderboard 0 -1 WITHSCORES             # include scores
ZRANGEBYSCORE leaderboard 900 1100              # by score range
ZRANGEBYLEX leaderboard "[a" "[m"               # by lex range (when scores equal)
ZCARD leaderboard                               # count
ZREM leaderboard "bob"
ZPOPMIN leaderboard         # remove lowest score member
ZPOPMAX leaderboard         # remove highest score member

# Use cases: leaderboards, rate limiting, time-sorted events

Hashes

# Hashes — object-like, field:value pairs
HSET user:1 name "Alice" email "alice@example.com" age 28
HGET user:1 name            # "Alice"
HMGET user:1 name email     # ["Alice", "alice@example.com"]
HGETALL user:1              # all field-value pairs
HKEYS user:1                # all keys
HVALS user:1                # all values
HLEN user:1                 # field count
HDEL user:1 age
HEXISTS user:1 email        # 1
HINCRBY user:1 points 10
HSETNX user:1 name "Bob"    # set only if field doesn't exist

# Use case: cache full objects instead of encoding to string
# Better memory efficiency for many small objects vs separate keys

Key Management

# Key patterns
KEYS user:*               # DANGER: blocks server — never use in prod
SCAN 0 MATCH user:* COUNT 100   # iterative, production-safe
TYPE key                  # string / list / set / zset / hash / stream
OBJECT ENCODING key       # internal encoding (embstr, listpack, skiplist...)
RENAME oldkey newkey
RENAMENX oldkey newkey    # only if newkey doesn't exist
COPY source dest          # copy value to new key
DUMP key / RESTORE key TTL serialized   # serialize/deserialize

# Expiry
EXPIRE key 60             # set TTL in seconds
EXPIREAT key 1700000000  # expire at Unix timestamp
PEXPIRE key 60000         # milliseconds
TTL key                   # remaining seconds
PTTL key                  # remaining ms

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free