参考blog我可以批量上传文件。我的问题是很少有文件已经存在于cloudant中。所以建议的方法是失败的。如果文档不存在于cloudant中,请建议如何处理批量添加,否则如果docuemnts存在则更新bluk update。
答案 0 :(得分:0)
以下代码对我有用:
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);
}