Consider a very simple json document that I intend to store in Couchbase:
1 | { "key" : "1" , "value" : "one" } |
and a Java class to hold this json:
1 2 3 4 5 6 | public class KeyVal { private String key; private String value; ... } |
The following is the code to insert an instance of KeyVal to a Couchbase bucket:
1 2 3 4 5 | JsonObject jsonObject = JsonObject.empty().put( "key" , keyVal.getKey()).put( "value" , keyVal.getValue()); JsonDocument doc = JsonDocument.create(keyVal.getKey(), jsonObject); Observable<JsonDocument> obs = bucket .async() .insert(doc); |
The return type of the insert is an Observable, so if I needed to map the return type back a KeyVal I can use the extensive mapping support provided by Observable class.
1 2 3 4 5 6 | Observable<KeyVal> obs = bucket .async() .insert(doc) .map(jsonDoc -> new KeyVal(jsonDoc.id(), jsonDoc.content().getString( "value" )) ); |
Other API's follow a similar pattern, for eg. to retrieve the saved document:
1 2 3 4 5 6 | bucket .async() .get(id) .map(doc -> new KeyVal(doc.id(), doc.content().getString( "value" ))); |
If you are interested in exploring this sample further, here is my github repo with a working example - https://github.com/bijukunjummen/sample-karyon2-couch
References:
- Couchbase Java SDK: http://docs.couchbase.com/developer/java-2.1/java-intro.html
- Rx-Java: https://github.com/ReactiveX/RxJava
- An excellent and concise article on Rx-Java provided at the Couchbase site: http://docs.couchbase.com/developer/java-2.0/observables.html