2017-03-05 58 views
0

參考blog我可以批量上傳文檔。我的問題是很少有文件已經存在於cloudant中。所以建議的方法是失敗的。如果文件不存在於雲中,請建議如何處理批量添加,如果文件已存在,請提供其他文件更新。什麼是最好的方法來更新cloudant中的文檔(如果可用)或者使用Java cloudant API插入文檔

+0

檢查的'upsert' opertation存在它創建一個新文檔的情況下,它是不存在或以其他方式對其進行更新。否則,你必須首先查詢哪些文件已經存在,然後觸發2個操作;更新和創建。 –

+0

感謝您的快速響應..但「cloudant-client-2.6.2.jar」沒有任何「upsert」操作。 所以,現在唯一的選擇是 1.拉每個文件,並檢查它是否存在。 2.如果沒有找到,然後添加它。 3.如果找到,則更新它。 –

回答

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

} 
相關問題