Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join tables with a array of IDs

Attempting to use this example to join on an array of IDs: https://github.com/rethinkdb/rethinkdb/issues/1533#issuecomment-26112118

Stores table snippet

{ 
  "storeID": "80362c86-94cc-4be3-b2b0-2607901804dd",
  "locations": [
    "5fa96762-f0a9-41f2-a6c1-1335185f193d",
    "80362c86-94cc-4be3-b2b0-2607901804dd"
  ]
}

Locations table snippet

{
  "lat": 125.231345,
  "lng": 44.23123,
  "id": "80362c86-94cc-4be3-b2b0-2607901804dd"
}

I'd like to select the stores and join their store locations.

Original example from ReThinkDB contributor:

r.table("blog_posts")
.concat_map(lambda x: x["comment_ids"].map(lambda y: x.merge("comment_id" : y)))
.eq_join("comment_id", r.table("comments"))

My attempt to convert to JS

r.table("stores")
 .concatMap((function(x){ 
   return x("locations").map((function(y){ 
     return x("locations").add(y);
   })) 
}))
.eqJoin("locations", r.table("locations"))

Result

RqlRuntimeError: Expected type ARRAY but found STRING

like image 385
Dustin Brownell Avatar asked Jan 03 '14 17:01

Dustin Brownell


1 Answers

You're using concatMap incorrectly, here's what you want the first part of your query to be.

r.table("stores")
 .concatMap(function (x) {
   return x("locations");
 })

Try running that, it should give you:

["5fa96762-...", "80362c86-...", ...]

Now we need to join this to the other table. To join an array of ids to a table you can use eqjoin like so:

array.eqJoin(function (row) { return row; }, table)

There's more details here: rql get multple documents from list of keys rethinkdb in javascript.

Putting it all together we get:

r.table("stores")
 .concatMap(function (x) {
   return x("locations")
 })
 .eqJoin(function (i) { return i; }, r.table("locations"))

To get back the documents from the stores:

r.table("stores")
 .concatMap(function (x) {
   return x("locations").map(function (loc) {
      return x.merge({locations: loc});
   });
 })
 .eqJoin("locations", r.table("locations"))
like image 80
Joe Doliner Avatar answered Sep 28 '22 05:09

Joe Doliner