Redis LTRIM – How to trim an existing list stored in redis datastore
4 weeks ago Lalit Bhagtani 0
In this tutorial, we will learn about how to trim an existing list value stored at a key in redis datastore. For this we will use a COMMAND – LTRIM in redis-cli.
This command, trims an existing list value such that resulting list value contains only the specified range of elements. Range is define by start ( inclusive ) and end ( inclusive ) offsets, which determined the start and end index of a substring.
The index is zero based, so 0 means the first element, 1 means the second element and so on. Negative number can also be used to provide an offset starting from the end of the string value, here -1 means the last element, -2 means second last element and so on.
An out of range offsets are handle in the following ways :-
- start > end :- Result is an empty list, which cause specified Key to be removed.
- end > size of list :- Index of last element of the list value is set to end offset.
If key exist but value stored at the key is not of list datatype, error is returned. The syntax of redis LTRIM command is as follows :-
redis host:post> LTRIM <keyname> <start> <stop>
- (string) reply, OK - Error, if key exist and value stored at the key is not a list.
That’s all for how to trim an existing list value stored at a key in redis datastore. If you liked it, please share your thoughts in comments section and share it with others too.