Create a Couchbase Document without Specifying an ID



Is it possible to insert a new document into a Couchbase bucket without specifying the document’s ID? I would like use Couchbase’s Java SDK create a document and have Couchbase determine the document’s UUID with Groovy code similar to the following:


// Connect to localhost
CouchbaseCluster myCluster = CouchbaseCluster.create()

// Connect to a specific bucket
Bucket myBucket = myCluster.openBucket(“default”)

// Build the document
JsonObject person = JsonObject.empty()
.put(“firstname”, “Stephen”)
.put(“lastname”, “Curry”)
.put(“twitterHandle”, “@StephenCurry30”)
.put(“title”, "First Unanimous NBA MVP)

// Create the document
JsonDocument stored = myBucket.upsert(JsonDocument.create(person));


Nope, determining an ID is the responsibility of the developer and the SDK doesn’t provide an automatic way of doing it.


Thank you, @simonbasle. Do you know how Couchbase developers typically go about create their documents’ IDs? I am dealing with a difficult data set where it is not the case that each entry will always have an inherently unique value. For example, it is not the case that each entry will always have a unique ID from another system (e.g. an SSN, an e-mail address, etc).


Why not just use an “artificial” Key and use UUID.randomUUID().toString().


@gmina That is a great idea. Let me try to implement it. Calling UUID.randomUUID().toString() returns an object of type java.util.UUID. But I will see if Couchbase accepts the value as a document ID.


Make sure you call the toString() method on the UUID object.


Using the UUID without the toString() method seems to be working. (I am storing the value to a String variable instead.) Hopefully, I am not overlooking anything that will come back to bite me later on.


Cluster myCluster = CouchbaseCluster.create()
Bucket myBucket = myCluster.openBucket(“myBucketName”)
String docId = UUID.randomUUID()

// …verify that the document ID is unique in the bucket…

docJson = JsonObject.empty()
.put(“myKey”, “myValue”)
doc = JsonDocument.create(docId, docJson)
JsonDocument insertedDoc = bucket.insert(doc, 500, TimeUnit.MILLISECONDS) // Specify the timeout to prevent TimeoutExceptions