Click anywhere to close

One-to-Many Relationships in CouchDB

Recently I have been playing around a lot with CouchDB, and one of the more challenging aspects of it is understanding the map/reduce functions on views.

This is how I handle a One-to-Many foreign key between different types of objects.

The data is set up as follows:
{
    "_id":1,
    "type":"person",
    "name":"mike"
    ...
},
{
    "_id":2,
    "type":"pet",
    "name":"barky",
    "owner":1
    ...
},
{
    "_id":3,
    "type":"pet",
    "name":"chirpy",
    "owner":1
    ...
}
And here is the map/reduce function that I use to retrieve a person and their pets:
Map:
function( doc ) {
    if( doc.type === "person" )
        emit( [doc._id, 0], doc );
    if( doc.type === "pet" )
        emit( [owner, 1], doc );
}
Reduce:
function( keys, values ) {
    var person = { _id: null, pets: [] }
    for( var value in values ) {
        var cur = values[ value ];
        if( cur.type === "user" ) {
            person._id = cur._id;
        }
        if( cur.type === "pet" ) {
            person.pets.push( cur );
        }
    }
    return person;
}

Now just make sure that you query your view with a group_level of 1, and it should return to you a user object with an array pets.


Recent Posts

Retro on Colab Using Google Colab to run OpenAI's Gym Retro
Categories:  AI/ML, Colab, Retro
Posted: May 25, 2018
Running Multiple Retro Environments Using retrowrapper to easily run environments as subprocesses
Categories:  AI/ML, Retro
Posted: May 22, 2018
Google Colab + Losswise Using Losswise as a replacement for Tensorboard on Colab
Categories:  AI/ML, Colab
Posted: May 21, 2018
OpenAI Retro - Collision Maps Detecting collision maps from sonic frames using a U-Net
Categories:  Projects, AI/ML
Posted: May 20, 2018
Walmart.com - Fake "AirPods" I just can't believe that Walmart is allowing these on the marketplace
Categories:  Random
Posted: May 19, 2018