Redis LTRIM – How to trim an existing list stored in redis datastore

5 years 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 Redis LTRIM commands.

LTIM Command

This command trims an existing list value such that resulting list value contains only the specified range of elements. The range is defined 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. A 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 handled in the following ways :-

  1. start > end :- Result is an empty list, which causes specified Key to be removed.
  2. end > size of list :- Index of the last element of the list value is set to end offset.

If the key exists but value stored at the key is not of list datatype, an error is returned. The syntax of Redis LTRIM command is as follows :- 

Syntax :-

redis host:post> LTRIM <keyname> <start> <stop>

Output :- 

- (string) reply, OK
- Error, if key exist and value stored at the key is not a list.

Example :-

Redis LTRIM

References :-

  1. LTRIM Command Docs

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.

<- List Commands