Channels ▼
RSS

Web Development

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");
System.out.println(d.toString());

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:


{"_id":"1","_rev":"11366234614","EmpNO":"1","Name":"Mike","Group":"J2EECOE,"Designation":"Manager","Language":"Java"}

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:


{"total_rows":10,"offset":0,"rows":[
{"id":"1","key":"1","value":{"rev":"2-1489202834"}},
{"id":"2","key":"2","value":{"rev":"1-4204838667"}},
{"id":"3","key":"3","value":{"rev":"1-4214212353"}},
{"id":"4","key":"4","value":{"rev":"1-1670290986"}},
{"id":"5","key":"5","value":{"rev":"1-3067378719"}}
]}

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:


{"total_rows":10,"offset":2,"rows":[
{"id":"3","key":"3","value":{"rev":"1-4214212353"}},
{"id":"4","key":"4","value":{"rev":"1-1670290986"}},
{"id":"5","key":"5","value":{"rev":"1-3067378719"}},
{"id":"6","key":"6","value":{"rev":"1-3896700837"}}
]}

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();
doc.setId("_design/couchview");
				
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); 
db.saveDocument(doc);

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)
{
       System.out.println(strdata);
}

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:


{"total_rows":7,"offset":0,"rows":[
{"id":"1","key":null,"value":{"_id":"1","_rev":"2-1489202834","EmpNO":"1","Name":"Mike","Group":"J2EECOE","Designation":"Manager","Language":"Java"}},
{"id":"2","key":null,"value":{"_id":"2","_rev":"1-4204838667","EmpNO":"2","Name":"Hayden","Group":"J2EECOE","Designation":"RA","Language":"Java"}},
{"id":"3","key":null,"value":{"_id":"3","_rev":"1-4214212353","EmpNO":"3","Name":"Tom","Group":"J2EECOE","Designation":"JRA","Language":"Java"}},
{"id":"4","key":null,"value":{"_id":"4","_rev":"1-1670290986","EmpNO":"4","Name":"Harry","Group":"J2EECOE","Designation":"TeamLead","Language":"Java"}},
{"id":"6","key":null,"value":{"_id":"6","_rev":"1-3896700837","EmpNO":"6","Name":"Andrew","Group":"J2EECOE","Designation":"SE","Language":"Java"}},
{"id":"8","key":null,"value":{"_id":"8","_rev":"1-1691341568","EmpNO":"8","Name":"James","Group":"BCMD","Designation":"SE","Language":"Java"}},
{"id":"9","key":null,"value":{"_id":"9","_rev":"1-793156542","EmpNO":"9","Name":"Peter","Group":"BCMD","Designation":"TeamLead","Language":"Java"}}
]}

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:


{"total_rows":2,"offset":0,"rows":[
{"id":"6","key":null,"value":{"_id":"6","_rev":"1-3896700837","EmpNO":"6","Name":"Andrew","Group":"J2EECOE","Designation":"SE","Language":"Java"}},
{"id":"8","key":null,"value":{"_id":"8","_rev":"1-1691341568","EmpNO":"8","Name":"James","Group":"BCMD","Designation":"SE","Language":"Java"}}
]}

Conclusion

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.
 
Dr. Dobb's TV