0
0
Redisquery~5 mins

LRANGE for reading elements in Redis

Choose your learning style9 modes available
Introduction
LRANGE helps you get a part or all of a list stored in Redis. It is like reading a few pages from a book instead of the whole book.
You want to see the first few items in a list of recent messages.
You need to get the last 10 scores from a game leaderboard.
You want to read a specific range of elements from a list of tasks.
You want to display a page of comments from a long list.
Syntax
Redis
LRANGE key start stop
start and stop are indexes, starting at 0 for the first element.
Use -1 to mean the last element, -2 for the second last, and so on.
Examples
Gets the first three elements (index 0 to 2) from the list named 'mylist'.
Redis
LRANGE mylist 0 2
Gets all elements from the list 'mylist'.
Redis
LRANGE mylist 0 -1
Gets the last three elements from the list 'mylist'.
Redis
LRANGE mylist -3 -1
Sample Program
First, we add five fruits to 'mylist'. Then, we get elements from index 1 to 3, which are the second to fourth fruits.
Redis
RPUSH mylist "apple" "banana" "cherry" "date" "elderberry"
LRANGE mylist 1 3
OutputSuccess
Important Notes
Indexes are inclusive, so both start and stop elements are included in the result.
If start is greater than the last index, the result is empty.
If stop is greater than the last index, it stops at the last element.
Summary
LRANGE reads a part or all of a Redis list by index range.
Indexes start at 0 and can be negative to count from the end.
It returns the elements between start and stop, including both.