我希望在Java中将文档作为批量插入Couchbase。那么,在java.中为每个文档生成密钥的标准过程是什么?
发布于 2017-03-30 09:14:01
您可以使用Couchbase“计数器”文档作为序列的形式。使用Java的反应性方法,如果您的批处理是一个包含要保存到Couchbase的每个内容的List<JsonObject>,则这样做如下:
//start with a sequence of contents to save
Observable.from(listOfDocumentContent)
//for each content, asynchronously generate something...
.flatMap(content -> bucket.async() //assuming bucket is a `Bucket`
//atomically generate an increasing value, starting from 0
.counter("DOCUMENT_KEY_GENERATOR", 1, 0) //use a more relevant document key
//this gives a `JsonLongDocument`, so extract the number and turn that + the original content into a `JsonDocument` to be saved
.map(cDoc -> JsonDocument.create(KEY_PREFIX + cDoc.content(), content))
)
//next up, asynchronously saving each document we generated in the previous step... You could also use insert since you don't expect the keys to already exist in Couchbase
.flatMap(docToSave -> bucket.async().upsert(docToSave))
//this will perform the above asynchronously but wait for the last doc in the batch to finish saving:
.toBlocking().last(); 注意,在生成要保存的文档时,我们使用了一个KEY_PREFIX,这样冲突的风险就更小了(否则,存储桶中的其他文档可以命名为"1“,如果您在同一个桶中对多个类型的文档这样做的话)。
还调整了用于您的需求的保存方法(在这里,upsert与create与update、TTL、耐久性要求等)
https://stackoverflow.com/questions/43061341
复制相似问题