Reader small image

You're reading from  Getting Started with RethinkDB

Product typeBook
Published inMar 2016
Reading LevelIntermediate
PublisherPackt
ISBN-139781785887604
Edition1st Edition
Languages
Right arrow
Author (1)
Gianluca Tiepolo
Gianluca Tiepolo
author image
Gianluca Tiepolo

Gianluca Tiepolo is a cybersecurity researcher who specializes in mobile forensics and incident response. He holds a BSc degree in Computer Science and an MSc in Information Security, as well as several security-related certifications. Over the past 12 years, he has performed security monitoring, threat hunting, incident response, and intelligence analysis as a consultant for dozens of organizations, including several Fortune 100 companies. Gianluca is also the co-founder of the startup Sixth Sense Solutions, which developed AI-based anti-fraud solutions. Today, Gianluca works as a Security Delivery Team Lead for consulting firm Accenture Security. In 2016, he authored the book Getting Started with RethinkDB, published by Packt Publishing.
Read more about Gianluca Tiepolo

Right arrow

Chapter 5. Programming RethinkDB in Node.js

In the previous chapters, you learned to interact with RethinkDB by running queries through the web interface; however, while this can be useful for testing purposes, it's not very efficient when using the database for production purposes.

If you're working on a web application, you typically want to incorporate the database programming within your application logic usually on the backend. This is one of the reasons why databases offer drivers, which are modules that allow you to access the database from your favorite programming language. Probably, the two most common languages used for backend programming are Python and Node.js, and you'll be happy to know that RethinkDB provides official drivers for both these languages.

In this chapter, we will focus on Node.js and understand how to interface it with RethinkDB.

In this chapter, you will also learn the following:

  • How Node.js works and why it's so popular

  • How to install RethinkDB's Node.js driver...

Introducing Node.js


This chapter focuses on using Node.js to interact with RethinkDB; however, although you may have used JavaScript before, you maybe interested in knowing a little more about how this new technology works.

First of all, Node.js is a software framework built upon Chrome's JavaScript runtime (called V8) that can be used to develop fast and scalable web applications. Node is provided as a full-fledged platform as it offers a high-performance web development framework that can be programmed in JavaScript.

You may have noticed the presence of two keywords in the previous paragraph: scalable and high-performance. The reason for this is that since the very beginning, Node.js has focused on the performance, and this has been possible due to the way that Node is designed. In fact, what sets Node.js apart from traditional web servers and applications is its event-driven, non-blocking I/O model that makes it lightweight and efficient and perfectly suited for real-time applications that...

Installing Node.js


The first thing we need to do to start developing web applications is to install Node.js, if you haven't done so already. Due to its enormous popularity, Node.js is available on practically any operating system. In this chapter, however, we will focus on installing it on Linux and OS X as these are the only officially supported platforms by RethinkDB.

For further information on Node.js and the platforms it supports, you can visit its website at https://nodejs.org/en/ where you will find package installers for your operating system and links to Node's GitHub repository if you prefer compiling the source code.

Installing on Linux

If you are running a Linux-based operating system, in most cases, you should be able to install Node.js using your distribution's package manager.

For example, if you're running the latest LTS version of Ubuntu Linux, you can install Node.js by running the following commands from the terminal:

curl -sL https://deb.nodesource.com/setup_4.x | sudo -E...

Running Node.js


Now that Node is installed and configured, we're ready to start using it. However, before trying this, let's just verify that Node is installed correctly by printing its version number.

This book assumes that you're using the latest stable version of Node.js. If you have installed a different version, for example, by building from the latest unstable source code, then the examples in this chapter might not work. From the command line, you can run the following command to see which version you have installed on your system:

node --version

If the command is successful, the output will be Node's version number.

Note

At the time of writing this book, the latest stable release was Node v4.2.2.

Node provides a JavaScript runtime environment that can be accessed at any time by running the node command from your command-line or terminal window. This feature is called the CLI (command-line interface), and it allows you to experiment with Node. For the purpose of this book, you will be...

Installing the RethinkDB module


Usually, platforms such as Node.js are simple and minimal by design; this is why most of these platforms have some sort of system that allows you to download, install, and manage third-party extension packages called modules. For example, in Python, you have pip or easy install. In Node, you have NPM—the Node Package Manager.

NPM is both a package manager to install and remove modules from the system and a standard to define dependencies on other packages. It also provides a public registry service that contains all the Node.js modules that developers want to publish through NPM.

The RethinkDB module is also hosted on NPM, and we will use Node's package manager to install it.

Before attempting to install the module, you should check to see if NPM is installed on your system. If you have installed Node.js by following the instructions in the previous section of this chapter, you will already have NPM installed on your machine. If, however, you have installed Node...

Connecting to RethinkDB


Now that we have everything installed, it's time to start interacting with RethinkDB through Node.js. In the following examples, we'll be adding some fake data to a table in our RethinkDB cluster. We'll be running these commands on a server running Ubuntu Linux.

To start, let's look at how to connect to our RethinkDB instance. First, make sure that your database is up and running. If it's not running, you can start RethinkDB by executing the following command from a terminal window:

sudo /etc/init.d/rethinkdb start

This will start the database. Now, let's have a look at the code used to connect to our instance:

r.connect({host: 'localhost', port: 28015 }, function(err, conn) {
    //
});

As you can see, the RethinkDB module provides us with a connect function, which creates a new connection to the database. This function accepts a few parameters, such as the server host and port. Optionally, you can also specify the name of the database and an authentication key (more...

Inserting documents


In this example, we're going to look at how to insert some data into our newly created table. As you may remember from Chapter 2, The ReQL Query Language you can add data to a table using the insert command. Adding data from a RethinkDB script follows exactly the same syntax.

As an example, a query that inserts the name of a person into the database looks as follows:

r.table("posts").insert({ name: "Matt" }).run(conn, callback);

It's now time to write our first full-fledged Node.js script. We're going to write a script that inserts some random data generated by a Node.js module. In particular, we're going to insert data about people: a name and an e-mail address.

To generate this sample data, we are going to use a module called faker. The first step is to install this module using the NPM package manager. You can do so by running the following command from a terminal window:

sudo npm install faker

We are now going to write a script that generates 100 random names and e-mail...

Reading documents


If you've been following along with the previous examples, your database will now have a table called fake_data that contains 100 documents. Now that we've got some data in our database, let's see how we can read data from RethinkDB from a Node.js script.

We've already seen how RethinkDB provides us with the filter command to read data from the database based on a condition. In the previous chapters, you learned to use this command in the web interface to perform read queries on our datasets.

However, sometimes you may want to read all the data from a table without any filtering. To do this, you just need to select the table from which you want to read, and RethinkDB will give you a cursor to access the data. You can then use the cursor to create an array that includes all the results.

This example reads and prints all the documents from the fake_data table:

r.table("fake_data").run(conn, function(err, cursor) {
    if (err) throw err;
    cursor.toArray(function(err, results...

Updating and deleting documents


Now that you've inserted a few documents into your RethinkDB table, you'll probably be wondering how to update or delete these documents using Node.js.

You'll be happy to know that the queries for updating and removing are exactly the same as the ones you learned in Chapter 2, The ReQL Query Language and used in the web interface. Let's go over them very briefly.

RethinkDB provides us with the update command to update the existing documents. This command accepts as input a JSON document with the required changes. As an example, suppose we want to add a gender field to all documents in the fake_data table. We can do so with the following lines of code:

r.table('fake_data').update({gender: "male"}).run(conn, function(err, result) {
    if (err) throw err;
    console.log(result);
});

As you can see, the query syntax is exactly the same as running it from the web interface. The only difference is appending the run command at the end of the query.

Now, let's take look...

Introducing Changefeeds


Over the past chapters, we've looked at a variety of different features that RethinkDB offers; we've seen how RethinkDB provides us with a rich API and how to use the API from Node.js. There is, however, one feature that we must talk about is Changefeeds.

Changefeeds allow you to run a query and subscribe to it so that when changes occur to it, your program gets notified about them. You maybe wondering why this is such a revolutionary feature. The reason is that traditionally, a client, in our case, a Node.js script, must continuously query the database to detect changes. This can result in the database becoming slow and your application risks becoming unresponsive. Changefeeds, on the contrary, allow RethinkDB to push updates directly to the client when changes occur. Why is this so useful? For starters, we can use Changefeeds to subscribe to a table and be notified when a value changes or when a document is added or removed from the table.

You maybe wondering how...

Summary


In this chapter, you learned all about Node.js and how to use this innovative platform to interact with RethinkDB. First, we looked at how to install Node and its package manager, then you learned how to install RethinkDB's Node.js module and how to use it. Finally, we introduced the concept of Changefeeds and developed a simple example that puts these concepts in practice.

In the following chapter, you will learn all about RethinkDB administration tasks, such as backups and security.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Getting Started with RethinkDB
Published in: Mar 2016Publisher: PacktISBN-13: 9781785887604
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Gianluca Tiepolo

Gianluca Tiepolo is a cybersecurity researcher who specializes in mobile forensics and incident response. He holds a BSc degree in Computer Science and an MSc in Information Security, as well as several security-related certifications. Over the past 12 years, he has performed security monitoring, threat hunting, incident response, and intelligence analysis as a consultant for dozens of organizations, including several Fortune 100 companies. Gianluca is also the co-founder of the startup Sixth Sense Solutions, which developed AI-based anti-fraud solutions. Today, Gianluca works as a Security Delivery Team Lead for consulting firm Accenture Security. In 2016, he authored the book Getting Started with RethinkDB, published by Packt Publishing.
Read more about Gianluca Tiepolo