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. If this seems familiar, it is because the view we have created is just like the normalized data we examined right at the beginnoing of the tour. We have effectively normalized the data for this one purpose.  Compare these two reports: (1) normalised data  (2) denormalized data.  The data is different because they are based on different documents and I was not so disciplined when I set them up. 

The limitation in the denormalized version is that CouchDB only selects documents from a view based in the key field, so that is the only field you can filter on. if you want to filter by other fields you need to do that yourself in the application software (which I haven't done).  However the data in the denormalized case is all taken from the view and not the original student documents. This makes this sort of function super-fast - even for large amounts of data. However we do look up the subject name - and we only store the subject key in the view so the order is by the key value, not the subject name.

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.  

So you sacrifice flexibility for speed and efficiency. This is not an unusual trade-off, and one that is often worth-while.