0
0
Redisquery~5 mins

LTRIM for list capping in Redis

Choose your learning style9 modes available
Introduction
LTRIM helps keep a Redis list at a fixed size by removing items outside a set range. This stops the list from growing too big and using too much memory.
You want to keep only the latest 100 messages in a chat history.
You store recent user actions but only need the last 50 for quick access.
You maintain a leaderboard and want to keep only the top 10 scores.
You log events but want to keep the list size small to save memory.
Syntax
Redis
LTRIM key start stop
The start and stop are zero-based indexes, where 0 is the first element.
Negative indexes count from the end, for example -1 is the last element.
Examples
Keeps only the first 100 elements (index 0 to 99) in the list named 'mylist'.
Redis
LTRIM mylist 0 99
Keeps the entire list unchanged because it trims from start 0 to last element (-1).
Redis
LTRIM mylist 0 -1
Keeps only elements from index 10 to 19, removing all others.
Redis
LTRIM mylist 10 19
Keeps only the first element in the list.
Redis
LTRIM mylist 0 0
Sample Program
This example adds 10 elements to 'mylist'. Then it trims the list to keep only the first 5 elements (index 0 to 4).
Redis
127.0.0.1:6379> RPUSH mylist a b c d e f g h i j
(integer) 10
127.0.0.1:6379> LRANGE mylist 0 -1
1) "a"
2) "b"
3) "c"
4) "d"
5) "e"
6) "f"
7) "g"
8) "h"
9) "i"
10) "j"
127.0.0.1:6379> LTRIM mylist 0 4
OK
127.0.0.1:6379> LRANGE mylist 0 -1
1) "a"
2) "b"
3) "c"
4) "d"
5) "e"
OutputSuccess
Important Notes
LTRIM runs in O(n) time where n is the number of elements removed, so trimming very large lists by removing many elements can be costly.
Use LTRIM after adding new elements to keep the list size fixed and avoid memory growth.
A common mistake is using wrong indexes and accidentally removing all elements or the wrong part of the list.
Summary
LTRIM keeps only a specified range of elements in a Redis list.
It is useful to cap list size and save memory.
Indexes start at 0 and can be negative to count from the end.