Key Value Operations

    +
    Key Value (KV) or data service offers the simplest way to retrieve or mutate data where the key is known. Here we cover CRUD operations, document expiration, and optimistic locking with CAS.

    Documents

    A document refers to an entry in the database (other databases may refer to the same concept as a row). A document has an ID (primary key in other databases), which is unique to the document and by which it can be located. The document also has a value which contains the actual application data. See the concept guide to Documents for a deeper dive into documents in the Couchbase Data Platform. Or read on, for a hands-on introduction to working with documents from the PHP SDK.

    CRUD Operations

    The core interface to Couchbase Server is simple KV operations on full documents. Make sure you’re familiar with the basics of authorization and connecting to a Cluster from the Start Using the SDK section. We’re going to expand on the short Upsert example we used there, adding options as we move through the various CRUD operations. Here is the Insert operation at its simplest:

    $document = ["foo" => "bar", "bar" => "foo"];
    $res = $collection->insert("document-key-new", $document);
    printf("document \"document-key\" has been created with CAS \"%s\"\n", $res->cas());

    Options may be added to operations:

    $document = ["foo" => "bar", "bar" => "foo"];
    $opts = new InsertOptions();
    $opts->timeout(300000 /* milliseconds */);
    $res = $collection->insert("document-key", $document, $opts);
    printf("document \"document-key\" has been created with CAS \"%s\"\n", $res->cas());

    Setting a Compare and Swap (CAS) value is a form of optimistic locking - dealt with in depth in the CAS page. Here we just note that the CAS is a value representing the current state of an item; each time the item is modified, its CAS changes. The CAS value is returned as part of a document’s metadata whenever a document is accessed. Without explicitly setting it, a newly-created document would have a CAS value of 0.

    Timeout is an optional parameter which is a integer value representing time duration in milliseconds. Timeout sets the timeout value for the underlying network connection. We will add to these options for the Replace example:

    // Replace document with incorrect CAS
    $opts = new ReplaceOptions();
    $opts->timeout(300000 /* milliseconds */);
    $invalidCas = "776t3gAAAAA=";
    $opts->cas($invalidCas);
    try {
        $collection->replace("document-key", $document, $opts);
    } catch (\Couchbase\CasMismatchException $ex) {
        printf("document \"document-key\" cannot be replaced with CAS \"%s\"\n", $invalidCas);
    }
    
    // Get and Replace document with CAS
    $res = $collection->get("document-key");
    $doc = $res->content();
    $doc["bar"] = "moo";
    
    $opts = new ReplaceOptions();
    $oldCas = $res->cas();
    $opts->cas($oldCas);
    $res = $collection->replace("document-key", $doc, $opts);
    printf("document \"document-key\" \"%s\" been replaced successfully. New CAS \"%s\"\n", $oldCas, $res->cas());

    The example above also shows how to handle the case when optimistic falure will fail.

    Expiration sets an explicit time to live (TTL) for a document. We’ll discuss modifying expiry in more details below. For a discussion of item (Document) vs Bucket expiration, see the Expiration Overview page.

    $document = ["foo" => "bar", "bar" => "foo"];
    $opts = new UpsertOptions();
    $opts->expiry(60 * 1000 /* 60 seconds */);
    $res = $collection->upsert("document-key", $document, $opts);
    printf("document \"document-key\" has been created with CAS \"%s\"\n", $res->cas());

    Durability

    In Couchbase Server releases before 6.5, Durability was set with these two options — see the 6.0 Durability documentation — covering how many replicas the operation must be propagated to and how many persisted copies of the modified record must exist.

    If 6.5 or above is being used, you can take advantage of the Durable Write feature, in which Couchbase Server will only return success to the SDK after the requested replication level has been achieved. The three replication levels are:

    • Majority - The server will ensure that the change is available in memory on the majority of configured replicas.

    • MajorityAndPersistToActive - Majority level, plus persisted to disk on the active node.

    • PersistToMajority - Majority level, plus persisted to disk on the majority of configured replicas.

    The options are in increasing levels of safety. Note that nothing comes for free - for a given node, waiting for writes to storage is considerably slower than waiting for it to be available in-memory. These trade offs, as well as which settings may be tuned, are discussed in the durability page.

    The following example demonstrates using the newer durability features available in Couchbase server 6.5 onwards.

    // Remove with Durability
    $opts = new RemoveOptions();
    $opts->timeout(3000 /* milliseconds */);
    $opts->durabilityLevel(DurabilityLevel::MAJORITY);
    $res = $collection->remove("document-key", $opts);
    printf("document \"document-key\" has been removed\n");

    To stress, durability is a useful feature but should not be the default for most applications, as there is a performance consideration, and the default level of safety provided by Couchbase will be reasonable for the majority of situations.

    Sub-Document Operations

    All of these operations involve fetching the complete document from the Cluster. Where the number of operations or other circumstances make bandwidth a significant issue, the SDK can work on just a specific path of the document with Sub-Docunent Operations.

    Retrieving full documents

    Using the Get() method with the document key can be done in a similar fashion to the other operations:

    $res = $collection->get("document-key");
    $doc = $res->content();
    printf("document \"document-key\" has content: \"%s\" CAS \"%s\"\n", json_encode($doc), $res->cas());

    Timeout can also be set - as in the earlier Insert example:

    $opts = new GetOptions();
    $opts->timeout(3000 /* milliseconds */);
    $res = $collection->get("document-key", $opts);
    $doc = $res->content();
    printf("document \"document-key\" has content: \"%s\" CAS \"%s\"\n", json_encode($doc), $res->cas());

    Removing

    When removing a document, you will have the same concern for durability as with any additive modification to the Bucket:

    Remove (with options)

    $opts = new RemoveOptions();
    $options->timeout(5000); // 5 seconds
    $result = $collection->remove("document-key", $opts);

    Expiration / TTL

    By default, Couchbase documents do not expire, but transient or temporary data may be needed for user sessions, caches, or other temporary documents. Using Touch(), you can set expiration values on documents to handle transient data:

    $collection->touch($key, 60 /* seconds */);

    A network timeout can be set with the optional TouchOptions(), in the same fashion as earlier examples on this page:

    $opts = new TouchOptions();
    $opts->timeout(500000 /* microseconds */);
    $collection->touch($key, 60 /* seconds */);

    Another way to change expiration time is to use getAndTouch() method of the collection.

    $res = $collection->getAndTouch($key, 1 /* seconds */);
    printf("[getAndTouch] document content: %s\n", var_export($res->content(), true));
    
    sleep(2); // wait until the document will expire
    
    try {
        $collection->get($key);
    } catch (Couchbase\DocumentNotFoundException $ex) {
        printf("The document does not exist\n");
    }
    If the absolute value of the expiry is less than 30 days (such as 60 * 60 * 24 * 30), it is considered an offset. If the value is greater, it is considered an absolute time stamp. For more on expiration see the expiration section of our documents discussion doc.

    Atomic document modifications

    The value of a document can be increased or decreased atomically using Binary.Increment() and .Binary.Decrement().

    Increment
    // increment binary value by 1 (default)
    $binaryCollection = $collection->binary();
    $res = $binaryCollection->increment("foo");
    // Create a document and assign it to 10 -- counter works atomically
    // by first creating a document if it doesn't exist. If it exists,
    // the same method will increment/decrement per the "delta" parameter
    $key = "phpDevguideExampleCounter";
    $opts = new IncrementOptions();
    $opts->initial(10)->delta(2);
    
    $res = $binaryCollection->increment($key, $opts);
    // Should print 10
    printf("Initialized Counter: %d\n", $res->content());
    Decrement
    // decremtnt binary value by 1 (default)
    $res = $binaryCollection->decrement("foo");
    Decrement (with options)
    $opts = new DecrementOptions();
    $opts->initial(10)->delta(4);
    // Decrement value by 4 to 8
    $res = $binaryCollection->decrement($key, $opts);
    // Should print 8
    printf("Decremented Counter: %d\n", $res->content());
    Increment & Decrement are considered part of the ‘binary’ API and as such may still be subject to change

    Additional Resources

    Working on just a specific path within a JSON document will reduce network bandwidth requirements - see the Sub-Document pages.

    Another way of increasing network performance is to pipeline operations with Batching Operations.

    As well as various Formats of JSON, Couchbase can work directly with arbitary bytes, or binary format.

    Our Query Engine enables retrieval of information using the SQL-like syntax of N1QL.