如何一次插入许多文档?

时间:2019-02-28 08:06:45

标签: couchdb

当我想使用CouchDB插入文档时,我发送这样的请求:

POST http://localhost:5984/blogging/
Accept: application/json
Content-Type: application/json

{
    "name": "Example",
    "value": 5
}

它有效。但是,如果我想一次插入两个文档怎么办?我尝试:

POST http://localhost:5984/blogging/
Accept: application/json
Content-Type: application/json

[
    {
        "name": "Example 2",
        "value": 6
    },
    {
        "name": "Example 3",
        "value": 7
    }
]

它回答了我:

HTTP/1.1 400 Bad Request
Cache-Control: must-revalidate
Connection: close
Content-Length: 66
Content-Type: application/json
Date: Thu, 28 Feb 2019 08:03:52 GMT
Server: CouchDB/2.3.0 (Erlang OTP/19)
X-Couch-Request-ID: 9ed2f39fcf
X-CouchDB-Body-Time: 0

{
  "error": "bad_request",
  "reason": "Document must be a JSON object"
}

1 个答案:

答案 0 :(得分:3)

首先,我建议您从文档http://docs.couchdb.org/en/1.6.1/api/database/bulk-api.html#inserting-documents-in-bulk

中检查此API。

此外,您还没有发送有效的JSON对象。我会以这种方式更改您的请求:

POST http://localhost:5984/blogging/_bulk_docs
Accept: application/json
Content-Type: application/json

{
    "docs": [
        {
            "name": "Example 2",
            "value": 6
        },
        {
            "name": "Example 3",
            "value": 7
        }
    ]
}