0

My documents contain an array, for example;

{
    "a": [ 2, 3 ],
    "id":  ...
}

I want to return only the documents for which a contains only the elements 2 and 3.

This is the simplest I've found yet;

r.table("t").filter(r.row('a').difference([2,3]).eq([]))

Is there a better way?

Dagrada
  • 1,135
  • 12
  • 22

1 Answers1

1

A nice way to write the same function would be to use .isEmpty instead of .eq([]).

r.table("t")
 .filter(r.row('a').difference([2,3]).isEmpty())

This query is equivalent to the function you wrote.

That being said, your current query returns document where a has only 2 and/or 3. So, for example, a document with with a: [2] would get matched.

Example result set:

{
  "a": [ 2 ] ,
  "id":  "f60f0e43-a542-499f-9481-11372cc386c8"
} {
  "a": [ 2, 3 ] ,
  "id":  "c6ed9b4e-1399-47dd-a692-3db80df4143c"
}

That might be what you want, but if you only want documents where the a property is [2, 3] or [3, 2] exactly and contains no other elements, you might want to just use .eq:

r.table("t")
 .filter(r.row('a').eq([2,3]).or( r.row('a').eq([3, 2]) ))

Example result:

{
  "a": [ 2, 3 ] ,
  "id":  "c6ed9b4e-1399-47dd-a692-3db80df4143c"
}, {
  "a": [ 3, 2 ] ,
  "id":  "cb2b5fb6-7601-43b4-a0fd-4b6b8eb83438"
}
Jorge Silva
  • 4,574
  • 1
  • 23
  • 42
  • Hi Jorge. In this case the array would never have less than 2 elements, so I think it is the better solution as the .eq([2,3]) comparison requires the elements be ordered first. That said, I missed isEmpty() - thank you! – Dagrada Apr 19 '15 at 01:57
  • I updated my solution to match either `[2, 3]` or `[3, 2]` using just `eq`, so that the answer is more accurate. – Jorge Silva Apr 19 '15 at 02:36
  • Also, I took the time to answer your question and it seems I answered it correctly. I'd probably be best to mark it as answered :). Thanks! – Jorge Silva Apr 19 '15 at 02:37
  • The simple 'or' method makes the most sense. Sorry for the delay in marking your answer! I got side-tracked wondering whether a hash would be a better idea - http://stackoverflow.com/questions/29725106/hash-uuids-without-requiring-ordering – Dagrada Apr 19 '15 at 03:13
  • Thanks! The hash idea is interesting, but personally it seems better to have the data in your database be very clear unless it saves a significant amount of time. Or not? – Jorge Silva Apr 19 '15 at 03:24