5

I am using the Jedis Redis client and would like to be able to make sure if a key exists and if so then get the value. I am currently using an if statement to check if the key exists and if it doesn't then return null. I am assuming this is not the best way of doing things as you need to access the database more than once. Is there a way of checking if a key exists in the same step as getting the value?

Some example code:

try {
    if (!jedis.exists(name)) {
        return null;
    }

    return jedis.hgetAll(name);
} catch (JedisConnectionException exception) {
    // Do stuff
} finally {
    // Clean up
}
user2248702
  • 2,741
  • 7
  • 41
  • 69

1 Answers1

5

With Redis, if a key exists, the associated value is not empty. This is true for set, zset, hash, list, but not string.

Example:

> hmset x id 0
OK
> keys *
1) "x"
> hdel x id
(integer) 1
> keys *
(empty list or set)

In your situation, you can just perform the hgetAll and check if the return is empty.

Didier Spezia
  • 70,911
  • 12
  • 189
  • 154