RethinkDB WHERE clause examples

RethinkDB calls a WHERE clause “filter”, and you can write it in several forms.

One is the “equals” form:

r.db('performance')
 .table('query_timings')
 .filter({ 'Duration': 0 })

If you can actually use this form, you can put many filters in the one function call, although they are all equality comparisons, so they aren’t that useful:

r.db('performance')
 .table('query_timings')
 .filter({ 'Duration': 0, 'Day': 0 })

According to the documentation, you can use an index if you completely rewrite this form:

r.table("performance").index_create("Duration").run(conn)

r.table("users")
 .get_all("0", index="Duration")

The more useful form of a filter is to just write a function. However, beware that you have to use functions like “ne” for not equals (and eq, add, etc), as they aren’t able to send Javascript operators across.

r.db('performance')
 .table('query_timings')
 .filter(function(row) { return row('Duration').ne(null) })

Alternately, if you absolutely must use normal Javascript syntax, or are writing an Orm, you can pass the Javascript as a string, which is eval’ed on the server side. Comparing this with alternate implementations would be an interesting possibility here, to test the performance of various implementations of the same query.

r.db('performance')
 .table('query_timings')
  .filter(r.js('(function (row) { return row.Duration != null; })'))

They do offer one final shortcut method, which is to use “match”, which presumably returns a lamdba (note this uses the somewhat unexpected “r.row” syntax, so this is operating as some sort of static method):

r.db('performance')
 .table('query_timings').filter(
   r.row['Query'].match("^test.*")}
 )

This is likely better for performance than building you’re own regex in a function, as (hopefully) this is compiled prior to creating the lambda, rather than on each call to the function.

Leave a Reply

Your email address will not be published. Required fields are marked *