Redis Data Types Overview

Redis supports 5 basic data types, each with unique characteristics and use cases. This lesson provides an overview of all data types.

Redis Data Types Overview

Data Type Description Internal Implementation Use Cases
String Most basic type, stores strings, integers, binary data SDS (Simple Dynamic String) Caching, counters, distributed locks
Hash Key-value collection, like Map/Object Hash table + ziplist Storing objects, shopping carts
List Ordered, repeatable list of strings Doubly linked list + ziplist Message queues, recent lists
Set Unordered, unique string collection Hash table + intset Tags, social relationships
Sorted Set Ordered, unique collection with scores per element Skip list + hash table Leaderboards, weighted collections
💡 Why is Redis fast? All data is in memory, and it uses efficient data structures (hash tables, skip lists, etc.).

String

Strings are the most basic Redis data type. They can store:

Features

Basic Commands

REDIS
# Set and get
SET key value
GET key

# Numeric operations
INCR key          # Increment by 1
INCRBY key 10     # Increment by 10
DECR key          # Decrement by 1

# Other operations
APPEND key suffix  # Append
STRLEN key         # Get length

Use Cases

Scenario Example
Caching SET user:1:profile '{"name":"Alice"}'
Counter INCR article:123:views
Distributed lock SET lock:resource "locked" NX EX 10
Session SET session:token123 "user_data" EX 3600
💡 Distributed lock principle: The NX parameter (set only if key doesn't exist) combined with EX (expiration) of the SET command provides atomic lock acquisition.

Hash

A hash is a key-value collection, similar to a Map, Dictionary, or Object in programming languages.

Features

Basic Commands

REDIS
# Set and get fields
HSET user:1 name "Alice"
HSET user:1 age 25
HGET user:1 name        # "Alice"

# Set multiple fields
HMSET user:2 name "Bob" age 30 city "Beijing"

# Get all fields and values
HGETALL user:2
# 1) "name"
# 2) "Bob"
# 3) "age"
# 4) "30"
# 5) "city"
# 6) "Beijing"

# Get multiple fields
HMGET user:2 name age
# 1) "Bob"
# 2) "30"

# Delete a field
HDEL user:2 city

# Check if field exists
HEXISTS user:2 name    # 1

# Get all field names
HKEYS user:2
# 1) "name"
# 2) "age"

# Get all values
HVALS user:2
# 1) "Bob"
# 2) "30"

# Get number of fields
HLEN user:2            # 2

Use Cases

Scenario Example
Storing objects HSET user:1 name "Alice" age 25 email "alice@example.com"
Shopping cart HSET cart:user1 product:101 2 product:102 1 (product ID and quantity)
Counter group HINCRBY article:123 likes 1

Hash vs String for Storing Objects

Method 1: String with JSON

REDIS
SET user:1 '{"name":"Alice","age":25,"email":"alice@example.com"}'

Method 2: Hash

REDIS
HSET user:1 name "Alice" age 25 email "alice@example.com"
💡 Recommendation: Use Hash for simple objects, use String with JSON for complex nested objects.

List

A list is an ordered sequence of strings, allowing duplicate elements.

Features

Basic Commands

REDIS
# Left insert (head)
LPUSH mylist "a" "b" "c"  # Returns list length

# Right insert (tail)
RPUSH mylist "d" "e"

# Get list length
LLEN mylist               # 5

# Get elements within a range
LRANGE mylist 0 -1        # Get all elements
# 1) "c"
# 2) "b"
# 3) "a"
# 4) "d"
# 5) "e"

# Get element at a specific index
LINDEX mylist 0           # "c" (first element)

# Left pop (head)
LPOP mylist               # "c"

# Right pop (tail)
RPOP mylist               # "e"

# Set element at a specific index
LSET mylist 0 "new"

# Remove elements by value
LREM mylist 1 "a"         # Remove 1 element with value "a"

Use Cases

Scenario Description
Message queue LPUSH + RPOP or RPUSH + LPOP
Recent list Latest articles, recent comments
Timeline User's feed, microblog timeline

Example: Message Queue

BASH
# Producer: push messages to the queue
LPUSH queue:email "send to user1"
LPUSH queue:email "send to user2"

# Consumer: pop messages from the queue
RPOP queue:email
RPOP queue:email

# Blocking pop (blocks when no messages)
BRPOP queue:email 10
▶ Try it Yourself
💡 LPUSH + RPOP = Queue (FIFO), LPUSH + LPOP = Stack (LIFO)

Set

A set is an unordered collection of unique strings.

Features

Basic Commands

REDIS
# Add elements
SADD myset "a" "b" "c"

# Get all elements
SMEMBERS myset
# 1) "a"
# 2) "b"
# 3) "c"

# Check if element exists
SISMEMBER myset "a"      # 1 (exists)

# Remove elements
SREM myset "a"

# Get set size
SCARD myset              # 2

# Get a random element
SRANDMEMBER myset

# Pop a random element
SPOP myset

Set Operations

REDIS
# Create two sets
SADD set1 "a" "b" "c"
SADD set2 "b" "c" "d"

# Intersection (elements in both sets)
SINTER set1 set2
# 1) "b"
# 2) "c"

# Union (elements in either set)
SUNION set1 set2
# 1) "a"
# 2) "b"
# 3) "c"
# 4) "d"

# Difference (elements in set1 but not in set2)
SDIFF set1 set2
# 1) "a"

# Store result in a new set
SINTERSTORE result set1 set2

Use Cases

Scenario Description
Tag system User tags, article tags
Social relationships Friend lists, follow lists
Mutual friends Intersection of two users' friend sets
Recommendation system People you may know = friends of my friends - my friends - me

Example: Mutual Friends

BASH
# User 1's friends
SADD friends:user1 "Alice" "Bob" "Charlie"

# User 2's friends
SADD friends:user2 "Bob" "Charlie" "David"

# Mutual friends
SINTER friends:user1 friends:user2
▶ Try it Yourself

Sorted Set

A sorted set is a collection with scores, where elements are sorted by score.

Features

Basic Commands

REDIS
# Add elements (with score)
ZADD leaderboard 100 "Alice"
ZADD leaderboard 95 "Bob"
ZADD leaderboard 98 "Charlie"

# Get element's score
ZSCORE leaderboard "Alice"    # "100"

# Get element's rank (0-based, ascending by score)
ZRANK leaderboard "Alice"     # 2 (3rd place)

# Get element's rank (descending by score)
ZREVRANK leaderboard "Alice"  # 0 (1st place)

# Get elements by rank range (ascending)
ZRANGE leaderboard 0 -1 WITHSCORES
# 1) "Bob"
# 2) "95"
# 3) "Charlie"
# 4) "98"
# 5) "Alice"
# 6) "100"

# Get elements by rank range (descending)
ZREVRANGE leaderboard 0 -1 WITHSCORES
# 1) "Alice"
# 2) "100"
# 3) "Charlie"
# 4) "98"
# 5) "Bob"
# 6) "95"

# Get elements by score range
ZRANGEBYSCORE leaderboard 95 100 WITHSCORES

# Increment element's score
ZINCRBY leaderboard 5 "Bob"   # Bob's score becomes 100

# Remove element
ZREM leaderboard "Bob"

# Get set size
ZCARD leaderboard

# Count elements within a score range
ZCOUNT leaderboard 90 100

Use Cases

Scenario Description
Leaderboard Gaming leaderboard, trending list
Weighted tags Tags + weight
Delayed queue Score is execution timestamp
Sliding window Data statistics within a time window

Example: Gaming Leaderboard

BASH
# Update player scores
ZADD game:leaderboard 1500 "player1"
ZADD game:leaderboard 2300 "player2"
ZADD game:leaderboard 1800 "player3"

# Get top 10
ZREVRANGE game:leaderboard 0 9 WITHSCORES

# Get player rank
ZREVRANK game:leaderboard "player1"

# Get players with scores between 1000-2000
ZRANGEBYSCORE game:leaderboard 1000 2000 WITHSCORES
▶ Try it Yourself

Data Type Selection Guide

Decision Tree

What do you need to store?
├─ Single value (string, number, binary)
│  └─ Use String
│
├─ Object (multiple fields)
│  ├─ Fields often modified individually
│  │  └─ Use Hash
│  └─ Fields rarely modified individually
│     └─ Use String (JSON)
│
├─ Ordered list
│  ├─ Needs dual-ended operations
│  │  └─ Use List
│  └─ Needs sorting by score
│     └─ Use Sorted Set
│
└─ Unordered collection
   ├─ Needs deduplication
   │  └─ Use Set
   └─ Needs deduplication + sorting
      └─ Use Sorted Set

Comparison Summary

Feature String Hash List Set Sorted Set
Ordered - -
Repeatable - -
Numeric ops
Set operations
Range queries
Single-field modify

TYPE Command

Use the TYPE command to check a key's data type:

REDIS
SET mystring "hello"
TYPE mystring          # string

HSET myhash field "value"
TYPE myhash            # hash

LPUSH mylist "a"
TYPE mylist            # list

SADD myset "a"
TYPE myset             # set

ZADD myzset 1 "a"
TYPE myzset            # zset

❓ FAQ

Q How much data can a String store?
A Maximum 512MB. However, storing very large data is not recommended as it affects performance.
Q Which is better for storing objects — Hash or String?
A Use Hash for simple objects (individual fields can be modified), use String (JSON) for complex nested objects.
Q How many elements can a List store?
A Up to 2^32-1 (about 4.2 billion), but practically limited by available memory.
Q What is the difference between Set and List?
A Sets are unordered with unique elements; Lists are ordered and allow duplicates. Use Set for deduplication, List for ordered sequences.
Q Can Sorted Set scores be decimals?
A Yes, scores are double-precision floating-point numbers.

📖 Summary

📝 Exercises

  1. Create data: Create sample data for each data type
  2. TYPE command: Use TYPE to verify the data types you created
  3. Scenario thinking: For an e-commerce site, what data types would you use for product info, shopping cart, and order list?
  4. Set operations: Create two users' follow lists and calculate their mutual follows

Next Lesson

In the next lesson, we will learn Redis Key Management, diving deeper into key operations and management.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏