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 Changefeeds have been implemented within the RethinkDB API. It turns out that the syntax is extremely simple; in fact, you can enable Changefeeds by simply appending the changes command at the end of your query.

Let's clarify this with an example. If we want to read all documents from the fake_data table, we would normally run the following query:

r.table('fake_data').run(conn, function(err, cursor) {
    if (err) throw err;
    cursor.each(console.log);
});

This will print all the documents. If, however, we want to enable Changefeeds and be notified when the fake_data table is updated, we can edit the query as follows:

r.table('fake_data').changes().run(conn, function(err, cursor) {
    if (err) throw err;
    cursor.each(console.log);
});

Appending the changes command to the query will return a cursor as usual; however, the output of this cursor is infinite. Every time a change is made to the table, the cursor will receive the update.

A simple example using Changefeeds

Now that we know a little more about how Changefeeds work, let's put this into practice by writing a simple example. First, we will edit the example1.js script so that it inserts a new document into the database every second. We will then write a new script that listens for changes on the table.

The first thing to do is make a copy of the example1.js script and edit it so that a new random document is inserted every second. Our updated script will look as follows:

r.connect({host: 'localhost', port: 28015}, function(err, conn) {
    if (err) throw err;
    connection = conn;
    setInterval(insertData, 1000);
});

function insertData() {
    var randomName = faker.name.findName();
    var randomEmail = faker.internet.email();
    r.table("fake_data").insert({ name: randomName, email: randomEmail }).run(connection, function(err, data) {
        if (err) throw err;
    });
}

As you can see, we're using the setInterval function to set a timer that runs the insertData function every 1000 milliseconds, that is, every second. Now, save the script as example3.js. You can find the complete source code in the code folder that accompanies this book.

Now that we've got a script that continuously generates some data for us, we need to create a script that uses Changefeeds to receive notifications when updates occur.

Create a new file called example4.js and type the following code:

r.connect({host: 'localhost', port: 28015}, function(err, conn) {
    if (err) throw err;
    connection = conn;
    listenForUpdates()
});

function listenForUpdates() {
    r.table("fake_data").changes().run(connection, function(err, cursor) {
        if (err) throw err;
        cursor.each(function(err, item) {
            if (err) throw err;
            console.log("Added document with email", item.new_val.email);
        });
    });
}

Let's go over what happened in this script:

  • First, we connect to the database by creating a new connection to it
  • Then, we call the listenForUpdates function, which runs the query on the fake_data table, appending the changes command at the end of it
  • When the cursor receives a new document, we print the value of the e-mail field within the document

Although, this may seem rather complicated at the start, running the two scripts will definitely help you understand better how it all fits together.

First, run the example3.js script, which will keep generating new data for us:

node example3.js

Then, in a new terminal window, run the example4.js script:

node example4.js

If everything works correctly, you will see the e-mail addresses of the new documents appearing on the screen every second. The output will be similar to this:

$ node example4.js
Added document with email [email protected]
Added document with email [email protected]
Added document with email [email protected]
Added document with email [email protected]
Added document with email [email protected]

This simple example demonstrates the power of Changefeeds, which are at the heart of RethinkDB's real-time functionality; in fact, the example4.js script notifies us in realtime as the example3.js script generates new data and inserts it into the database.

In this section of the chapter, we've only just scratched the surface of Changefeeds' potential. In Chapter 7, Developing Real-Time Web Applications we will go in much more detail and you will learn how to develop a full-fledged, real-time web application powered by Changefeeds.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.189.250