Slide 1

Slide 1 text

RethinkDB The database for the realtime web OpenWest Orem, Utah May 10, 2015

Slide 2

Slide 2 text

Jorge Silva @thejsj Developer Evangelist @ RethinkDB

Slide 3

Slide 3 text

Introduction What is RethinkDB?

Slide 4

Slide 4 text

What is RethinkDB? • Open source database for building realtime web applications • NoSQL database that stores schemaless JSON documents • Distributed database that is easy to scale

Slide 5

Slide 5 text

Built for Realtime Apps • Subscribe to change notifications from database queries • No more polling — the database pushes changes to your app • Reduce the amount of plumbing needed to stream live updates

Slide 6

Slide 6 text

RethinkDB Structure Database → Table → Document MySQL: Database → Table → Row MongoDB: Database → Collection → Document

Slide 7

Slide 7 text

Sample Document { "name": "Will Riker", "position": "Commander", "height": 193, "birthdate": Mon Aug 19 2335, "ships": [ { "name": "USS Pegasus" }, { "name": "USS Potemkin" }, { "name": "USS Enterprise" }, ], ... }

Slide 8

Slide 8 text

Introduction to ReQL RethinkDB Query Language

Slide 9

Slide 9 text

Introduction to ReQL • ReQL embeds natively into your programming language • Compose ReQL queries by chaining commands

Slide 10

Slide 10 text

Anatomy of a ReQL Query r.table("users") .pluck("last_name") .distinct().count() Number of unique last names

Slide 11

Slide 11 text

Anatomy of a ReQL Query r.table("users") .pluck("last_name") .distinct().count() Access a database table

Slide 12

Slide 12 text

Anatomy of a ReQL Query r.table("users") .pluck("last_name") .distinct().count() Isolate a document property

Slide 13

Slide 13 text

Anatomy of a ReQL Query r.table("users") .pluck("last_name") .distinct().count() Consolidate duplicate values

Slide 14

Slide 14 text

Anatomy of a ReQL Query r.table("users") .pluck("last_name") .distinct().count() Display the number of items

Slide 15

Slide 15 text

Sample ReQL Queries r.table("users") .filter(r.row("age").gt(30)) r.table(“posts") .eqJoin(“user”, r.table(“users”)) .zip() r.table("posts") .filter({status: "draft"}) .update({status: "published"})

Slide 16

Slide 16 text

ReQL Commands • Transformations: map, orderBy, skip, limit, slice • Aggregations: group, reduce, count, sum, avg, min, max, distinct, contains • Documents: row, pluck, without, merge, append, difference, keys, hasFields, spliceAt • Writing: insert, update, replace, delete • Control: forEach, range, branch, do, coerceTo, expr

Slide 17

Slide 17 text

Understanding ReQL • Client driver translates ReQL queries into wire protocol • In JS use e.g. the mul and gt commands instead of the normal operators

Slide 18

Slide 18 text

Additional ReQL Features • Geospatial indexing for location- based queries • Date and time functions for time data • Support for storing binary objects

Slide 19

Slide 19 text

Running Queries https://github.com/thejsj/rethinkdb-workshop

Slide 20

Slide 20 text

http://rethinkdb-chat.thejsj.com:10001/ Running Queries

Slide 21

Slide 21 text

Realtime Updates Working with Changefeeds

Slide 22

Slide 22 text

Subscribe to change notifications on database queries Changefeeds

Slide 23

Slide 23 text

r.table("users").changes() Track changes on the users table Changefeeds

Slide 24

Slide 24 text

Changefeeds • The changes command returns a cursor that receives updates • Each update includes the new and old value of the modified record

Slide 25

Slide 25 text

Changefeeds r.table("users").changes() r.table("users") .insert({name: "Bob"}) Changefeed output: { new_val: { id: '362ae837-2e29-4695-adef-4fa415138f90', name: 'Bob', ... }, old_val: null }

Slide 26

Slide 26 text

Changefeeds r.table("users").changes() r.table("users") .filter({name: "Bob"}).delete() Changefeed output: { new_val: null, old_val: { id: '362ae837-2e29-4695-adef-4fa415138f90', name: 'Bob', ... } }

Slide 27

Slide 27 text

Changefeeds r.table("users").changes() r.table("users") .get("362ae837-2e29-4695-adef-4fa415138f90") .update({name: "Bobbby"}) Changefeed output: { new_val: { id: '362ae837-2e29-4695-adef-4fa415138f90', name: 'Bobby' }, old_val: { id: '362ae837-2e29-4695-adef-4fa415138f90', name: 'Bob' } }

Slide 28

Slide 28 text

Changefeeds r.table("players") .orderBy({index: r.desc("score")}) .limit(3).changes() Track top three players by score Chain the changes command to an actual ReQL query:

Slide 29

Slide 29 text

Changefeeds r.table("table").get(ID).changes() r.table("table").getAll(ID).changes() r.table("table").between(X, Y).changes() r.table("table").filter(CONDITION).changes() r.table("table").union(ID).changes() r.table("table").map(FUNCTION).changes() r.table("table").min(INDEX).changes() r.table("table").max(INDEX).changes() r.table("table").orderBy(INDEX) .limit(N).changes() Commands that currently work with changefeeds:

Slide 30

Slide 30 text

Using Changefeeds

Slide 31

Slide 31 text

Building Web Apps Using RethinkDB in Node

Slide 32

Slide 32 text

Client Driver • Use a RethinkDB client driver to access the database in your app • Official drivers available for Ruby, Python, and JavaScript • Third-party drivers available for other languages like Go and Clojure

Slide 33

Slide 33 text

> Client Driver Install the JS client driver from NPM in your Node.js project: $ npm install rethinkdb --save

Slide 34

Slide 34 text

Client Driver var r = require("rethinkdb"); r.connect().then(function(conn) { return r.table("users") .insert({name: “Bob”}).run(conn) .finally(function () { conn.close(); }); }).then(function() { // Documented inserted }); Add Bob to the “users” table

Slide 35

Slide 35 text

Client Driver var r = require("rethinkdb"); r.connect().then(function(conn) { return r.table("users") .insert({name: “Bob"}).run(conn) .finally(function () { conn.close(); }); }).then(function(output) { console.log(output); }); Import the RethinkDB module

Slide 36

Slide 36 text

Client Driver var r = require("rethinkdb"); r.connect().then(function(conn) { return r.table("users") .insert({name: “Bob”}).run(conn) .finally(function () { conn.close(); }); }).then(function(output) { console.log(output); }); Connect to the database

Slide 37

Slide 37 text

Client Driver var r = require("rethinkdb"); r.connect().then(function(conn) { return r.table("users") .insert({name: “Bob”}).run(conn) .finally(function () { conn.close(); }); }).then(function(output) { console.log(output); }); ReQL query that inserts a record

Slide 38

Slide 38 text

Client Driver var r = require("rethinkdb"); r.connect().then(function(conn) { return r.table("users") .insert({name: “Bob”}).run(conn) .finally(function () { conn.close(); }); }).then(function(output) { console.log(output); }); Run the query on a connection

Slide 39

Slide 39 text

Client Driver var r = require("rethinkdb"); r.connect().then(function(conn) { return r.table("users") .insert({name: “Bob"}).run(conn) .finally(function () { conn.close(); }); }).then(function(output) { console.log(output); }); Display query response

Slide 40

Slide 40 text

Client Driver var r = require("rethinkdb"); r.connect().then(function(conn) { return r.table("users") .insert({name: “Bob"}).run(conn) .finally(function () { conn.close(); }); }).then(function(output) { console.log(output); }).error(function(err) { console.log("Failed:", err); }); Handle errors emitted by Promise

Slide 41

Slide 41 text

Using Changefeeds r.connect().then(function(conn) { return r.table("fellowship") .changes().run(conn); }) .then(function(cursor) { cursor.each(function(err, item) { console.log(item); }); }); Display every change on the “fellowship” table

Slide 42

Slide 42 text

Using Changefeeds Attach a changefeed to the table r.connect().then(function(conn) { return r.table("fellowship") .changes().run(conn); }) .then(function(cursor) { cursor.each(function(err, item) { console.log(item); }); });

Slide 43

Slide 43 text

Using Changefeeds Iterate over every value passed into the cursor r.connect().then(function(conn) { return r.table("fellowship") .changes().run(conn); }) .then(function(cursor) { cursor.each(function(err, item) { console.log(item); }); });

Slide 44

Slide 44 text

Using Changefeeds r.connect().then(function(conn) { return r.table("fellowship") .changes().run(conn); }) .then(function(cursor) { cursor.each(function(err, item) { console.log(item); }); }); Display received changes in the console

Slide 45

Slide 45 text

Using Socket.io • Powerful framework for realtime client/server communication • Supports WebSockets, long polling, and other transports • Lets you send JSON messages between your app and frontend

Slide 46

Slide 46 text

Socket.io (Server) var sockio = require("socket.io"); var app = require("express")(); var r = require("rethinkdb"); var io = sockio.listen(app.listen(8090)); r.connect().then(function(conn) { return r.table("players") .orderBy({index: r.desc("score")}) .limit(5).changes().run(conn); }) .then(function(cursor) { cursor.each(function(err, data) { io.sockets.emit("update", data); }); }); Broadcast score changes over Socket.io

Slide 47

Slide 47 text

Socket.io (Server) var sockio = require("socket.io"); var app = require("express")(); var r = require("rethinkdb"); var io = sockio.listen(app.listen(8090)); r.connect().then(function(conn) { return r.table("players") .orderBy({index: r.desc("score")}) .limit(5).changes().run(conn); }) .then(function(cursor) { cursor.each(function(err, data) { io.sockets.emit("update", data); }); }); Load the Socket.io module

Slide 48

Slide 48 text

Socket.io (Server) var sockio = require("socket.io"); var app = require("express")(); var r = require("rethinkdb"); var io = sockio.listen(app.listen(8090)); r.connect().then(function(conn) { return r.table("players") .orderBy({index: r.desc("score")}) .limit(5).changes().run(conn); }) .then(function(cursor) { cursor.each(function(err, data) { io.sockets.emit("update", data); }); }); Instantiate Socket.io server

Slide 49

Slide 49 text

Socket.io (Server) var sockio = require("socket.io"); var app = require("express")(); var r = require("rethinkdb"); var io = sockio.listen(app.listen(8090)); r.connect().then(function(conn) { return r.table("players") .orderBy({index: r.desc("score")}) .limit(5).changes().run(conn); }) .then(function(cursor) { cursor.each(function(err, data) { io.sockets.emit("update", data); }); }); Attach a changefeed to the query

Slide 50

Slide 50 text

Socket.io (Server) var sockio = require("socket.io"); var app = require("express")(); var r = require("rethinkdb"); var io = sockio.listen(app.listen(8090)); r.connect().then(function(conn) { return r.table("players") .orderBy({index: r.desc("score")}) .limit(5).changes().run(conn); }) .then(function(cursor) { cursor.each(function(err, data) { io.sockets.emit("update", data); }); }); Broadcast updates to all Socket.io connections

Slide 51

Slide 51 text

Socket.io (Client) Real-time web app var socket = io.connect(); socket.on("update", function(data) { console.log("Update:", data); }); Receive Socket.io updates on frontend

Slide 52

Slide 52 text

Socket.io (Client) Real-time web app var socket = io.connect(); socket.on("update", function(data) { console.log("Update:", data); }); Load the Socket.io client script

Slide 53

Slide 53 text

Socket.io (Client) Real-time web app var socket = io.connect(); socket.on("update", function(data) { console.log("Update:", data); }); Connect to the Socket.io server

Slide 54

Slide 54 text

Socket.io (Client) Real-time web app var socket = io.connect(); socket.on("update", function(data) { console.log("Update:", data); }); Create handler for “update” messages

Slide 55

Slide 55 text

Socket.io (Client) Real-time web app var socket = io.connect(); socket.on("update", function(data) { console.log("Update:", data); }); Display update in browser console

Slide 56

Slide 56 text

Tutorial: Building a chat app

Slide 57

Slide 57 text

#1: Clone the repository git clone [email protected]:thejsj/ rethinkdb-workshp.git or https://github.com/thejsj/rethinkdb- workshop/tarball/master

Slide 58

Slide 58 text

#2: Go to config/default.js 6QEBUFZPVS3FUIJOL%# EBUBCBTFDPOHVSBUJPO var config = { 'rethinkdb': { 'host': ‘rethinkdb-chat.thejsj.com’, 'port': 10002, 'db': ‘GITHUB_HANDLE_rethinkdb_workshop’ },

Slide 59

Slide 59 text

#3: Install Dependencies // Go to the project directory cd rethinkdb-workshop // Install dependencies npm install // Start server npm run dev // or `node server`

Slide 60

Slide 60 text

#4: Go to server/index.js -PPLGPSUIFDPNNFOUTJOPSEFS UPXSJUFUIFDPSSFDU3F2-RVFSJFT // Step 1 // Write a query…

Slide 61

Slide 61 text

Connections *OUIJTBQQ UIFrPCKFDUDPOUBJOT BDPOOFDUJPO r.table(‘messages’).run(r.conn);

Slide 62

Slide 62 text

#5: Switch database $POOFDUUPUIFGPMMPXJOH EBUBCBTF TPXFDBOBMMTIBSF NFTTBHFT var config = { 'rethinkdb': { 'host': ‘rethinkdb-chat.thejsj.com’, 'port': 10002, 'db': ‘main_rethinkdb_workshop’ },

Slide 63

Slide 63 text

Additional Resources • RethinkDB website:
 http://rethinkdb.com • RethinkDB cookbook:
 http://rethinkdb.com/docs/cookbook • RethinkDB installation:
 http://rethinkdb.com/docs/install/