How to check whether a document exists or not?


I’ve went over the documentation, but I just can’t find it.

How to check whether a document exists or not? I don’t really want to use ‘get’ to get the whole content just to check if a document exists or not.

I came across this example for PHP, but is this reliable?

public function exists($key)
    if ($this->object->add($key, true)) {
        return false;
    return true;

hi @moon0326,
First of all please forgive my lack of PHP background (you are using PHP SDK 1.x right?) and the Java-oriented bits that will probably seep into this answer :wink:

The get operation is generally advocated for that use case because AFAIK there’s no operation in the protocol that just checks the key. Plus, the server can very quickly check if the key doesn’t exist (keyspace is loaded in memory) and so return null.

The incurred cost for this is directly dependent of the size of the document, since that will impact the response time due to I/O, but that’s it.

Of course, there may be alternatives better suited for your use case. For example, if you want this info for “conditional” creation of a document, add and replace operations have built-in checks on keys (add will only work if key doesn’t exist, replace only if key does exist).

The function you came across is not a good solution IMHO, better use a get and check for NULL return value and a specific result code:

public function exists($key) {
    return $cb_obj->get($key) == NULL 
        && $cb_obj->getResultCode() == COUCHBASE_KEY_ENOENT;

Of course maybe it’s not such a good idea to wrap it into a boolean function if you’re going to actually use the document after (no point in making a second get call).

Note: in the 2.x generation of SDK, add/set/replace have been renamed insert/upsert/replace across all SDKs (Java, .Net, PHP, etc…), they have a coherent API.

Thank you simonbasle.

I really think there should be an API for it. Like you said, there’s cost to get a big document just to check if it’s there or not.

@simonbasle - does an exists() exist for the python SDK?

I agree with @moon0326 since I would actually be trapping a ‘NotFoundError’ and im not sure if thats good coding technique to rely on a error catch for an operation.

Maybe something to add to the SDK’s for the future :slight_smile:

@whollycow007 I’m not sure what’s the timeframe for that in Python SDK but there have been discussions to bring an exist method to the common SDK 2 API. It’s already in master branches for .Net and Java :smile:

Awesome! Thank you! - you guys rock :slight_smile: