Wednesday, 7 August 2013

CouchDB - an outer join on a many to many relationship

CouchDB - an outer join on a many to many relationship

I have couchDB database with 3 sets of documents Items, Users, Reviews A
many to many relationship is maintained in Reviews document for Items and
Users
User
{"type":"user","user_id":"U1"},
{"type":"user","user_id":"U2"},
{"type":"user","user_id":"U3"}
Item
{"type":"item","item_id":"I1"},
{"type":"item","item_id":"I2"},
{"type":"item","item_id":"I3"},
{"type":"item","item_id":"I4"}
Review
{"type":"review","item_id":"I1","user_id":"U1","score":4},
{"type":"review","item_id":"I1","user_id":"U2","score":3},
{"type":"review","item_id":"I2","user_id":"U1","score":4},
{"type":"review","item_id":"I3","user_id":"U3","score":1}
I want to get an outer join on Items and Users using reviews so as to get
the below results
Intended Result
{"total_rows":16,"offset":0,"rows":[
{"id":"...","key":"I1","value":["item"]},
{"id":"...","key":"I1","value":["user","U1",4]},
{"id":"...","key":"I1","value":["user","U2",3]},
{"id":"...","key":"I1","value":["user","U3",0]},
{"id":"...","key":"I2","value":["item"]},
{"id":"...","key":"I2","value":["user","U1",4]},
{"id":"...","key":"I2","value":["user","U2",0]},
{"id":"...","key":"I2","value":["user","U3",0]},
{"id":"...","key":"I3","value":["item"]},
{"id":"...","key":"I3","value":["user","U1",0]},
{"id":"...","key":"I3","value":["user","U2",0]},
{"id":"...","key":"I3","value":["user","U3",1]},
{"id":"...","key":"I4","value":["item"]},
{"id":"...","key":"I4","value":["user","U1",0]},
{"id":"...","key":"I4","value":["user","U2",0]},
{"id":"...","key":"I4","value":["user","U3",0]}
]}
I am using the tips mentioned in here
http://wiki.apache.org/couchdb/EntityRelationship#Many_to_Many:_Relationship_documents
"many_join_review": {
"map": "function(doc) {
if (doc.type == 'review') {
emit(doc.item_id,[doc.type,doc.user_id,doc.score]);
} else if (doc.type == 'item') {
emit(doc.item_id,[doc.type]);
}"
}
But unable to get the desired result on how to have zeros on items whose
reviews don't exist for a user. Do I need to add something under reduce
section.
Thanks

No comments:

Post a Comment