在java中为每个文档生成密钥的标准过程是什么?

时间:2017-03-28 05:35:36

标签: couchbase couchbase-java-api

我想在Java中将文档作为批量插入Couchbase。那么为java中的每个文档生成密钥的标准过程是什么??

1 个答案:

答案 0 :(得分:0)

您可以使用Couchbase&#34;计数器&#34;文档作为序列的一种形式。使用Java SDK的反应式方法,假设您的批处理是List<JsonObject>,并且要将每个内容保存到Couchbase,这将是这样的:

//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,这样可以减少冲突的风险(否则,存储桶中的其他文档可以命名为#34; 1&#34;如果您这样做对于同一个桶内的多种类型的文件而言。)

同时调整用于满足您需求的保存方法(此处为upsert vs create vs update,TTL,耐久性要求等......)