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 Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

Shipping Methods
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
Estimated delivery fee Deliver to Austria

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

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 : 9781786461070
Category :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Austria

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Publication date : Dec 16, 2016
Length: 330 pages
Edition : 1st
Language : English
ISBN-13 : 9781786461070
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

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela