How to check whether a document exists or not?

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.