Redis - how to RPUSH/LPUSH an empty list
Asked Answered
R

2

8

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

Ricoricochet answered 10/7, 2016 at 5:17 Comment(0)
L
14

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.

Lytta answered 10/7, 2016 at 6:45 Comment(0)
P
0

Just create list holder and be happy :)

[ProtoContract]
class ListHolder{
   [ProtoMember(1)]
   public List<String> List{get; set;}
}
Parachronism answered 20/9, 2022 at 7:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.