How to join using embedded links in rethinkdb

60 Views Asked by At

given a similar schema for people as:

[{
  "id": 1,
  "name": "Darth",
  "family": [2,3]
},
  {
    "id": 2,
    "name": "Luke"
  },
  {
    "id": 3,
    "name": "Leia"
  }
]

how do I return Darth and outer join to get all his family?

2

There are 2 best solutions below

2
On BEST ANSWER

I you want the ids in family to be replaced with the documents for the family members, you can do a map with a get.

Like this:

r.table('people').get(1) // Get Darth
  // Add a `family` property to Darth
  .merge(function (row) {
    return {
      // Map all the family member ids to their respective documents
      'family': row('family').map(function (id) {
        return r.table('people').get(id);
      })
    }
  })

The result of this query will be something this:

{
  "family": [
    {
      "id": 2 ,
      "name":  "Luke"
    } ,
    {
      "id": 3 ,
      "name":  "Leia"
    }
  ] ,
  "id": 1 ,
  "name":  "Darth"
}
2
On

Ended up with the below which will be much more performant than a map I believe. And it will use the default index on id

r.db('myDb')
    .table('tests')
    .get(1)
  .merge(function (person) {
    return {
      myFamily: r.db('myDb').table('tests').getAll(r.args(person('family'))).coerceTo('ARRAY')
    }
  })
  .pluck('name', 'myFamily');