CouchDB Views

CouchDB provides two ways of getting data from your database. One is to simply access the database directly, and the system will filter and sort the data according to your query. This means that the system has to examine each record to find the ones that match and return them in the order you specify.  

This proces requires an index for the field you are sorting by, and this is kept up to date by the system once it is set up (if no index exists, SDUDSJS creates one).  But there is more to indexes than meets the eye. An index is just a simple type of 'view'. 

Views are like indexes, they allow you to sort data by any field. But you can specify rules about which documents to include in the index. You can also include other data fields in the index.  You can even create more than one index entry for each document. 

What does that mean in practice?  For example in our case studies we had student records that were denormalized, and included the exam results for that student. There could be any number of results per student stored in the student document along with contact details etc.. The test data includes a view that generated one index entry per result per student.  So in our case study example, there are five view entries for that one student (three for Maths, and one each for IT and Sales and Marketing). If this seems familiar, it is because the view we have created is just like the normalized data we examined right at the beginning of the tour. We have effectively normalized the data for this one purpose.  Compare these two reports:(1) normalized data, which is just a regular table listing and  (2) denormalised data, which is a listing of a view.  The data is different because they are based on different documents and I was not so disciplined when I set them up.

This concept takes a little getting used to, especially if you were brought up on SQL database management systems. There are more details on the CouchDB website. Don't get put off by the commands using 'curl'.  There is a user-friendly graphical user interface you would use instead, and numerous tutorials..

Views have other features to. You can group records and count or do maths on groups. However there are limitations. For example in the report you have just looked at, youi can only filter by subject, because this is the fields that is being indexed. You can't sort other fields because that would need an index of an index - which doesn't exist.