我正在使用 lightcouch API通过Java连接到couchdb.我可以使用dbclient.save(object)方法保存单个文档.但是,我的要求是一次保存批量文档.我无法找到任何与使用Lightcouch api保存批量文档相关的方法.请建议任何可能的解决方案
提前致谢!
我决定尝试一下。我有一个数据库,保存描述一个人的文档。
这是我的Person类,它扩展了LightCouch:Document
public class Person extends Document {
private String firstname = "";
private String lastname = "";
private int age = -1;
public Person(String firstname, String lastname, int age) {
super();
this.setFirstname(firstname);
this.setLastname(lastname);
this.setAge(age);
}
// setters and getters omitted for brevity
}
Run Code Online (Sandbox Code Playgroud)
算法很简单。
Document代码大致如下。
注意:为简洁起见,省略了 try/catch!当然,您应该使用它们。
public static void main(String[] args) {
// You could also use a List and then convert it to an array
Document[] docs = new Document[2];
docs[0] = new Person("John", "Smith", 34);
docs[1] = new Person("Jane", "Smith", 30);
DefaultHttpClient httpClient = new DefaultHttpClient();
// Note the _bulk_docs
HttpPost post = new HttpPost("http://127.0.0.1:5984/persons/_bulk_docs");
Gson gson = new Gson();
StringEntity data =
new StringEntity("{ \"docs\": " + gson.toJson(docs) + "}");
data.setContentType("application/json");
post.setEntity(data);
HttpResponse response = httpClient.execute(post);
if (response.getStatusLine().getStatusCode() != 201) {
throw new RuntimeException("Failed. HTTP error code: "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
httpClient.getConnectionManager().shutdown();
}
Run Code Online (Sandbox Code Playgroud)
我将描述这个例子中两个值得注意的部分。
第一个是文献收集。在本例中,我使用数组而不是 aList作为示例。
Document[] docs = new Document[2];
docs[0] = new Person("John", "Smith", 34);
docs[1] = new Person("Jane", "Smith", 30);
Run Code Online (Sandbox Code Playgroud)
您也可以使用 a List,然后使用 Java 的实用方法将其转换为数组。
第二个是StringEntity. 根据 CouchDB 关于HTTP Bulk Document API 的有关使用单个请求修改多个文档的文档,请求正文的 JSON 结构应如下所示。
{
"docs": [
DOCUMENT,
DOCUMENT,
DOCUMENT
]
}
Run Code Online (Sandbox Code Playgroud)
这就是定义有些丑陋的原因StringEntity。
StringEntity data = new StringEntity("{ \"docs\": " + gson.toJson(docs) + "}");
Run Code Online (Sandbox Code Playgroud)
作为响应,您将获得一个 JSON 数组,其中包含对象,这些对象的字段代表插入文档的 *_id* 和 *_rev* 以及事务状态指示器。