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);
}
});
}
}
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.
If key does not exist, a new key holding a hash is created. If field already exists in the hash, it is overwritten.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With