我正在使用 lightcouch API通过 Java 连接到 couchdb。我可以使用 dbclient.save(object) 方法保存单个文档。但是,我的要求是一次保存批量文档。我找不到任何与使用 Lightcouch api 保存批量文档相关的方法。请提出任何可能的解决方案。
提前致谢!
我正在使用 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
}
算法很简单。
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();
}
我将在这个例子中描述两个值得注意的部分。
第一个是文档的收集。在这种情况下,我使用数组而不是List
示例。
Document[] docs = new Document[2];
docs[0] = new Person("John", "Smith", 34);
docs[1] = new Person("Jane", "Smith", 30);
您也可以使用 a List
,然后使用 Java 的实用方法将其转换为数组。
第二个是StringEntity
。根据 CouchDB 在HTTP Bulk Document API上关于使用单个请求修改多个文档的文档,您的请求正文的 JSON 结构应该如下所示。
{
"docs": [
DOCUMENT,
DOCUMENT,
DOCUMENT
]
}
这就是有点丑陋的StringEntity
定义的原因。
StringEntity data = new StringEntity("{ \"docs\": " + gson.toJson(docs) + "}");
作为响应,您将获得一个 JSON 数组,其中包含对象,其字段表示插入文档的 *_id* 和 *_rev* 以及事务状态指示器。
我做了同样的事情,但是使用 spring Rest Template 我创建了一个类,该类将保存要按照以下方式更新的文档。
public class BulkUpdateDocument {
private List<Object> docs;
}
我的 Rest 代码如下所示。
BulkUpdateDocument doc = new BulkUpdateDocument(ListOfObjects);
Gson gson = new Gson();
RestTemplate restTemplate = new RestTemplate();
HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.APPLICATION_JSON_UTF8);
HttpEntity<?> requestObject = new HttpEntity<Object>(gson.toJson(doc), header);
ResponseEntity<Object> postForEntity = restTemplate.postForEntity(path + "/_bulk_docs", requestObject, Object.class);