使用myCouch将多个文档发布到CouchDB

时间:2018-04-07 04:24:25

标签: c# couchdb mycouch

我正在将SQL数据库迁移到couchDB。我发布多个文档时遇到问题,比如大约8K文档ID。代码如下:

 MyClass cl = new MyClass();
 foreach (DataRow row in dteqEvent.Rows)
 {
    NewSnDocument pn = new NewSnDocument();
    pn.id = row[1].ToString(); //this is the document id
    pn.val = row[2].ToString(); 
    string json = JsonConvert.SerializeObject(pn);
    cl.PostToCouch(json); //method under MyClass to post documents
 }    

然后在MyClass下我有以下方法:

public async void PostToCouch(string json)
{
   using (var client = new MyCouchClient(HostServer, Database))
   {
         var resp = await client.Documents.PostAsync(json);
         Console.WriteLine(resp.StatusCode);
   }
}

前2K ID已成功发布,然后在此之后出现错误。错误说:"无法连接到远程服务器。" InnerException状态"无法建立连接,因为目标计算机主动拒绝它。"这与我的couchDB配置有关。

是否有另一种方法来发布多个文档。我在MyCouch中看到了批量操作,但我不清楚:https://github.com/danielwertheim/mycouch/wiki/documentation#bulk-operations 提前谢谢!

更新: 好吧,我设法通过调整代码来解决我的问题:

MyClass cl = new MyClass();
 List<NewSnDocument> pnList = new List<NewSnDocument>();
 foreach (DataRow row in dteqEvent.Rows)
 {
    NewSnDocument pn = new NewSnDocument();
    pn.id = row[1].ToString(); //this is the document id
    pn.val = row[2].ToString(); 
    pnList.Add(pn);
 }
 cl.PostToCouch(pnList);

然后MyClass下的方法:

public async void PostToCouch(List<NewSnDocument> obj)
{
   int r = obj.Count;
   using (var client = new MyCouchClient(HostServer, Database))
   {
       for(int i=0; i<r; i++)
       {
           string json = JsonConvert.SerializeObject(obj[i]);
           var resp = await client.Documents.PostAsync(json);
           Console.WriteLine(resp.StatusCode);
       }
}

1 个答案:

答案 0 :(得分:0)

我认为即使你更新的代码看起来也不对。我不确定,请查看我在您的代码中所做的评论/修改:

MyClass cl = new MyClass();
 List<NewSnDocument> pnList = new List<NewSnDocument>(); //List of documents
 foreach (DataRow row in dteqEvent.Rows)
 {
    NewSnDocument pn = new NewSnDocument();
    pn.id = row[1].ToString();
    pn.val = row[2].ToString(); 
    // cl.PostToCouch(pnList); 
    pnList.push(pn);//You need to push each document to the list of documents
                    //I'm not sure about C#, but there should some "push" method
                    //or something equivalent to "push"
 }
cl.PostToCouch(pnList);//"pnList" contains a list of documents
                       //So it should be posted to CouchDB outside "foreach" loop
                       //After all documents have been pushed into it