[英]What is the best approach to update a document in cloudant if available or else insert the document using Java cloudant API
下面的代碼為我工作:
public void upsert(List<JsonObject> bulkData,String dbName)
{
if (bulkData == null) {
return;
}
if(bulkData.isEmpty()){
return;
}
if(null==dbName || dbName.length() <1){
return;
}
int totalDocumentsToSave = 0;
int totalDocumentToInsert = 0;
int totalDocumentToUpdate = 0;
int totalUpdatesFailed=0;
int totalInsertsFailed =0;
totalDocumentsToSave = bulkData.size();
Database db = client.database(dbName, false);
try {
for (JsonObject aDoc : bulkData) {
if (aDoc.get("_id") != null) {
String _id= aDoc.get("_id").getAsString();
if(db.contains(_id))
{
try
{
Map<String, String> aDocOnCloudant = db.getAllDocsRequestBuilder()
.keys(_id)
.includeDocs(true)
.build()
.getResponse()
.getIdsAndRevs();
String _revId = aDocOnCloudant.get(_id);
aDoc.addProperty("_rev", _revId);
db.update(aDoc);
totalDocumentToUpdate++;
}
catch(Exception e)
{
totalUpdatesFailed++;
}
}
else
{
try
{
db.save(aDoc);
totalDocumentsToSave++;
}
catch(Exception e)
{
totalInsertsFailed++;
}
}
}
}
db.ensureFullCommit();
}
catch(Exception e){
}
String log = " .Number of Documents to Save: " + totalDocumentsToSave +
" .Number of Documents inserted: " + totalDocumentToInsert +
" .Number of Documents to Updated: " + totalDocumentToUpdate +
" .Failed Inserts: " + totalInsertsFailed +
" .Failed Updates: " + totalUpdatesFailed +
" .Cloudant full commit completed";
System.out.println(log);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.