Computing Absolute Values in RethinkDB

It took me a bit to figure out how to do absolute values in RethinkDB, because you can’t use conditionals and mathematical operations that you might normally expect.

I expect that abs will be added to the language relatively soon, based on the outstanding tickets, but if you need it now, here is how to implement it:

  'aDelta': 
     r.branch(
        row('Delta').gt(0), 
        row('Delta'), 
        row('Delta').mul(0)
  ),

The following query is more complete if you want to see an example in action – this computes root-mean-square variance as well (unfortunately there does not appear to be a power function in the language as yet, so you can’t do the square root at the end that you’d want)

r.database('performance')
 .table('query_timings)
 .map(function(row) {
       return {
         'Delta': row('Delta'),
         'aDelta': 
            r.branch(
              row('Delta').gt(0), 
              row('Delta'), 
              row('Delta').mul(0)
           ),
         'rmsDelta': row('Delta').mul(row('Delta')),
         'Count': 1
       }
     })
    .group('Count')
    .reduce(function(left, right) {
      var Delta = left('Delta').add(right('Delta'));
      var aDelta = left('aDelta').add(right('aDelta'));
      var rmsDelta = left('rmsDelta').add(right('rmsDelta'));
      var Count = left('Count').add(right('Count'));    
  
      return {
        Delta: Delta,
        Count: Count,
        aDelta: aDelta,
        rmsDelta: rmsDelta,
        Variance: rmsDelta.exp(0.5),
        Avg: Delta.div(Count)
      }
    })

Leave a Reply

Your email address will not be published.