I am trying to create a secondary index in cloudant that aggregates multiple documents into a single document. This is the scenario that I have, say I have a Cloudant database that contains person addresses and three sample documents belonging to a fictitious person John G are as follows
{
"id":"xxx",
"Name":"John G",
"Address Type":"H",
"Address":" Home Address blah blah blah"
}
{
"id":"yyy",
"Name":"John G",
"Address Type":"O",
"Address":"Office Address blah blah blah"
}
{
"id":"zzz",
"Name":"John G",
"Address Type":"V",
"Address":"Vacation/Summer house Address blah blah blah"
}
I would like to create a secondary index/view on this database that aggregates these three documents belonging to John G and creates one single document that looks like below
{
"id":"www",
"key":"John G",
"value":
{
"Address_Home":"Home Address blah blah blah",
"Address_Office":"Office Address blah blah blah",
"Address_Summerhouse":"Vacation/Summer house Address blah blah blah"
}
}
Please suggest how should I write the view/secondary index to achieve this.
You can't quite achieve what you suggest as you suggest it. A view takes one document and emits data based on that document only. You can't do 'sub queries' inside a map function. There is a way to link documents in a view if you have stored the id of one in the other (think foreign key). However, I think the issue here is that you're trying to shoehorn a relational model into Cloudant, which usually is a bad idea. De-normalise instead, and store all three address records in the same document. This may seem inefficient if you come from a relational background - but Cloudant does not have joins in the traditional sense, and the atomic unit is the document.