Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
CB JAVA 2.2.5 Subdoc Updates for Whats New Page
package com.couchbase.devguide;
import com.couchbase.client.core.message.kv.subdoc.multi.Lookup;
import com.couchbase.client.core.message.kv.subdoc.multi.Mutation;
import com.couchbase.client.java.document.json.JsonArray;
import com.couchbase.client.java.document.json.JsonObject;
import com.couchbase.client.java.error.subdoc.PathExistsException;
import com.couchbase.client.java.subdoc.DocumentFragment;
import java.util.Random;
/**
* Example of Subdocument API For Java
*/
public class Subdocument extends ConnectionBase {
@Override
protected void doWork() {
// Fetch and print the name from an airline
DocumentFragment<Lookup> resultLookup = bucket.lookupIn("airline_13633").get("name").doLookup();
LOGGER.info(resultLookup.content("name", String.class));
// ============== MUTATE EXAMPLE
// Update CallSign for "Pan Am" to "Clipper"
DocumentFragment<Mutation> resultMutation = bucket.mutateIn("airline_13633").upsert("callsign","CLIPPER",false).doMutate();
// Fetch and print the callsign from an airline
resultLookup = bucket.lookupIn("airline_13633").get("callsign").doLookup();
LOGGER.info(resultLookup.content("callsign", String.class));
// ============== ARRAY EXAMPLE
// Creates a "fleet" array and pushes aircraft into it
bucket.mutateIn("airline_13633").upsert("fleet", JsonArray.from(
JsonObject.create().put("name", "747-200B").put("heavy",true).put("engines",4),
JsonObject.create().put("name", "737-200").put("engines",2)
), false).doMutate();
// ============== ADD UNIQUE EXAMPLES
// Creates a "models" array and adds UNIQUE values into it
bucket.mutateIn("airline_13633").upsert("models",JsonArray.empty(),false).doMutate();
bucket.mutateIn("airline_13633").addUnique("models","747-200B",false).
addUnique("models","747-120",false).doMutate();
// This will fail! The Array already contains the 747-120
try {
bucket.mutateIn("airline_13633").addUnique("models", "747-120", false).doMutate();
} catch (PathExistsException ex){
LOGGER.info("Whoops! Model is already part of the models array.");
}
// ============== COUNTER EXAMPLE
// Increment passenger_served counter on the airline
bucket.mutateIn("airline_13633").counter("passengers.served",1L,true).doMutate();
// Simulate some randomness that a passenger complained while being served
if (new Random().nextInt() % 2 == 0) {
bucket.mutateIn("airline_13633").counter("passengers.complained",1L,true).doMutate();
}
}
public static void main(String[] args) {
new Subdocument().execute();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.