|
| 1 | +# Data Structures in Redis |
| 2 | + |
| 3 | +Redis supports **five core data structures**, each designed for specific use-cases and access patterns. These are: |
| 4 | + |
| 5 | +1. **Strings** |
| 6 | +2. **Lists** |
| 7 | +3. **Sets** |
| 8 | +4. **Hashes** |
| 9 | +5. **Sorted Sets (ZSets)** |
| 10 | + |
| 11 | +Each structure is optimized for fast in-memory operations and has a dedicated set of commands. |
| 12 | + |
| 13 | +--- |
| 14 | + |
| 15 | +## 1. 🔹 **Strings** |
| 16 | +The simplest and most commonly used data structure in Redis. |
| 17 | + |
| 18 | +### 📌 Characteristics: |
| 19 | +- Value is a sequence of bytes (binary-safe). |
| 20 | +- Can be used to store text, integers, or serialized objects. |
| 21 | +- Max size of a string value: **512 MB**. |
| 22 | + |
| 23 | +### 📂 Use-cases: |
| 24 | +- Caching data (e.g., API responses) |
| 25 | +- Storing session tokens or flags |
| 26 | +- Rate-limiting counters |
| 27 | +- Feature flags |
| 28 | + |
| 29 | +### 🛠️ Key Commands: |
| 30 | + |
| 31 | +| Command | Description | |
| 32 | +|--------|-------------| |
| 33 | +| `SET key value` | Set a string value | |
| 34 | +| `GET key` | Retrieve the string value | |
| 35 | +| `INCR key` | Atomically increment an integer value | |
| 36 | +| `DECR key` | Atomically decrement an integer | |
| 37 | +| `APPEND key value` | Append to existing string | |
| 38 | +| `STRLEN key` | Length of string | |
| 39 | + |
| 40 | +### 🔍 Example: |
| 41 | + |
| 42 | +```bash |
| 43 | +SET user:1001:name "Yashvi" |
| 44 | +GET user:1001:name |
| 45 | +INCR visit:count # visit:count = 1 |
| 46 | +APPEND user:1001:name " Patel" |
| 47 | +``` |
| 48 | + |
| 49 | +--- |
| 50 | + |
| 51 | +## 2. 🔹 **Lists** |
| 52 | +An ordered collection of string elements. Think of them like a doubly-linked list. |
| 53 | + |
| 54 | +### 📌 Characteristics: |
| 55 | +- Elements are ordered (insertion order preserved). |
| 56 | +- Can efficiently add/remove items from **both ends**. |
| 57 | +- Ideal for **FIFO** (queue) or **LIFO** (stack) structures. |
| 58 | + |
| 59 | +### 📂 Use-cases: |
| 60 | +- Task/job queues |
| 61 | +- Activity feeds or timelines |
| 62 | +- Message buffering |
| 63 | + |
| 64 | +### 🛠️ Key Commands: |
| 65 | + |
| 66 | +| Command | Description | |
| 67 | +|--------|-------------| |
| 68 | +| `LPUSH key value` | Insert at head (left) | |
| 69 | +| `RPUSH key value` | Insert at tail (right) | |
| 70 | +| `LPOP key` | Remove from head | |
| 71 | +| `RPOP key` | Remove from tail | |
| 72 | +| `LRANGE key start end` | Get a range of elements | |
| 73 | +| `LLEN key` | List length | |
| 74 | + |
| 75 | +### 🔍 Example: |
| 76 | + |
| 77 | +```bash |
| 78 | +LPUSH queue:emails "email1" "email2" |
| 79 | +RPUSH queue:emails "email3" |
| 80 | +LRANGE queue:emails 0 -1 # ["email2", "email1", "email3"] |
| 81 | +LPOP queue:emails # "email2" |
| 82 | +``` |
| 83 | + |
| 84 | +--- |
| 85 | + |
| 86 | +## 3. 🔹 **Sets** |
| 87 | +An **unordered** collection of **unique** string values. |
| 88 | + |
| 89 | +### 📌 Characteristics: |
| 90 | +- Duplicate entries are automatically ignored. |
| 91 | +- Internally implemented using a hash table. |
| 92 | +- Supports set operations like **union**, **intersection**, and **difference**. |
| 93 | + |
| 94 | +### 📂 Use-cases: |
| 95 | +- Track unique visitors |
| 96 | +- Tagging systems |
| 97 | +- Avoiding duplication (e.g., unique voters) |
| 98 | + |
| 99 | +### 🛠️ Key Commands: |
| 100 | + |
| 101 | +| Command | Description | |
| 102 | +|--------|-------------| |
| 103 | +| `SADD key member [member ...]` | Add one or more elements | |
| 104 | +| `SMEMBERS key` | Get all members | |
| 105 | +| `SISMEMBER key value` | Check membership | |
| 106 | +| `SREM key value` | Remove a member | |
| 107 | +| `SUNION key1 key2` | Union of two sets | |
| 108 | +| `SINTER key1 key2` | Intersection of sets | |
| 109 | + |
| 110 | +### 🔍 Example: |
| 111 | + |
| 112 | +```bash |
| 113 | +SADD course:students "Arjun" "Mahir" "Yashvi" |
| 114 | +SISMEMBER course:students "Krishna" # false |
| 115 | +SMEMBERS course:students # {"Arjun", "Mahir", "Yashvi"} |
| 116 | +``` |
| 117 | + |
| 118 | +--- |
| 119 | + |
| 120 | +## 4. 🔹 **Hashes** |
| 121 | +A collection of **field-value pairs**, similar to a row in a database or an object in a JSON document. |
| 122 | + |
| 123 | +### 📌 Characteristics: |
| 124 | +- Best used to store objects (like user profiles, product details). |
| 125 | +- Efficient for retrieving or modifying individual fields. |
| 126 | + |
| 127 | +### 📂 Use-cases: |
| 128 | +- Representing structured data (users, products) |
| 129 | +- Updating subfields without replacing the entire value |
| 130 | + |
| 131 | +### 🛠️ Key Commands: |
| 132 | + |
| 133 | +| Command | Description | |
| 134 | +|--------|-------------| |
| 135 | +| `HSET key field value` | Set a field | |
| 136 | +| `HGET key field` | Get value of a field | |
| 137 | +| `HGETALL key` | Get all fields and values | |
| 138 | +| `HDEL key field` | Delete a field | |
| 139 | +| `HEXISTS key field` | Check if field exists | |
| 140 | +| `HINCRBY key field n` | Increment field by value `n` | |
| 141 | + |
| 142 | +### 🔍 Example: |
| 143 | + |
| 144 | +```bash |
| 145 | +HSET user:1001 name "Priyesha" age "23" city "Surat" |
| 146 | +HGET user:1001 name # "Priyesha" |
| 147 | +HGETALL user:1001 # {name: "Priyesha", age: "23", city: "Surat"} |
| 148 | +``` |
| 149 | + |
| 150 | +--- |
| 151 | + |
| 152 | +## 5. 🔹 **Sorted Sets (ZSets)** |
| 153 | +Similar to Sets but with a **score** associated with each member that determines ordering. |
| 154 | + |
| 155 | +### 📌 Characteristics: |
| 156 | +- Members are unique. |
| 157 | +- Score is a floating-point number. |
| 158 | +- Automatically keeps elements sorted by score. |
| 159 | + |
| 160 | +### 📂 Use-cases: |
| 161 | +- Leaderboards |
| 162 | +- Ranking systems |
| 163 | +- Time-based event queues (timestamps as scores) |
| 164 | + |
| 165 | +### 🛠️ Key Commands: |
| 166 | + |
| 167 | +| Command | Description | |
| 168 | +|--------|-------------| |
| 169 | +| `ZADD key score member` | Add a member with score | |
| 170 | +| `ZRANGE key start end [WITHSCORES]` | Get members in order | |
| 171 | +| `ZREVRANGE key start end` | Reverse order | |
| 172 | +| `ZINCRBY key increment member` | Increment score of a member | |
| 173 | +| `ZRANK key member` | Get the rank of a member | |
| 174 | + |
| 175 | +### 🔍 Example: |
| 176 | + |
| 177 | +```bash |
| 178 | +ZADD leaderboard 1500 "Krishna" |
| 179 | +ZADD leaderboard 1600 "Arjun" |
| 180 | +ZINCRBY leaderboard 50 "Krishna" |
| 181 | +ZRANGE leaderboard 0 -1 WITHSCORES |
| 182 | +``` |
| 183 | + |
| 184 | +--- |
| 185 | + |
| 186 | +## ⚙️ Internal Efficiency and Performance |
| 187 | + |
| 188 | +Redis uses optimized C implementations for each data structure: |
| 189 | + |
| 190 | +| Data Structure | Internal Implementation | |
| 191 | +|----------------|--------------------------| |
| 192 | +| String | Simple dynamic strings (SDS) | |
| 193 | +| List | Quicklist (compressed linked list + array) | |
| 194 | +| Set | Hash tables or intsets | |
| 195 | +| Hash | Hashtable (dict) or ziplist | |
| 196 | +| Sorted Set | Skiplist + hashtable | |
| 197 | + |
| 198 | +Redis automatically chooses compact representations (e.g., ziplist, intset) for memory efficiency on small datasets. |
| 199 | + |
| 200 | +--- |
| 201 | + |
| 202 | +## 🧠 When to Use Which Data Structure? |
| 203 | + |
| 204 | +| Use-case | Recommended Structure | |
| 205 | +|----------|------------------------| |
| 206 | +| Caching a single value | String | |
| 207 | +| Representing user profile | Hash | |
| 208 | +| Recent activities | List | |
| 209 | +| Unique tags or categories | Set | |
| 210 | +| Real-time leaderboards | Sorted Set | |
| 211 | + |
| 212 | +--- |
| 213 | + |
| 214 | +## 🧾 Summary |
| 215 | + |
| 216 | +| Data Type | Ordered? | Unique Values? | Score/Field Support? | Use-cases | |
| 217 | +|-----------|----------|----------------|----------------------|-----------| |
| 218 | +| String | ✖️ | ✖️ | ✖️ | Basic storage, counters | |
| 219 | +| List | ✅ | ✖️ | ✖️ | Queues, feeds | |
| 220 | +| Set | ✖️ | ✅ | ✖️ | Tags, unique items | |
| 221 | +| Hash | ✖️ | Field-based | ✅ | Objects, profiles | |
| 222 | +| Sorted Set| ✅ | ✅ | ✅ | Rankings, time-series | |
| 223 | + |
| 224 | +--- |
| 225 | + |
| 226 | +Redis is not only fast — it’s **versatile**. Each data structure has a rich set of atomic commands allowing powerful, high-performance operations right from the Redis CLI or client library. |
| 227 | + |
0 commit comments