Database
NoSQL
Redis
Data Types & Commands

Data Types & Commands

Redis is often called a Data Structure Store because it supports more than just simple key-value pairs. Understanding these types is crucial for backend engineering.

1. Strings

Strings are the most basic type and can hold up to 512 MB of data. They can store text, serialized objects, or even binary data like images.

# Basic Ops
SET user:1 "John Doe"
GET user:1
 
# Numerical Ops (Strings are treated as integers if possible)
SET counter 10
INCR counter # 11
DECRBY counter 5 # 6
 
# Timing
SETEX session 3600 "data" # Set with 1-hour expiration

2. Lists

Lists are collections of strings sorted by insertion order. They are implemented as Linked Lists, making L/R operations very fast.

# Queue/Stack Ops
LPUSH mylist "first"
RPUSH mylist "second"
LPOP mylist # Returns "first"
RPOP mylist # Returns "second"
 
# Range search
LRANGE mylist 0 -1 # Get all elements

3. Sets

Sets are unordered collections of unique strings. Ideal for tracking unique items (e.g., unique visitors).

SADD tags "redis" "database" "performance"
SREM tags "database"
SISMEMBER tags "redis" # 1 (true)
 
# Group Operations
SINTER set1 set2 # Intersection
SUNION set1 set2 # Union

4. Hashes

Hashes are maps between string fields and string values. Best for representing objects.

HSET user:100 name "Alice" age 30 email "alice@example.com"
HGET user:100 name
HGETALL user:100 # Returns all fields and values
HINCRBY user:100 age 1

5. Sorted Sets (ZSets)

Similar to Sets but every member is associated with a score. Members are sorted by score.

ZADD leaderboard 100 "user1"
ZADD leaderboard 150 "user2"
ZADD leaderboard 50 "user3"
 
ZRANGE leaderboard 0 -1 WITHSCORES # Sorted list
ZREVRANK leaderboard "user1" # Get rank in descending order

6. Advanced Data Types

Streams

A log-like data structure that allows producers to append data and consumers to read it. Used for activity streams or message queues.

XADD mystream * sensor-id 1234 temperature 19.8
XREAD COUNT 1 STREAMS mystream 0-0

Bitmaps

Treat strings like an array of bits. extremely space-efficient for boolean tracking.

SETBIT user:active:2023-10-01 123 1 # User 123 is active on this day
GETBIT user:active:2023-10-01 123 # 1
BITCOUNT user:active:2023-10-01 # Count total active users

HyperLogLogs

Probabilistic data structure used for counting unique items with very low memory (max 12KB) but ~0.81% error rate.

PFADD hll_users "user1" "user2" "user3"
PFCOUNT hll_users # Returns 3

Geospatial

Store coordinates and query by radius or distance.

GEOADD locations 13.361389 38.115556 "Palermo"
GEODIST locations "Palermo" "Catania" km