gpt4 book ai didi

java - 如何在 java 中使用 lightcouch api 在 couchdb 中保存批量文档

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:26:37 25 4
gpt4 key购买 nike

我正在使用 lightcouch API通过 Java 连接到 couchdb。我可以使用 dbclient.save(object) 方法保存单个文档。但是,我的要求是一次保存大量文档。我找不到任何与使用 Lightcouch api 保存批量文档相关的方法。请提出任何可能的解决方案。

提前致谢!

最佳答案

我决定试一试。我有一个数据库,其中包含描述一个人的文档。

这是我的 Person 类,它扩展了 Document LightCouch :

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

}

算法简单。

  1. 创建一个类型为Document的数组
  2. 将你的文档放入数组
  3. 创建 HTTP POST 请求
  4. 将JSON转换后的数组放入请求体
  5. 发送

代码大致如下所示。

注意:为简洁起见省略了 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);

您也可以使用 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* 的对象以及交易状态指示符。

关于java - 如何在 java 中使用 lightcouch api 在 couchdb 中保存批量文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10350853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com