How to connect to Couchbase Server and insert JSON documents into a Couchbase bucket using the official Java SDK.
couchbse
Hope you know how to how to setup couchbase server. Now time for create bucket and insert document in the bucket.
I will explain here how to create bucket and insert document into it using java. Please follow the below steps to insert data into bucket.
Step1
Create a java project using Maven
Open eclipse File -> new -> project
new project in eclipse
Step 2
Select maven project
maven project in eclipse
Step 3
Click on Next
java couchbase eclipse project
Step 4
Select next
maven details
Step 5
- Provide group Id
- Artifact Id
- Package
Now click on finish
maven project finished
Step 6
Open couchbase and Create bucket
create bucket in couchbase
If you get above message please change the per server RAM size
couchbase bucket ram size
Provide the bucket Name, Size and password and click on save button. now create the new bucket by clicking "Create New Data Bucket"
create bucket in couchbase
Provide
- bucket name
- Per Node Ram Quota
- Password
Now Click on Create buton, bucket created.
bucket in couchbase
click on documents , there should not be any documents.
Bucket With no documents
Step 7
Write the java class and insert the document in bucket
package com.cuchbase.java;
import com.couchbase.client.java.Bucket;
import com.couchbase.client.java.Cluster;
import com.couchbase.client.java.CouchbaseCluster;
import com.couchbase.client.java.document.JsonDocument;
import com.couchbase.client.java.document.json.JsonObject;
public class CouchbaseJava {
public static void main(String[] args) {
try{
////////Create the cluster
Cluster cluster = CouchbaseCluster.create();
////////////Open the bucket on that cluster
Bucket bucket = cluster.openBucket("javaant", "javaant");
///////////////////////Make a Json File
JsonObject object = JsonObject.empty()
.put("firstname", "Java")
.put("lastname", "Ant")
.put("type", "blog");
///////// create json object
JsonDocument doc = JsonDocument.create("myFirstDoc", object);
/////////insert the json object to bucket
JsonDocument response = bucket.upsert(doc);
System.out.println("Done");
}
catch(Exception e){
e.printStackTrace();
}
}
}Add the below dependency in pom.xml
<dependency>
<groupId>com.couchbase.client</groupId>
<artifactId>java-client</artifactId>
<version>2.0.1</version>
</dependency>Step 8
Run the class
Run java class in eclipse
Now check one document inserted in the bucket
document inserted in couchbase
Done