I'm using Redis for PHP.
I need to check if the key exists in redis list, and if it does not, add it. For now my code looks as follows:
$redis = Redis::connection();
$redis->pipeline(function($pipe) use ($type, $redis)
{
$list = $pipe->lRange($type.'_unique_list', 0, -1);
if(!in_array($this->uid, $list)) {
$pipe->rPush($type . '_unique_list', $this->uid);
}
});
The problem is that $list
taken from $pipe
returns Redis object, not array, and in_array
does not work. But if I use $redis->lRange
, the script becomes too slow.
So my question is, if there is any possibility to check if the key exists in Redis list without retrieving the list into the script? Some special Redis command which I can't find in docs? Or maybe I could replace in_array
with something else in this particular situation?
Wrongish answer: you can call LINDEX
instead of doing the search in the client.
Righter answer: scanning a linked list is always an expensive operation (O(N)) whether it is server- or client-side. Consider using a different data structure, e.g. a Set, for that purpose if your N is large.