Micael
Micael

Reputation: 6970

What is best practice for list and set handling in Redis?

We are using Redis as a caching server, and often have to deal with caching list. When we cache simple objects we do a GET and Redis will return null if the object doesn't exist and we'll know that the object isn't cached and have to be loaded from database.

But how do we best handle the same for lists - an empty list can be a valid value. Do we need to call EXISTS to check if the list exists (but making the operation 2 calls instead of one) or does someone have a better idea how to handle this scenario?

/Thanks

Upvotes: 10

Views: 6152

Answers (3)

antirez
antirez

Reputation: 18504

If you absolutely need to do that, when the list is created you can push a "sentinel" as first element that is never removed. In order to do this atomically you can use MULTI/EXEC/WATCH, but watch is only available in Redis 2.2 that is currently a preview (even if pretty stable, you can grab it from github master branch).

I think in your use case you may also want RPUSHX and LPUSHX, that will atomically push against a list only if it already exists.

Note that since Redis 2.2 to exist means to have at least 1 element for a list, as lists that will reach zero elements are automatically removed, for many good reasons ;)

Upvotes: 9

kijin
kijin

Reputation: 8900

Unfortunately, list/set retrieval commands such as LRANGE and SMEMBERS do not seem to distinguish between an empty list/set and a non-existent list/set.

So if you absolutely need to distinguish between the two cases, I guess you'll need to do an EXISTS first. Try pipelining your commands for better performance. Most Redis client libraries support pipelining.

Or you might reconsider your caching strategy so that you don't need to distinguish them.

Upvotes: 3

Colum
Colum

Reputation: 3914

If you are using php, I would assign the return value to an variable and then check if it is an array. (This is how it works using the Predis library)

$res = $redis->get('Key');
if(is_array($res))
    do code here

Upvotes: -1

Related Questions