In Redis, the LTRIM
command allows us to trim a list to a specified number of elements. We specify the starting and ending index, which is used to trim the list to just that range.
Syntax
The syntax goes like this:
LTRIM key start stop
Example
Suppose we create a list like this:
RPUSH scores 1 2 3 4 5 6 7 8 9 10
Result:
(integer) 10
Let’s take a look at the list:
LRANGE scores 0 -1
Result:
1) "1" 2) "2" 3) "3" 4) "4" 5) "5" 6) "6" 7) "7" 8) "8" 9) "9" 10) "10"
Let’s now use the LTRIM
command to trim the list:
LTRIM scores 4 8
Result:
OK
A simple string reply of OK
indicates that the operation was successful.
Now when we check the list again, we can see that it has been trimmed as specified:
LRANGE scores 0 -1
Result:
1) "5" 2) "6" 3) "7" 4) "8" 5) "9"
When the End Index is Larger than the End of the List
Specifying an ending index that’s larger than the list will result in it being treated as the last element of the list:
LTRIM scores 3 20
Result:
OK
Now when we check the list again, we can see that it has been trimmed as specified:
LRANGE scores 0 -1
Result:
1) "8" 2) "9"
When the Start Index is Larger than the End of the List
Specifying a starting index that’s larger than the list will result in an empty list. Doing this actually causes the key to be removed:
LTRIM scores 5 9
Result:
OK
Now when we check the list again, we get an empty array:
LRANGE scores 0 -1
Result:
(empty array)