Getting to Know ReQL

RethinkDB uses a special syntax call ReQL to interact with the data. ReQL is chainable. You start with a database, chain to table, and chain to other API to get what you want, in a way very natural. Type this into data explorer:

1 r.db("foodb").table('flavors').filter({'flavor_group': 'fruity'})

You should see some interesting data now.

Result of filter command by flavor_group
Result of filter command by flavor_group

Don’t worry about the syntax, just look at it again and even without any knowledge you know what it does and easily remember it. A way, for me, to understand ReQL is that every command return an object which share some API which we can call those API as if method of an object.

ReQL is particular binding to your language. Though, of course, they will look familiar between different language to maintain consitent look and feel. But, they are different. Those querie are constructed by making function call of your language, not by concat SQL String, or not by special JSON object like MongoDB. Therefore, it feel very natualy to write ReQL, as if the data we manipulate is an object or data type in our language. But everything comes with a trade off. On the downside, we have to accept differences of ReQL betweens many language. No matter how hard we try, different language has different syntax, especially when it comes to anonymous function.

What is r? r is like a special namespace which is all RethinkDB is exposed via it. It’s just a normal variable in your language, or a namespace, a package name, a module. Think of r like $ of jQuery. If you don’t like r, assign another variable to it is possible.

We will call all method of r, or of any method of return resulted from other method are command for now. Think of it like a method in jQuery world.

Here is example, with this HTML structure:

1 <div class="db">
2   <div class="table" data-type="anime">Haru River</div>
3   <div class="table" data-type="anime">Bakasara</div>
4   <div class="table" data-type="movie">James Bond</div>
5 </div>

To filter only anime movie, we can use this jQuery:

1 $('.db').find('.table').filter('[data-type="anime"]')

If we have a database call db, and a table call table, with 3 records:

1 {type: 'anime', title: 'Haru River'}
2 {type: 'anime', title: 'Bakasara'}
3 {type: 'movie', title: 'James Bond'}

The equavilent ReQL use to find only anime is:

1 r.db('db').table('table').filter({type: 'anime'})

Notice how similar the structure between them? Because of those concept, I find ReQL is easy to learn. If you can write jQuery, you can write ReQL.

Another way to understand is considering ReQL like the pipe on Linux, you select the data, passing into another command:

1 $ cd db; ls -la table/* | grep 'type: anime'