Prem Prem - 1 month ago 7
Node.js Question

Unable to ltrim when Redis list is having only one record

I try to trim the records in

redis
queue using the following command. But unfortunately, unable to trim if there is only one item in the list.

ltrim key, -1, 0;

Answer

For ltrim key start_index stop_index command, the index is zero based. 0 is the index of the first element, and -1 is the index of the last element. If start_index is larger than stop_index, Redis clears the list, i.e. deletes the key.

Base on the above definition, let's take a look at your command:

ltrim key -1 0

The start_index is -1, i.e. the index of the last element, and the stop_index is 0, i.e. the index of the first element.

If the list has more than one elements, then the start_index is larger than the stop_index. In this case, the list / key will be deleted. However, if there's only 1 element in the list, both start_index and stop_index are the index of the first (also the last) element of list. You command has the same effect as: ltrim key 0 0. With this command, Redis keeps the first element (also the only element) of the list, and the list won't be trimmed.

By the way, do you want to delete the list? If you do, just call del key.