A newer version of this documentation is available.

View Latest

Key Value Operations

  • how-to
    +
    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.

    The complete code samples used on this page can be found here:

    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-new\" 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 a version of Couchbase Server lower than 6.5 is being used then the application can fall-back to 'client verified' durability.

    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.

    // Upsert with Durability
    $opts = new UpsertOptions();
    $opts->timeout(3000 /* milliseconds */);
    $opts->durabilityLevel(DurabilityLevel::MAJORITY);
    $res = $collection->upsert("document-key2", $opts);
    printf("document \"document-key2\" has been created with CAS \"%s\"\n", $res->cas());

    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-Document 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();
    $opts->timeout(5000); // 5 seconds
    $result = $collection->remove("document-key", $opts);
    printf("document \"document-key\" \"%s\" been removed successfully.\n", $res->cas());

    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 Counters

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

    Increment & Decrement are considered part of the ‘binary’ API and as such may still be subject to change.
    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());
    Setting the document expiry time only works when a document is created, and it is not possible to update the expiry time of an existing counter document with the Increment method — to do this during an increment, use with the Touch() method.

    Atomicity Across Data Centers

    If you are using Cross Data Center Replication (XDCR), be sure to avoid modifying the same counter in more than one datacenter. If the same counter is modified in multiple datacenters between replications, the counter will no longer be atomic, and its value can change in unspecified ways.

    A counter must be incremented or decremented by only a single datacenter. Each datacenter must have its own set of counters that it uses — a possible implementation would be including a datacenter name in the counter document ID.

    Scoped KV Operations

    It is possible to perform scoped key value operations on named Collections with the beta version of the next Couchbase Server release, 7.0β. See the API docs for more information.

    This feature is marked Uncommitted. Expect a promotion to Committed API in a future minor release.

    Here is an example showing an upsert in the users collection, which lives in the travel-sample.tenant_agent_00 keyspace:

    $document = ["name" => "John Doe", "preferred_email" => "johndoe111@test123.test"];
    $opts = new UpsertOptions();
    
    $agentScope = $bucket->scope("tenant_agent_00");
    $usersCollection = $agentScope->collection("users");
    
    $res = $usersCollection->upsert("user-key", $document, $opts);
    printf("document \"user-key\" has been created with CAS \"%s\"\n", $res->cas());

    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.