I decided to leave. I have a database with documents that describe a person.
Here is my Person
class that extends 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); }
The algorithm is simple.
- Create an array of type
Document
- Put your documents in an array
- Create an HTTP POST request
- Put the converted JSON array in the request body
- Submit
Here is some code that might look like.
Note: try / catch is omitted for brevity! Of course you should use them.
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(); }
I will describe two noteworthy parts in this example.
The first is a collection of documents. In this case, I used an array instead of List
for an example.
Document[] docs = new Document[2]; docs[0] = new Person("John", "Smith", 34); docs[1] = new Person("Jane", "Smith", 30);
You can also use List
and then convert it to an array using Java utility methods.
The second is StringEntity
. According to the CouchDB documentation in the HTTP Bulk Document API, for modifying multiple documents with a single request, the JSON structure of your request body should look like this.
{ "docs": [ DOCUMENT, DOCUMENT, DOCUMENT ] }
This is the reason for some ugly definition of StringEntity
.
StringEntity data = new StringEntity("{ \"docs\": " + gson.toJson(docs) + "}");
In response, you will receive a JSON array containing objects whose fields represent * * id and * _rev * of the inserted document along with a transaction status indicator.