Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.

Channels ▼

JVM Languages

Apache CouchDB and Java

Retrieving Data

You can retrieve data from CouchDB in two ways:

  • Retrieving based on keys
  • Retrieving based on field values

All the non-relational databases generally retrieve data based on the Key only. For each piece of data, there is a Key associated with it. If you want to retrieve any data than you need to specify the Key. You cannot perform search based on the value of any fields as in relational databases. In CouchDB, Key will be equal to Document Id.

You can retrieve all the documents in a particular database. For retrieving all the documents in the database "employee", you can use the following code:

String dbname = "employee";
Database db = dbSession.getDatabase(dbname);
ViewResults results = db.getAllDocuments();

Here the db.getAllDocuments() method is used to retrieve all the documents present in "employee" database.

You can retrieve a single document from a particular database. If you want to retrieve a document whose id is "1" from the "employee" database, then you can use the following code:

Database db = dbSession.getDatabase("employee");	
Document d = db.getDocument("1");

Here you are using db.getDocument("1") method to retrieve a particular document and it accepts DocID as its input parameter.

The result for DocID=1 is:


CouchDB also provides many different methods to retrieve documents in various ways as required. For example, if you want to retrieve the first five documents from the "employee" database, you can use the following code:

HttpClient httpclient = new DefaultHttpClient();

HttpGet get = new HttpGet("http://localhost:5984/employee/_all_docs?startkey=%221%22&limit=5");

HttpResponse response = httpclient.execute(get);

The result is:


From id values, you can retrieve all the documents. For example, if you want to retrieve documents whose id is from 3 to 6, then you can use this query:

HttpGet get = new HttpGet("http://localhost:5984/employee/_all_docs?startkey=%223%22&endkey=%226%22");

The result is:


Note: %22 is used for "(single quote).

You can also retrieve documents in descending order by including "descending = true" in the URL.

Again, CouchDB is a non-relational database. Non-relational databases only allow querying data based on "key" only, so we cannot retrieve data based on field values from such databases. But CouchDB provides a "Views" feature which lets you retrieve data based on "field" values. Views are used for querying and reporting on CouchDB documents. Views are defined with Javascript functions:

function(doc) {
  emit(null, doc);

To create a permanent view, the functions must first be saved into design documents. The IDs of design documents must begin with _design/ and have a special views attribute that have a map member and an optional reduce member to hold the view functions.

Back to the "employee" database example: At this point, you have data for nine employees in the database. So now we will show how to create a View and how to retrieve data using that View.

Views are shown below. First the name of the View is given, followed by the function it implements. If more than one View is created, then they will be separated by comma as shown below.

  " javalanguage ": {
    "map": "function(doc) { if (doc.Language = = 'Java')  emit(null, doc) }"
 "java_and_se ": {
  "map": "function(doc) { if (doc.Language = = 'Java' & doc.Designation  = = 'SE')  emit (null, doc) }"  

Now we will create a design document and put two Views and its functions in that document. The code below shows how to create a design document named "_design/couchview" and how to put Views in it. Here we are creating two Views named "javalanguage" and "java_and_se" and its functions.

  • javalanguage is used to retrieve the employees data for which "Language = Java" is satisfied.
  • java_and_se is used to retrieve the employees data for which "Language = Java" AND "Designation = SE".

Database db = dbSession.getDatabase("employee");
Document doc = new Document();
String str = "{\"javalanguage\": {\"map\": \"function(doc) { if (doc.Language == 'Java')  emit(null, doc) } \"}, \"java_and_se\": {\"map\": \"function(doc) { if (doc.Language == 'Java' & doc.Designation == 'SE')  emit(null, doc) } \"}}";
doc.put("views", str); 

Okay, we just created two Views named "javalanguage" and "java_and_se", which when called will retrieve employee's data from the database for which the function criteria are satisfied. Now we will call "javalanguage" View:

HttpClient httpclient = new DefaultHttpClient();

HttpGet get = new HttpGet("http://localhost:5984/employee/_design/couchview/_view/javalanguage");

HttpResponse response = httpclient.execute(get);
HttpEntity entity=response.getEntity();
InputStream instream = entity.getContent();

BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
String strdata = null;

while( (strdata =reader.readLine())!=null)

When you run the above code you will receive the following output. In this case, we retrieved total of seven employees data for which "Language = Java". If required, you can also extract document id from the result and retrieve data for each document.

The results of the retrieval process are:


Now if we want to retrieve data of the employees for Language = Java and Designation = SE, then we will call the java_and_se View as follows:

HttpGet get = new HttpGet("http://localhost:5984/employee/_design/couchview/_view/java_and_se");

The results in this case are:



In this article, we've shown how to create an Apache CouchDB database, how to insert data into that database, and how to retrieve data based on "keys" and "field" values, among other operations. All in all, we think you'll agreethat CouchDB is easy to use for data storage and retrieval.

Related Reading

More Insights

Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.