Count both sides of a partition in ReQL

31 views Asked by At

I have a dataset which has a boolean attribute, like:

{
  name: 'Steven',
  isQualified: true
}

And I want to count both sides of a partition. That is, how many documents are qualified or not. What's the best way to do this with a single rethinkdb query?

Here's an example with underscore.js, but it relies on querying all the documents and processing them in my app:

results = _.partition(data, 'isQualified').map(_.iteratee('length'))

At the moment I have this, but it feels inefficient and I'm assuming/hoping there's a better way to do it.

r.expr({
  'qualified': r.table('Candidate').filter({isQualified: true}).count(),
  'unqualified': r.table('Candidate').filter({isQualified: false}).count()
})

How could I improve this and make it more DRY?

1

There are 1 answers

0
neumino On

Create an index on isQualified

r.table('Candidate').indexCreate("isQualified");

Then use it to count

r.expr({
  'qualified': r.table('Candidate').getAll(true, {index: "isQualified"}).count()
  'unqualified': r.table('Candidate').getAll(false, {index: "isQualified"}).count(),
})

This is way faster as the server doesn't have to iterate through all the documents, but just has to traverse a B-tree.