How to check if the key exists in Redis?

Viewed 11725

I have a function in Laravel model and I need to check if my key ($key variable) exists in Redis, in other words I want to make a condition to not allow for duplicate results from redis. Here is my function. Any help is appreciated.

function

public static function cacheFields($fields)
{
    foreach ($fields as $fieldname => $values) {

        $key = static::$redisFieldKey.$fieldname; // here is that variable

        Redis::pipeline(function ($pipe) use ($key, $values) {
            foreach ($values as $value => $label) {
                $pipe->hset($key, $value, $label);
            }
        });
    }
}
1 Answers

When you execute hset for non existing key, it will set your hash with the field and its corresponding value. When you execute it against the existing hash (and field key), it will update the hash value of existing hash field.

127.0.0.1:6379> hset myhash myhashfield myvalue
(integer) 1
127.0.0.1:6379> hgetall myhash
1) "myhashfield"
2) "myvalue"
127.0.0.1:6379> hset myhash myhashfield anothervalue
(integer) 0
127.0.0.1:6379> hgetall myhash
1) "myhashfield"
2) "anothervalue"
127.0.0.1:6379>

Still if you want to check whether the key exists, you may use exists O(1)

127.0.0.1:6379> exists myhash
(integer) 1
127.0.0.1:6379> exists nonexisting
(integer) 0

If you want to check whether the hash field exists, you may use hexists O(1)

127.0.0.1:6379> hexists myhash myhashfield
(integer) 1
127.0.0.1:6379> hexists myhash nonfield
(integer) 0
127.0.0.1:6379> hexists notmyhash myfield
(integer) 0

Edit:

The documentation states that for hset;

Sets field in the hash stored at key to value. If key does not exist, a new key holding a hash is created. If field already exists in the hash, it is overwritten.

Related