Couchbase Server Quickstart - Java with Couchbase SDK 2.7 and IntelliJ

    +
    Using Intellij and Couchbase Java SDK 2.7 to create new database records in Couchbase and look them up.

    Prerequisite: Run Couchbase Server

    1. Couchbase Server 6.5 is already running.

      • An empty bucket named "default" has been created.

      • Both a primary index and an adaptive index have been created and built on the default bucket.

      • If you still need to perform these tasks please use the following:

    2. IntelliJ is installed. If you don’t have it installed yet, follow this tutorial.

    3. Java 8 or higher is installed.

    Step 1: Start a New Project on IntelliJ

    Open IntelliJ and create a new project.

    New Project dialog in IntelliJ

    Select the Maven template in the next dialog:

    Template select in IntelliJ

    Inform a name for your project and click on Finish:

    Project name in IntelliJ

    In the end, your project should look similar to the following:

    Project name in IntelliJ

    Now, right-click on the java folder of your project and select new → package and choose a name for your new package:

    Create Package

    You can create new classes by right-clicking on your package name and selecting new → Java Class:

    Step 2: Adding Couchbase Dependency

    To add Couchbase as a dependency, simply add following block above the tag </project> near the end of your pom.xml file:

    <dependencies>
      <dependency>
        <groupId>com.couchbase.client</groupId>
        <artifactId>java-client</artifactId>
        <version>2.7.14</version>
      </dependency>
    </dependencies>
    If the <dependencies> tag is already present in your pom.xml file, you should add just the dependency instead:
        <!-- add the block bellow inside the <dependencies> tag -->
          <dependency>
            <groupId>com.couchbase.client</groupId>
            <artifactId>java-client</artifactId>
            <version>2.7.14</version>
          </dependency>

    Step 3: Connecting to Couchbase

    We will build a simple line command app. Let’s start by creating a new class called QuickStartCouchbase to show how to connect with Couchbase:

    import com.couchbase.client.java.*;
    import com.couchbase.client.java.document.*;
    import com.couchbase.client.java.document.json.*;
    import com.couchbase.client.java.query.*;
    
    public class QuickStartCouchbase {
    
        public static void main(String[] args) {
    
            String bucketName = "default";
            String username = "Administrator";
            String password = "password";
            Cluster cluster = null;
            Bucket bucket = null;
    
            try {
    
                // Initialize the Connection
                cluster = CouchbaseCluster.create("localhost");
                cluster.authenticate(username, password);
                bucket = cluster.openBucket(bucketName);
    
    
            } catch (Exception e ) {
                System.out.println("Ooops!... something went wrong");
                e.printStackTrace();
            } finally {
    
                //Naive way to just close a single bucket
                if(bucket != null) {
                    bucket.close();
                }
    
                // Disconnect and close all buckets
                if(cluster != null) {
                    cluster.disconnect();
                }
            }
    
        }
    }
    It is very important that cluster and bucket instances are created during startup and are then reused until the application shuts down. Connection setup is expensive and the SDK is designed to be thread safe and can be efficiently used across all your application threads.

    The cluster and bucket objects can be reused in your application, the most common pattern is to create a Singleton returning them. You can read more about how to manage your connection here.

    Step 4: Create and query new document

    Suppose we need to store the following data in the database representing 3 distinct users:

    //user::0001
    {
        "firstName" : "Perry",
        "lastName" : "Mason",
        "email" : "perry.mason@acme.com",
        "tagLine" : "Who can we get on the case?",
        "type" : "user"
    }
    
    //user::0002
    {
        "firstName" : "Major",
        "lastName" : "Tom",
        "email" : "major.tom@acme.com",
        "tagLine" : "Send me up a drink",
        "type" : "user"
    }
    
    //user::0003
    {
        "firstName" : "Jerry",
        "lastName" : "Wasaracecardriver",
        "email" : "jerry.wasaracecardriver@acme.com",
        "tagLine" : "el sob number one",
        "type" : "user"
    }

    The code to store this data would look like the following:

        // Create a JSON Document
        JsonObject u1 = JsonObject.create()
                .put("firstName", "Perry")
                .put("lastName", "Mason")
                .put("email", "perry.mason@acme.com")
                .put("type", "user")
                .put("tagLine", "Who can we get on the case?");
    
        // Store the Document
        bucket.upsert(JsonDocument.create("user::0001", u1));
    
    
        // Create a JSON Document
        JsonObject u2 = JsonObject.create()
                .put("firstName", "Major")
                .put("lastName", "Tom")
                .put("email", "major.tom@acme.com")
                .put("type", "user")
                .put("tagLine", "Send me up a drink");
    
        // Store the Document
        bucket.upsert(JsonDocument.create("user::0002", u2));
    
    
        // Create a JSON Document
        JsonObject u3 = JsonObject.create()
                .put("firstName", "Jerry")
                .put("lastName", "Wasaracecardriver")
                .put("email", "jerry.wasaracecardriver@acme.com")
                .put("type", "user")
                .put("tagLine", "el sob number one");
    
        // Store the Document
        bucket.upsert(JsonDocument.create("user::0003", u3));

    To recover the document by the id, you can use the method get:

        // Load the Document by its id and print it
        // Prints Content and Metadata of the stored Document
        System.out.println(bucket.get("user::0001"));

    Finally, here is how you query the database when you need all users where the email ends with @acme.com:

        // Perform a N1QL Query
        N1qlQueryResult result = bucket.query(
                N1qlQuery.parameterized("SELECT * FROM `" + bucketName + "` WHERE email like $email",
                        JsonObject.create().put("email", "%@acme.com"))
        );
    
        // Print each found Row
        for (N1qlQueryRow row : result) {
            System.out.println(row);
        }

    Here is the code of the whole class:

    import com.couchbase.client.java.*;
    import com.couchbase.client.java.document.*;
    import com.couchbase.client.java.document.json.*;
    import com.couchbase.client.java.query.*;
    
    public class QuickStartCouchbase {
    
        public static void main(String[] args) {
    
            String bucketName = "default";
            String username = "Administrator";
            String password = "password";
            Cluster cluster = null;
            Bucket bucket = null;
    
            try {
    
                // Initialize the Connection
                cluster = CouchbaseCluster.create("localhost");
                cluster.authenticate(username, password);
                bucket = cluster.openBucket(bucketName);
    
                // Create a JSON Document
                JsonObject u1 = JsonObject.create()
                        .put("firstName", "Perry")
                        .put("lastName", "Mason")
                        .put("email", "perry.mason@acme.com")
                        .put("type", "user")
                        .put("tagLine", "Who can we get on the case?");
    
                // Store the Document
                bucket.upsert(JsonDocument.create("user::0001", u1));
    
    
                // Create a JSON Document
                JsonObject u2 = JsonObject.create()
                        .put("firstName", "Major")
                        .put("lastName", "Tom")
                        .put("email", "major.tom@acme.com")
                        .put("type", "user")
                        .put("tagLine", "Send me up a drink");
    
                // Store the Document
                bucket.upsert(JsonDocument.create("user::0002", u2));
    
    
                // Create a JSON Document
                JsonObject u3 = JsonObject.create()
                        .put("firstName", "Jerry")
                        .put("lastName", "Wasaracecardriver")
                        .put("email", "jerry.wasaracecardriver@acme.com")
                        .put("type", "user")
                        .put("tagLine", "el sob number one");
    
                // Store the Document
                bucket.upsert(JsonDocument.create("user::0003", u3));
    
                // Load the Document and print it
                // Prints Content and Metadata of the stored Document
                System.out.println(bucket.get("user::0001"));
    
                // Create a N1QL Primary Index (but ignore if it exists)
                bucket.bucketManager().createN1qlPrimaryIndex(true, false);
    
                // Perform a N1QL Query
                N1qlQueryResult result = bucket.query(
                        N1qlQuery.parameterized("SELECT * FROM `" + bucketName + "` WHERE email like $email",
                                JsonObject.create().put("email", "%@acme.com"))
                );
    
                // Print each found Row
                for (N1qlQueryRow row : result) {
                    System.out.println(row);
                }
            } catch (Exception e ) {
                System.out.println("Ooops!... something went wrong");
                e.printStackTrace();
            } finally {
    
                //Naive way to just close a single bucket
                if(bucket != null) {
                    bucket.close();
                }
    
                // Disconnect and close all buckets
                if(cluster != null) {
                    cluster.disconnect();
                }
            }
    
        }
    }
    Note that the code above has an extra line of code: bucket.bucketManager().createN1qlPrimaryIndex(true, false);. It will create a primary index in case you don’t have one yet. However, primary indexes should ideally only be used during development.

    If you want to run the code to see the output, right click on the class and choose the option "Run".