Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if the key exists in Redis?

Tags:

php

redis

laravel

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);
            }
        });
    }
}
like image 766
mrmar Avatar asked May 05 '20 09:05

mrmar


People also ask

Is key exist in Redis?

The Redis EXISTS command is used to check whether key exists in redis or not. Since Redis 3.0. 3 it is possible to specify multiple keys instead of a single one. In such a case, it returns the total number of keys existing.

What if key is not present in Redis?

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

What are keys in Redis?

Redis Keys are Ideal for Keeping Track of Lots of Strings. For the (simple string) key-value data type Redis allows you to set, get, delete, and increment arbitrary string <key, value> pairs. You can only have 1 value at a time for each key (i.e. set is destructive assignment). You can also delete keys.


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.

like image 151
Ersoy Avatar answered Sep 18 '22 14:09

Ersoy