Redis - Lists
Redis lists are lists of strings, sorted by the insertion order. List can contain duplicate values as it does not enforce unique values.
Limitations with lists
- You cannot find if a given value exists in a list. If you would need to do so, it would be best to use some of the other data types in Redis.
- You cannot nest other data structure inside a list other than a string. So for example, creating a list and nesting another list or hash inside that list is not possible.
Adding Elements to a List (LPUSH, RPUSH)
To add elements into a list (and to create a list with the given key), the commands LPUSH and RPUSH can be utilized. The RPUSH command adds the value to the end of the list and the LPUSH command adds the value to the beginning of the list.
Time Complexity: O(1) for each element added, so O(N) when there are multiple values.
For Example:
Listing Elements in a list (LRANGE)
To list the elements in a list (in the given range), the command LRANGE can be used. Learn more
Time Complexity: O(S+N) where S is the offset and N is the number of elements.
For example:
List Length (LLEN)
To list the length of the list, the command LLEN can be used. Learn more
Time Complexity: O(1)
For example:
Adding Item Before / After Specified Item (LINSERT)
To add a new item before or after the specified value in the list, the command LINSERT can be used. Learn more
Time Complexity: O(1) when inserting to beginning or ending of the list. If inserting to any other position, O(N) where N is the amount of elements that need to be traversed to find the pivot element.
For example:
LINSERT user#2:purchases:amount AFTER 30,99 89
LINSERT user#2:purchases:amount BEFORE 89 505
The first command would find the value 30,99 in the list and add the given value after that item. The second command does the same but adds the new value before the item.
Getting Item by Index (LINDEX)
To get the item in a list with the given index, the command LINDEX can be used. Learn more
Time Complexity: O(1) for accessing first or last element of the list. If accessing any other element from the list, O(N) where N is the amount of elements that need to be traversed to find the element.
For example:
Removing the First and Last Items (LPOP, RPOP)
To remove (pop) element from the beginning or end of the list, the commands LPOP and RPOP can be used. LPOP removes item from the beginning of the list (left pop) and RPOP removes item from the ending of the list (right pop).
Time Complexity: O(N) where N is the amount of items returned. O(1) if it is only one item.
For example:
Trimming List to Specified Range (LTRIM)
To trim the list to specified range, the command LTRIM can be used. For this command you pass the starting and ending index. All other values will be removed from the list. Learn more
Time Complexity: O(N) where N is the amount of elements to be removed. O(1) if only one element will be removed.
For example: