jeudi 23 avril 2015

Finding a document in RethinkDB that meets multiple criteria

I want to create a wrapper function that accepts an array of requirements. This wrapper function will ask rethinkDB for any documents that meet all criteria. The values will be numerical and I want anything returned which has >= the asked for value.

The syntax supplied in the API is like this:

r.table("name").filter(
r.row("cond1").lt(val1).and(r.row("cond2").gt(val2))
).run(conn, callback);

But that doesn't allow me to query for an arbitrary amount of conditions.

Is there a feature that I am missing, or is the solution to: 1. build a string and eval it - or - 2. pass a function to the RethinkDB server with my array of requirements included ?

An example that might make more sense: I have a database of monster trucks. I want to allow someone to say "show me trucks with a power score of at least 5 and with a speed of at least 10". Here is a failed attempt at passing a function:

r.db('test').table('monstertrucks').filter(
function(item){
var fail = 0, 
    arr = [{attr: "speed", val: 5}, {attr: "power", val: 10}];
for(var i = 0; i < arr.length; i++){
  if(item(arr[i].attr).lt(arr[i].val)){fail++}
}
return fail ? false : true;
})

Aucun commentaire:

Enregistrer un commentaire