<dependencies>
<dependency>
<groupId>com.couchbase.client</groupId>
<artifactId>java-client</artifactId>
<version>2.5.8</version>
</dependency>
</dependencies>
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 Example {
public static void main(String... args) throws Exception {
// 初始化连接
Cluster cluster = CouchbaseCluster.create("localhost");
cluster.authenticate("username", "password");
Bucket bucket = cluster.openBucket("bucketname");
// 创建json对象
JsonObject arthur = JsonObject.create()
.put("name", "Arthur")
.put("email", "kingarthur@couchbase.com")
.put("interests", JsonArray.from("Holy Grail", "African Swallows"));
// 存储文档
bucket.upsert(JsonDocument.create("u:king_arthur", arthur));
// 加载文档并打印
// 打印存储文档的内容和元数据
System.out.println(bucket.get("u:king_arthur"));
//创建一个N1QL主索引(但如果它存在则忽略)
bucket.bucketManager().createN1qlPrimaryIndex(true, false);
// Perform a N1QL Query
N1qlQueryResult result = bucket.query(
N1qlQuery.parameterized("SELECT name FROM `bucketname` WHERE $1 IN interests",
JsonArray.from("African Swallows"))
);
// Print each found Row
for (N1qlQueryRow row : result) {
// Prints {"name":"Arthur"}
System.out.println(row);
}
}
}