Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redis - how to RPUSH/LPUSH an empty list

We'd like to RPUSH/LPUSH a key with an empty list.
This is for consistency reasons: when the key is read with LRANGE than whether the list is empty or not, the rest of the code behaves the same.

Why the fact that if a key has an empty list it is deleted is a problem?
Because we are using Redis as a cache and would like to differentiate the 2 situations:
1. A specific key with corresponding values was not cached yet. In which case we want to calculate the values (takes a long time) and cache them. The outcome of the calculation might be an empty list.
2. A key with an empty list was already cached. In which case we would like not to perform the calculations and return an empty list.

The following options don't work:

1. rpush key --> no list value results with "wrong number of arguments".
2. rpush key [] --> adds a '[]' item

The (ugly) solution we are currently using is storing a one-item-list with an "EMPTY-ITEM" item, and checking that when we read the list.

Any ideas?

Thank you

like image 881
user3139774 Avatar asked Jul 10 '16 05:07

user3139774


People also ask

How do I create an empty list in Redis?

Empty lists do not exist in Redis - a list must have one or more items. Empty lists (e.g. as a result of popping a non-empty one) are automatically removed.

How do I add a list in Redis?

Redis reads lists from left to right, and you can add new list elements to the head of a list (the “left” end) with the lpush command or the tail (the “right” end) with rpush . You can also use lpush or rpush to create a new list: lpush key value.

What is Lpush Redis?

Redis LPUSH command is used to insert all the specified values at the head of the list stored at key. It is created as an empty list before performing the push operations if tje key does not exist.


1 Answers

Empty lists do not exist in Redis - a list must have one or more items. Empty lists (e.g. as a result of popping a non-empty one) are automatically removed.

like image 187
Itamar Haber Avatar answered Oct 19 '22 01:10

Itamar Haber