LRANGE, LINDEX and LLEN
Asha's activity feed has grown to hundreds of entries, but her profile only shows the latest five, a "see more" page shows the next five, and a badge says how many there are in total. You never want the whole list; you want a slice, one item, or a count.
The rule
Indexes start at 0 from the head and -1 from the tail; LRANGE includes both ends.
feed:asha holds, from head to tail: won, lost, won, joined, won.
| Item | won | lost | won | joined | won |
|---|---|---|---|---|---|
| From head | 0 | 1 | 2 | 3 | 4 |
| From tail | -5 | -4 | -3 | -2 | -1 |
127.0.0.1:6379> LRANGE feed:asha 0 1
1) "won"
2) "lost"
127.0.0.1:6379> LRANGE feed:asha -2 -1
1) "joined"
2) "won"
127.0.0.1:6379> LINDEX feed:asha 3
"joined"
127.0.0.1:6379> LINDEX feed:asha 9
(nil)
127.0.0.1:6379> LLEN feed:asha
(integer) 5LRANGE key start stopreturns the items fromstarttostop, both included.0 -1is the whole list.- An index past the end is clipped, not an error:
LRANGE feed:asha 3 100returns justjoined,won. Ifstartis already past the end, or afterstop, the reply is an empty list. LINDEX key indexreturns one item, or(nil)if there is nothing at that index.LLEN keycounts the items; a missing key has length0.
Paging a feed. Page 1 is LRANGE feed:asha 0 4, page 2 is LRANGE feed:asha 5 9. In general, page n of size 5 is start = 5 × (n − 1) and stop = start + 4.
A note on speed. Reading near either end is instant. LINDEX in the middle of a very long list has to walk to that position, so lists are best used from their ends; for "is X in here?" a set is the right tool.