Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Mastering RethinkDB
Mastering RethinkDB

Mastering RethinkDB: Master the skills of building real-time apps dramatically easier with open source, scalable database - RethinkDB

eBook
€8.99 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Mastering RethinkDB

Chapter 2. RethinkDB Query Language

ReQL means RethinkDB query language. It offers a powerful and easy way to perform operations on JSON documents. It is one of the most important parts of the RethinkDB architecture. It is built on three important principles: embedding ReQL in a programming language, ReQL queries being chainable, and ReQL queries being executed on the server.

Here is a list of topics we are going to cover, along with the mentioned principles:

  • Performing conditional queries
  • ReQL queries are chainable
  • ReQL queries are executed on a server
  • Traversing over nested fields
  • Performing string operations
  • Performing MapReduce operations
  • Calling HTTP APIs using ReQL
  • Handling binary objects
  • Performing JOINS
  • Accessing changefeed (real-time feed) in RethinkDB
  • Performing geolocation operations
  • Performing administrative operations

Let us look over each one of them.

Embedding ReQL in a programming language

RethinkDB provides client drivers for various programming languages. To explain, I am going to consider Node.js, and the steps are as follows:

  1. You can start the ReQL exploration journey by connecting to the database.
  2. Install the RethinkDB client module and make sure you have the RethinkDB server ready and running, listening to the default port.
  3. Make sure you have done npm install rethinkdb before running the following code:
          var rethinkdb = require('rethinkdb'); 
          var connection = null; 
          rethinkdb.connect({host : 'localhost', port :
                             28015},function(err,conn) { 
          if(err) {  
          throw new Error('Connection error');  
           } else { 
          connection = conn; 
           } 
           }); 
    

The preceding simple code snippet written in Node.js is importing the rethinkdb module and connecting to the RethinkDB server on the default port. It returns the callback function with error and the...

ReQL queries are chainable

Almost all ReQL queries are chainable. You can chain ReQL queries using the dot operator, just like you do with pipe in Unix. Data flows from left to right and data from one command is passed to the next one until the query gets executed. You can chain queries until your query is done.

Just like we performed some queries on the previous section, we chained the get() function with update() or delete() to perform the query.

Here is an example:

rethinkdb.table('users').delete(); 
rethinkdb.table('users').get('<<id>>').update({id : 10}); 
rethinkdb.db('test').table('users').distinct().count(); 

This way of design provides a natural way of reading and understanding queries. It's easy to learn, modify, and read.

ReQL queries are executed on a server

Queries are formed in the client but will be sent to server for execution when you run them. This makes sure there is no network round trip and bandwidth allocation. This provides efficiency in query execution.

We also mentioned in Chapter 1, The RethinkDB Architecture and Data Model, that RethinkDB executes queries in a lazy manner. It only fetches the data asked and required for the query to complete. Here is an example:

r.db('test').table('users').limit(5) 

To perform this query, RethinkDB will look for only the five documents only in the users table. It will perform enough operations to perform the data collection requested in the query. This avoids extra computation costs and CPU cycles.

To provide the highest level of efficiency, RethinkDB automatically parallelizes the query as much as possible across the server, CPU cores, or even data centers. RethinkDB automatically processes the complex queries into stages, parallelizes them...

Performing conditional queries

ReQL supports conditional queries using subqueries, expressions, and the lambda function. In this section, we will look at each one of them using sample code written in Node.js.

In order to perform these queries, I have populated our users table in the test database with some documents. Here is the query executed from the RethinkDB web administrative screen:

r.db('test').table('users').insert([{ 
name : "John", 
age : 24 
}, { 
name : "Mary", 
age : 32 
},{ 
name : "Michael", 
age : 28 
}]) 

Note

In the web administrative screen, you do not need to provide the run function with a connection; it automatically appends and executes the query on the server.

Let us run a query to find out documents with an age greater than 30 years. We are going to execute the following code after getting a connection to the database, the same as we did in the former section:

rethinkdb.table('users').filter(function (user...

Embedding ReQL in a programming language


RethinkDB provides client drivers for various programming languages. To explain, I am going to consider Node.js, and the steps are as follows:

  1. You can start the ReQL exploration journey by connecting to the database.

  2. Install the RethinkDB client module and make sure you have the RethinkDB server ready and running, listening to the default port.

  3. Make sure you have done npm install rethinkdb before running the following code:

          var rethinkdb = require('rethinkdb'); 
          var connection = null; 
          rethinkdb.connect({host : 'localhost', port :
                             28015},function(err,conn) { 
          if(err) {  
          throw new Error('Connection error');  
           } else { 
          connection = conn; 
           } 
           }); 
    

The preceding simple code snippet written in Node.js is importing the rethinkdb module and connecting to the RethinkDB server on the default port. It returns the callback function...

ReQL queries are chainable


Almost all ReQL queries are chainable. You can chain ReQL queries using the dot operator, just like you do with pipe in Unix. Data flows from left to right and data from one command is passed to the next one until the query gets executed. You can chain queries until your query is done.

Just like we performed some queries on the previous section, we chained the get() function with update() or delete() to perform the query.

Here is an example:

rethinkdb.table('users').delete(); 
rethinkdb.table('users').get('<<id>>').update({id : 10}); 
rethinkdb.db('test').table('users').distinct().count(); 

This way of design provides a natural way of reading and understanding queries. It's easy to learn, modify, and read.

ReQL queries are executed on a server


Queries are formed in the client but will be sent to server for execution when you run them. This makes sure there is no network round trip and bandwidth allocation. This provides efficiency in query execution.

We also mentioned in Chapter 1, The RethinkDB Architecture and Data Model, that RethinkDB executes queries in a lazy manner. It only fetches the data asked and required for the query to complete. Here is an example:

r.db('test').table('users').limit(5) 

To perform this query, RethinkDB will look for only the five documents only in the users table. It will perform enough operations to perform the data collection requested in the query. This avoids extra computation costs and CPU cycles.

To provide the highest level of efficiency, RethinkDB automatically parallelizes the query as much as possible across the server, CPU cores, or even data centers. RethinkDB automatically processes the complex queries into stages, parallelizes them across clusters...

Performing conditional queries


ReQL supports conditional queries using subqueries, expressions, and the lambda function. In this section, we will look at each one of them using sample code written in Node.js.

In order to perform these queries, I have populated our users table in the test database with some documents. Here is the query executed from the RethinkDB web administrative screen:

r.db('test').table('users').insert([{ 
name : "John", 
age : 24 
}, { 
name : "Mary", 
age : 32 
},{ 
name : "Michael", 
age : 28 
}]) 

Note

In the web administrative screen, you do not need to provide the run function with a connection; it automatically appends and executes the query on the server.

Let us run a query to find out documents with an age greater than 30 years. We are going to execute the following code after getting a connection to the database, the same as we did in the former section:

rethinkdb.table('users').filter(function (user) {  
return...

Performing string operations


ReQL provides the following functions to manipulate and search strings:

  • Match() takes a string or a regular expression as an input and performs a search over the field. If it matches, it returns the data in the cursor, which we can loop over to retrieve the actual data.

  • For example, we have to find all the users whose name starts with J. Here is the query for the same:

      rethinkdb.table("users").filter(function(user) { 
      return user("name").match("^J"); 
      }).run(connection,function(err,cursor) { 
      if(err) { 
      throw new Error(err); 
        } 
       cursor.toArray(function(err,data) { 
       console.log(data); 
        }); 
      }); 
  • Here we are first performing a filter, and inside it, we put our match() condition. The filter gives every document to the match() function and it appends it to the cursor. Upon running, you should be able to view the users with names starting with J.

  • split...

Performing MapReduce operations


MapReduce is the programming model to perform operations (mainly aggregation) on distributed sets of data across various clusters in different servers. This concept was coined by Google and was used in the Google file system initially and later was adopted by the open source Hadoop project.

MapReduce works by processing the data on each server and then combine it together to form a result set. It actually divides into two operations namely Map and Reduce.

  • Map: This performs the transformation of the elements in the group or individual sequence

  • Reduce: This performs the aggregation and combines the results from Map into a meaningful result set

In RethinkDB, MapReduce queries operate in three steps as follows:

  • Group operation: To process the data into groups. This step is optional

  • Map operation: To transform the data or group of data into a sequence

  • Reduce operation: To aggregate the sequence data to form a resultset

So mainly it is a Group MapReduce (GMR) operation...

Calling HTTP APIs using ReQL


RethinkDB provides support to call an external API that returns data in a JSON object, which most of the large API provider do. You can call HTTP API directly from your database hence no need of writing piece of code to just call an API and then dump into database. RethinkDB also handles it asynchronously so performance won't be affected if the API takes a longer time.

Let us try one basic API call before moving ahead with storing those in our table. We all know and use OMDb for movies review. There is a website called http://omdbapi.com/ that provides APIs to find out the movie information present in the OMDB database. Let's call one with the following code to fetch information about the Avengers movie and see how it goes:

rethinkdb.http("http://www.omdbapi.com/?t=avengers&y=2015&plot=short&r=json").run(connection,function(err,data) { 
if(err) { 
throw new Error(err); 
  } 
console.log(data); 
}); 

You should be receiving...

Handling binary objects


As we have mentioned in this chapter about RethinkDB binary object support, let's look over how to use it using ReQL. The syntax to store binary objects differs from client to client. In Node.js it uses buffers to convert the stream into binary and we can use RethinkDB to insert that in a table.

Let us take an example from the preceding document. There is a key called Poster, which is the official poster of the movie in a JPEG image format. We can store the image directly in RethinkDB in a binary format.

Consider the following code:

rethinkdb.http("http://www.omdbapi.com/?t=avengers&y=2015&plot=short&r=json").run(connection,function(err,data) { 
if(err) { 
throw new Error(err); 
  } 
rethinkdb.table("movies").insert({ 
movieName :data.Title, 
posterImage :rethinkdb.http(data.Poster, {resultFormat : 'binary'}) 
  }).run(connection,function(err,data) { 
if(err) { 
throw new Error(err); 
    } 
console.log...

Performing JOINS


JOINS are one of the features of NoSQL databases. RethinkDB provides the ReQL functions to perform various types of JOINS, such as inner, outer, and so on. Please refer to Chapter 1, The RethinkDB Architecture and Data Model, to study this more in detail.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Master the powerful ReQL queries to manipulate your JSON data,
  • Learn how to develop scalable, real-time web applications using RethinkDB and Node.js and deploy them for production,
  • A detailed, step-by-step guide to help you master the concepts of RethinkDB programming with ease

Description

RethinkDB has a lot of cool things to be excited about: ReQL (its readable,highly-functional syntax), cluster management, primitives for 21st century applications, and change-feeds. This book starts with a brief overview of the RethinkDB architecture and data modeling, and coverage of the advanced ReQL queries to work with JSON documents. Then, you will quickly jump to implementing these concepts in real-world scenarios, by building real-time applications on polling, data synchronization, share market, and the geospatial domain using RethinkDB and Node.js. You will also see how to tweak RethinkDB's capabilities to ensure faster data processing by exploring the sharding and replication techniques in depth. Then, we will take you through the more advanced administration tasks as well as show you the various deployment techniques using PaaS, Docker, and Compose. By the time you have finished reading this book, you would have taken your knowledge of RethinkDB to the next level, and will be able to use the concepts in RethinkDB to develop efficient, real-time applications with ease.

Who is this book for?

This book caters to all the real-time application developers looking forward to master their skills using RethinkDB. A basic understanding of RethinkDB and Node.js is essential to get the most out of this book.

What you will learn

  • Master the web-based management console for data-center configuration (sharding, replication, and more), database monitoring, and testing queries.
  • Run queries using the ReQL language
  • Perform Geospatial queries (such as finding all the documents with locations within 5km of a given point).
  • Deal with time series data, especially across various times zones.
  • Extending the functionality of RethinkDB and integrate it with third party libraries such as ElasticSearch to enhance our search

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 16, 2016
Length: 330 pages
Edition : 1st
Language : English
ISBN-13 : 9781786468628
Category :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Dec 16, 2016
Length: 330 pages
Edition : 1st
Language : English
ISBN-13 : 9781786468628
Category :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 103.97
Getting Started with RethinkDB
€29.99
Mastering RethinkDB
€36.99
Apache Spark for Data Science Cookbook
€36.99
Total 103.97 Stars icon
Banner background image

Table of Contents

10 Chapters
1. The RethinkDB Architecture and Data Model Chevron down icon Chevron up icon
2. RethinkDB Query Language Chevron down icon Chevron up icon
3. Data Exploration Using RethinkDB Chevron down icon Chevron up icon
4. Performance Tuning in RethinkDB Chevron down icon Chevron up icon
5. Administration and Troubleshooting Tasks in RethinkDB Chevron down icon Chevron up icon
6. RethinkDB Deployment Chevron down icon Chevron up icon
7. Extending RethinkDB Chevron down icon Chevron up icon
8. Full Stack Development with RethinkDB Chevron down icon Chevron up icon
9. Polyglot Persistence Using RethinkDB Chevron down icon Chevron up icon
10. Using RethinkDB and Horizon Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
(1 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 100%
Rudi Mar 02, 2017
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
Very bad book. Seems like the author has no clue what he is writing about. Code examples very bad not readable and full of errors. Code will never run when you type it. This book is not worth the money.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.