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.

    The complete code sample used on this page can be downloaded from here.

    At its heart Couchbase Server is a high-performance key-value store, and the key-value interface outlined below is the fastest and best method to perform operations involving single 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.

    Before proceeding, make sure you’re familiar with the basics of authorization and connecting to a Cluster from the Start Using the SDK section.

    The code samples below will use these imports:

    import com.couchbase.client.core.error.*;
    import com.couchbase.client.core.msg.kv.DurabilityLevel;
    import com.couchbase.client.java.*;
    import com.couchbase.client.java.json.*;
    import com.couchbase.client.java.kv.*;
    
    import java.time.Duration;
    
    import static com.couchbase.client.java.kv.GetOptions.getOptions;
    import static com.couchbase.client.java.kv.InsertOptions.insertOptions;
    import static com.couchbase.client.java.kv.ReplaceOptions.replaceOptions;
    import static com.couchbase.client.java.kv.UpsertOptions.upsertOptions;
    N1QL vs. Key-Value

    N1QL can also be used to perform many single-document operations but we very strongly recommend using the key-value API for this instead, as it can be much more efficient. The request can go directly to the correct node, there’s no query parsing overhead, and it’s over the highly optimized memcached binary protocol.

    JSON

    The Couchbase Server is a key-value store that’s agnostic to what’s stored, but it’s very common to store JSON so most of the examples below will focus on that use-case.

    The Java SDK provides you with several options for working with JSON.

    If you pass any object (like the provided JsonObject and JsonArray), including Map<String, Object> or List<Object> into the APIs provided, the SDK will use its internal JSON codec (utilizing Jackson) to encode/decode those objects transparently. The SDK also supports custom transcoders and serializers which are covered separately.

    Upsert

    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.

    Here is a simple upsert operation, which will insert the document if it does not exist, or replace it if it does.

    We’ll use the built-in JSON types for simplicity, but you can use different types if you want.

    JsonObject content = JsonObject.create().put("author", "mike").put("title","My Blog Post 1");
    
    MutationResult result = collection.upsert("document-key", content);

    All the examples here use the Java SDK’s simplest API, which blocks until the operation is performed. There’s also an asynchronous API that is based around Java’s CompletableFuture, and a reactive API built around Project Reactor. They can be accessed like this:

    AsyncCollection asyncCollection = collection.async();
    ReactiveCollection reactiveCollection = collection.reactive();

    Insert

    Insert works very similarly to upsert, but will fail if the document already exists with a DocumentExistsException:

    try {
      JsonObject content = JsonObject.create().put("title", "My Blog Post 2");
      MutationResult insertResult = collection.insert("document-key", content);
    } catch (DocumentExistsException ex) {
      System.err.println("The document already exists!");
    } catch (CouchbaseException ex) {
      System.err.println("Something else happened: " + ex);
    }

    Retrieving documents

    We’ve tried upserting and inserting documents into Couchbase Server, let’s get them back:

    try {
      GetResult getResult = collection.get("document-key");
      String title = getResult.contentAsObject().getString("title");
      System.out.println(title); // title == "My Blog Post"
    } catch (DocumentNotFoundException ex) {
      System.out.println("Document not found!");
    }

    Of course if we’re getting a document we probably want to do something with the content:

    GetResult found = collection.get("document-key");
    JsonObject content = found.contentAsObject();
    if (content.getString("author").equals("mike")) {
        // do something
    } else {
        // do something else
    }

    Once we have a GetResult, we can use contentAsObject() to turn the content back into a JsonObject like we inserted it in the examples before, or use the more generic contentAs(T.class) equivalent to turn it back into other entity structures. In fact, the contentAsObject() method is just a convenience method for contentAs(JsonObject.class).

    Replace

    A very common sequence of operations is to get a document, modify its contents, and replace it.

    collection.upsert("my-document", JsonObject.create().put("initial", true));
    
    GetResult result = collection.get("my-document");
    JsonObject content = result.contentAsObject();
    content.put("modified", true).put("initial", false);
    collection.replace("my-document", content, replaceOptions().cas(result.cas()));

    We upsert an initial version of the document. We don’t care about the exact details of the result, just whether it succeeded or not, so do not assign a return value. Then we get it back into doc and pull out the document’s content as a JsonObject using contentAs. Afterwards, we update a field in the JsonObject with put. JsonObject is mutable, we don’t need to store the result of the put. Finally, we replace the document with the updated content, and a CAS value, storing the final result as result.

    So, what is CAS?

    CAS, or Compare And Swap, is a form of optimistic locking. Every document in Couchbase has a CAS value, and it’s changed on every mutation. When you get a document you also get the document’s CAS, and then when it’s time to write the document, you send the same CAS back. If another thread or program has modified that document in the meantime, the Couchbase Server can detect you’ve provided a now-outdated CAS, and return an error. This provides cheap, safe concurrency. See this detailed description of CAS for further details.

    In general, you’ll want to provide a CAS value whenever you replace a document, to prevent overwriting another agent’s mutations.

    Retrying on CAS failures

    But if we get a CAS mismatch, we usually just want to retry the operation. Let’s see a more advanced replace example that shows one way to handle this:

    String id = "my-document";
    collection.upsert(id, JsonObject.create().put("initial", true));
    
    GetResult found = collection.get(id);
    JsonObject content = found.contentAsObject();
    content.put("modified", true).put("initial", false);
    while (true) {
        try {
            collection.replace(id, content, replaceOptions().cas(found.cas()));
            break; // if successful, break out of the retry loop
        } catch (CasMismatchException ex) {
            // don't do anything, we'll retry the loop
        }
    }

    Note that this code is simplistic to show how CAS retry works in general. If the replace() above never works, you would always get a CAS mismatch, and never break out of the loop - so for(int i = 0; i < maxAttempts; i++) would be a resaonable alternative.

    In later chapters we cover more sophisticated approaches to this, including asynchronous retry, retry with backoff and bailing out after a maximum amount of tries. All these should be in place for robust, production ready code.

    Removing

    Removing a document is straightforward:

    try {
      collection.remove("my-document");
    } catch (DocumentNotFoundException ex) {
      System.out.println("Document did not exist when trying to remove");
    }

    Like replace, remove also optionally takes the CAS value if you want to make sure you are only removing the document if it hasn’t changed since you last fetched it.

    Durability

    Writes in Couchbase are written to a single node, and from there the Couchbase Server will take care of sending that mutation to any configured replicas.

    The optional durability parameter, which all mutating operations accept, allows the application to wait until this replication (or persistence) is successful before proceeding.

    It can be used like this:

        collection.upsert(
            "my-document",
            JsonObject.create()
                .put("doc",
                    true),
            upsertOptions().durability(DurabilityLevel.MAJORITY)
        );

    If no argument is provided the application will report success back as soon as the primary node has acknowledged the mutation in its memory. However, we recognize that there are times when the application needs that extra certainty that especially vital mutations have been successfully replicated, and the other durability options provide the means to achieve this.

    The options differ depend on what Couchbase Server version is in use. 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.

    If a version of Couchbase Server lower than 6.5 is being used then the application can fall-back to 'client verified' durability. Here the SDK will do a simple poll of the replicas and only return once the requested durability level is achieved. This can be achieved like this:

        collection.upsert(
            "my-document",
            JsonObject.create()
                .put("doc",
                    true),
            upsertOptions().durability(PersistTo.NONE,
                ReplicateTo.TWO)
        );

    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.

    Document Expiration

    Couchbase Server includes an option to have particular documents automatically expire after a set time. This can be useful for some use-cases, such as user sessions, caches, or other temporary documents.

    You can set an expiry value when creating a document:

    MutationResult insertResult = collection.insert(
      "my-document",
      json,
      insertOptions().expiry(Duration.ofHours(2))
    );

    When getting a document, the expiry is not provided automatically by Couchbase Server but it can be requested:

    GetResult found = collection.get("my-document", getOptions().withExpiry(true));
    System.out.println("Expiry of found doc: " + found.expiry());

    Note that when updating the document, special care must be taken to avoid resetting the expiry to zero. Here’s how:

    GetResult found = collection.get("my-document", getOptions().withExpiry(true));
    
    collection.replace(
      "my-document",
      json,
      replaceOptions().expiry(found.expiry().get())
    );

    Some applications may find getAndTouch useful, which fetches a document while updating its expiry field. It can be used like this:

    collection.getAndTouch("my-document", Duration.ofDays(1));
    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.

    Additional resources

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

    For a significant performance speed up with large volumes of data, reference our asynchronous programmaing options.

    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 arbitrary bytes, or binary format.

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