Joins between data, even when the documents being examined are contained within the same bucket, are not possible directly within the view system. However, you can simulate this by making use of a common field used for linking when outputting the view information. For example, consider a blog post system that supports two different record types, 'blogpost' and 'blogcomment'. The basic format for 'blogpost' is:
{ "type" : "post", "title" : "Blog post" "categories" : [...], "author" : "Blog author" ... }
The corresponding comment record includes the blog post ID within the document structure:
{ "type" : "comment", "post_id" : "post_3454" "author" : "Comment author", "created_at" : 123498235 ... }
To output a blog post and all the comment records that relate to the blog post, you can use the following view:
function(doc, meta) { if (doc.post_id && doc.type && doc.type == "post") { emit([doc.post_id, null], null); } else if (doc.post_id && doc.created_at && doc.type && doc.type == "comment") { emit([doc.post_id, doc.created_at], null); } }
The view makes use of the sorting algorithm when using arrays as the view key. For a blog post record, the document ID will be output will a null second value in the array, and the blog post record will therefore appear first in the sorted output from the view. For a comment record, the first value will be the blog post ID, which will cause it to be sorted in line with the corresponding parent post record, while the second value of the array is the date the comment was created, allowing sorting of the child comments.
For example:
{"rows":[ {"key":["post_219",null], "value":{...}}, {"key":["post_219",1239875435],"value":{...}}, {"key":["post_219",1239875467],"value":{...}}, ] }
Another alternative is to make use of a multi-get operation within your client through the main Couchbase SDK interface, which should load the data from cache. This allows you to structure your data with the blog post containing an array of the of the child comment records. For example, the blog post structure might be:
{ "type" : "post", "title" : "Blog post" "categories" : [...], "author" : "Blog author", "comments": ["comment_2298","comment_457","comment_4857"], ... }
To obtain the blog post information and the corresponding comments, create a view to find the blog post record, and then make a second call within your client SDK to get all the comment records from the Couchbase Server cache.