Create a Couchbase Document without Specifying an ID

java

#1

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:

import com.couchbase.client.java.CouchbaseCluster
import com.couchbase.client.java.Cluster
import com.couchbase.client.java.Bucket
import com.couchbase.client.java.document.JsonDocument

// 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));


#2

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


#3

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).


#4

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


#5

@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.


#6

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


#7

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.

import com.couchbase.client.java.Bucket
import com.couchbase.client.java.Cluster
import com.couchbase.client.java.CouchbaseCluster
import com.couchbase.client.java.document.json.JsonObject
import com.couchbase.client.java.document.JsonDocument

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