Using Java to Operate Couchbase
Using Java operations, Couchbase can use the APIs provided by the Couchbase Java SDK. The following are the steps and code examples for inserting, modifying, querying, and deleting data using the Couchbase Java SDK.
1. Add Maven dependency:
<dependency>
<groupId>com.couchbase.client</groupId>
<artifactId>java-client</artifactId>
<version>VERSION</version>
</dependency>
Among them, 'VERSION' is the version number of the Couchbase Java SDK.
2. Create a Couchbase cluster connection:
Cluster cluster = Cluster.connect("localhost", "USERNAME", "PASSWORD");
During the connection process, it is necessary to provide the host address of the Couchbase cluster, as well as optional username and password. If authentication is not enabled in the Couchbase cluster, the username and password parameters can be omitted.
3. Open or create a new bucket:
Bucket bucket = cluster.bucket("BUCKET_NAME");
BUCKET here_ NAME 'is the name of the bucket you created in Couchbase.
4. Obtain the default collection: ` DefaultCollection collection=bucket. defaultCollection()`
You can also choose other collections.
5. Insert data:
JsonObject document = JsonObject.create()
.put("id", "1")
.put("name", "John Doe")
.put("age", 30);
MutationResult result = collection.insert("document_key", document);
Before inserting data, first create a 'JsonObject' object, and then use the 'collection. insert (key, document)' method to insert the data into the collection. When inserting data, a unique 'key' needs to be provided, which is used for subsequent data access. After successfully inserting data, the 'insert' method will return a 'MutationResult' object.
6. Modify data:
JsonObject updatedDocument = JsonObject.fromJson('{"name": "Jane Doe"}')
MutationResult result = collection.replace("document_key", updatedDocument);
The 'collection. replace (key, updatedDocument)' method can be used to replace the data of the specified 'key'.
7. Query data:
GetResult getResult = collection.get("document_key");
JsonObject document = getResult.contentAsObject();
String name = document.getString("name");
int age = document.getInt("age");
The 'collection. get (key)' method can be used to obtain data based on the specified 'key'. Then use the 'contentAsObject' method to convert the obtained data into a 'JsonObject' object. You can obtain specific field values of data based on the 'JsonObject' object.
8. Delete data:
MutationResult result = collection.remove("document_key");
The 'collection. remove (key)' method can be used to delete data for the specified 'key'.
9. Close Couchbase cluster connection:
cluster.disconnect();
After the operation is completed, it is necessary to close the connection to the Couchbase cluster.
This completes the data insertion, modification, query, and deletion operations of the Java operation Couchbase. Based on your actual needs, you can write corresponding Java code according to the above steps.