Introduction to Couchbase
Couchbase is a powerful NoSQL database that offers high performance, scalability, and flexibility for building modern web, mobile, and IoT applications. As a distributed database, Couchbase combines the strengths of relational databases with the flexibility of document databases, making it a popular choice for numerous industries.
Core APIs and Code Snippets
1. Connecting to Couchbase
import couchbase.cluster.Cluster; import couchbase.cluster.ClusterOptions; import couchbase.cluster.UserPasswordAuthenticator;
Cluster cluster = Cluster.connect("couchbase://localhost", ClusterOptions.clusterOptions("username", "password"));
2. Creating a Bucket
Bucket bucket = cluster.bucket("myBucket"); bucket.waitUntilReady(Duration.ofSeconds(10));
3. Inserting a Document
JsonObject doc = JsonObject.create()
.put("name", "John Doe")
.put("email", "john.doe@example.com");
bucket.defaultCollection().insert("user::1", doc);
4. Retrieving a Document
GetResult result = bucket.defaultCollection().get("user::1"); JsonObject doc = result.contentAsObject();
5. Updating a Document
JsonObject updatedDoc = doc.put("email", "john.doe@newdomain.com"); bucket.defaultCollection().replace("user::1", updatedDoc);
6. Deleting a Document
bucket.defaultCollection().remove("user::1");
7. Subdocument Operations
MutateInResult result = bucket.defaultCollection()
.mutateIn("user::1", Arrays.asList(MutateInSpec.upsert("address.city", "New York")));
8. Querying with N1QL
N1qlQueryResult result = cluster.query("SELECT * FROM `myBucket` WHERE age > 30"); for (N1qlQueryRow row : result) {
JsonObject jsonObject = row.value();
// process the result
}
Example Application
Let’s create a simple Java application that connects to Couchbase, creates a bucket, and performs CRUD operations on user data.
import couchbase.cluster.Cluster; import couchbase.cluster.ClusterOptions; import couchbase.cluster.UserPasswordAuthenticator; import couchbase.core.Collection; import couchbase.json.JsonObject;
public class CouchbaseApp {
public static void main(String[] args) {
Cluster cluster = Cluster.connect("couchbase://localhost", ClusterOptions.clusterOptions("username", "password"));
Bucket bucket = cluster.bucket("myBucket");
Collection collection = bucket.defaultCollection();
// Create a document
JsonObject doc = JsonObject.create().put("name", "Jane Doe").put("email", "jane.doe@example.com");
collection.insert("user::1", doc);
// Retrieve the document
JsonObject fetchedDoc = collection.get("user::1").contentAsObject();
System.out.println("Fetched Document: " + fetchedDoc);
// Update the document
fetchedDoc.put("email", "jane.doe@newdomain.com");
collection.replace("user::1", fetchedDoc);
// Remove the document
collection.remove("user::1");
}
}
With these sample APIs and example application, you can get started with Couchbase and leverage its powerful features for your projects.
Hash: 037c09c9fae5d1551fd6384010e321603ff430ce792f691adf745613a3f91002