Lists & Hashes: Overview
Two powerful types in one module
Section titled “Two powerful types in one module”This module introduces two of Redis’s most useful data structures: Lists and Hashes.
A List is an ordered collection of strings backed by a doubly-linked list. You can push and pop elements from either end in O(1) time — no matter how many items are in the list. That makes lists ideal for queues, stacks, activity feeds, and recent-item trackers.
A Hash is a field-value map stored under a single key — think of it as a Python dict or a JavaScript object. You can set and get individual fields atomically, which means you can update a user’s email without touching any of their other attributes.
127.0.0.1:6379> RPUSH notifications "login" "purchase" "logout"(integer) 3127.0.0.1:6379> LRANGE notifications 0 -11) "login"2) "purchase"3) "logout"127.0.0.1:6379> HSET user:1 name "Ada" email "[email protected]" age "30"(integer) 3127.0.0.1:6379> HGETALL user:11) "name"2) "Ada"3) "email"4) "[email protected]"5) "age"6) "30"When to use each type
Section titled “When to use each type”| Type | Use when you need… | Examples |
|---|---|---|
| List | Ordered elements, O(1) head/tail access | Message queues, activity feeds, recent searches |
| Hash | Named fields on one key, partial updates | User profiles, product records, session data |
What this module covers
Section titled “What this module covers”| Lesson | Topic |
|---|---|
| Lists & Hashes: Overview | This page — Lists, Hashes, when to use each |
| Lists | LPUSH, RPUSH, LRANGE, LLEN, LINDEX, LSET, LREM, LTRIM |
| Lists as Queues & Stacks | LPUSH+RPOP (FIFO), LPUSH+LPOP (stack), BLPOP/BRPOP |
| Hashes | HSET, HGET, HMGET, HGETALL, HDEL, HEXISTS, HKEYS, HVALS, HLEN |
| Hash Objects | Modeling objects, HINCRBY, HINCRBYFLOAT, HSETNX |
A quick taste of both types
Section titled “A quick taste of both types”Try pushing items onto a list and storing fields in a hash:
127.0.0.1:6379> RPUSH tasks "write tests" "deploy" "notify team"(integer) 3127.0.0.1:6379> LRANGE tasks 0 -11) "write tests"2) "deploy"3) "notify team"127.0.0.1:6379> HSET product:99 name "Widget" price "9.99" stock "100"(integer) 3127.0.0.1:6379> HGET product:99 name"Widget"127.0.0.1:6379> HGET product:99 price"9.99"RPUSH tasks "write tests" "deploy" "notify team"
LRANGE tasks 0 -1
HSET product:99 name "Widget" price "9.99" stock "100"
HGET product:99 name
HGET product:99 price