Created
June 6, 2014 04:41
-
-
Save weilliu/d2cd28a5410f297b7108 to your computer and use it in GitHub Desktop.
CBClient
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.couchbase.client.*; | |
import com.couchbase.client.CouchbaseClient; | |
import com.couchbase.client.protocol.views.Query; | |
import com.couchbase.client.protocol.views.View; | |
import com.couchbase.client.protocol.views.ViewResponse; | |
import com.couchbase.client.protocol.views.ViewRow; | |
import java.net.URI; | |
import java.util.Arrays; | |
import java.util.List; | |
import com.google.gson.Gson; | |
public class Client { | |
public static void main(String[] args) throws Exception { | |
// (Subset) of nodes in the cluster to establish a connection | |
List<URI> hosts = Arrays.asList( | |
new URI("http://127.0.0.1:8091/pools") | |
); | |
// Name of the Bucket to connect to | |
String bucket = "default"; | |
// Password of the bucket (empty) string if none | |
String password = ""; | |
// Connect to the Cluster | |
CouchbaseClient client = new CouchbaseClient(hosts, bucket, password); | |
// Store a Document | |
client.set("my-first-document", "Hello Couchbase!").get(); | |
// Retreive the Document and print it | |
System.out.println(client.get("my-first-document")); | |
//GSON example | |
Gson gson = new Gson(); | |
User user1 = new User("John", "Doe"); | |
User user2 = new User("Matt", "Ingenthron"); | |
User user3 = new User("Michael", "Nitschinger"); | |
client.set("user1", gson.toJson(user1)).get(); | |
client.set("user2", gson.toJson(user2)).get(); | |
client.set("user3", gson.toJson(user3)).get(); | |
System.out.println(client.get("user1")); | |
System.out.println(client.get("user2")); | |
System.out.println(client.get("user3")); | |
System.out.println("================= Test Views ==============="); | |
// 1: Load the View infos | |
String designDoc = "users"; | |
String viewName = "by_firstname"; | |
View view = client.getView(designDoc, viewName); | |
// 2: Create a Query object to customize the Query | |
Query query = new Query(); | |
query.setIncludeDocs(true); // Include the full document body | |
//filter the result | |
query.setRangeStart("M"); // Start with M | |
query.setRangeEnd("M\\uefff"); // Stop before N starts | |
// 3: Actually Query the View and return the results | |
ViewResponse response = client.query(view, query); | |
// 4: Iterate over the Data and print out the full document | |
for (ViewRow row : response) { | |
System.out.println(row.getDocument()); | |
} | |
// Shutting down properly | |
client.shutdown(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment