Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
RethinkDB @ Sydney Node Ninjas
Search
Josh Hunt
August 06, 2015
Programming
2
140
RethinkDB @ Sydney Node Ninjas
Josh Hunt
August 06, 2015
Tweet
Share
More Decks by Josh Hunt
See All by Josh Hunt
Using Webpack At Scale
joshhunt
2
760
Other Decks in Programming
See All in Programming
自動で //nolint を挿入する取り組み / Gopher's Gathering
utgwkk
1
150
Beyond ORM
77web
11
1.6k
[JAWS-UG横浜 #79] re:Invent 2024 の DB アップデートは Multi-Region!
maroon1st
0
120
2024年のkintone API振り返りと2025年 / kintone API look back in 2024
tasshi
0
160
ChatGPT とつくる PHP で OS 実装
memory1994
PRO
3
190
PHPで作るWebSocketサーバー ~リアクティブなアプリケーションを知るために~ / WebSocket Server in PHP - To know reactive applications
seike460
PRO
2
800
Lookerは可視化だけじゃない。UIコンポーネントもあるんだ!
ymd65536
1
130
functionalなアプローチで動的要素を排除する
ryopeko
1
750
ある日突然あなたが管理しているサーバーにDDoSが来たらどうなるでしょう?知ってるようで何も知らなかったDDoS攻撃と対策 #phpcon.2024
akase244
2
7.8k
盆栽転じて家具となる / Bonsai and Furnitures
aereal
0
2.1k
社内フレームワークとその依存性解決 / in-house framework and its dependency management
vvakame
1
430
[Fin-JAWS 第38回 ~re:Invent 2024 金融re:Cap~]FaultInjectionServiceアップデート@pre:Invent2024
shintaro_fukatsu
0
310
Featured
See All Featured
The MySQL Ecosystem @ GitHub 2015
samlambert
250
12k
Speed Design
sergeychernyshev
25
750
How GitHub (no longer) Works
holman
312
140k
Git: the NoSQL Database
bkeepers
PRO
427
64k
4 Signs Your Business is Dying
shpigford
182
22k
Code Reviewing Like a Champion
maltzj
521
39k
Rebuilding a faster, lazier Slack
samanthasiow
79
8.8k
Fight the Zombie Pattern Library - RWD Summit 2016
marcelosomers
232
17k
Into the Great Unknown - MozCon
thekraken
34
1.6k
Adopting Sorbet at Scale
ufuk
74
9.2k
Large-scale JavaScript Application Architecture
addyosmani
510
110k
Refactoring Trust on Your Teams (GOTO; Chicago 2020)
rmw
33
2.7k
Transcript
RethinkDB Josh Hunt Developer @ Mi9
What is RethinkDB?
RethinkDB is… Open Source Database for the realtime web Schemaless
‘JSON’ document store Easy to develop, easy to deploy
RethinkDB is MongoDB that doesn't suck
Realtime Changefeeds Subscribe to any query and receive notification when
data changes No need to poll for updates Eliminates infra and plumbing code
Easy development Modern, native query language in Javascript/Python/Ruby/Go/whatever Query features
like join, map, reduce Web UI for testing queries (with docs!)
Easy deployment Scale with web UI for hassle-free sharding and
replication Hosted options with Compose.io Support contracts available
Demo
Rethink(ing) Queries
ReQL 101 Native to your programming language by chaining functions
Secure - injection attacks are minimised Queries are executed AND distributed by the server
Sample queries r.table('shows') .get('e346caa5...') r.table('actors') .pluck('lastName') .distinct().count()
More sample queries r.table('actors') .filter(r.row('age').gt(20)) r.table('characters') .filter({species: 'hobbit'}) .update({species: 'halfling'})
Demo
(Secondary) Indexes Indexes makes queries faster RethinkDB has auto GUID
primary index Can have multiple secondary indexes, using any field, or multiple fields with compound indexes
Compound indexes r.table('cast').indexCreate('fullName', [r.row('firstName'), r.row('lastName')] )
Compound indexes r.table('cast').indexCreate('fullName', [r.row('firstName'), r.row('lastName')] ) r.table('cast').getAll( ['Josh', 'Hunt'], {index:
'fullName'} )
More ReQL Store (sub)queries into variables Location aware: query on
geospatial data Accessing external APIs
Store subexpressions in variables to reuse or for subqueries expired
= r.row('expiryDate').lt(r.row()) r.table('episodes') .filter(expired) .delete()
Store subexpressions in variables to remove boilerplate // models/Shows.js module.exports
= r.table('shows') // routes/shows.js Shows = require('../models/Shows') Shows.get(req.params.showId)
Adding geospatial data r.table('cities').insert([ {name: 'Sydney', location: r.point(-33.865, 151.209)}, {name:
'Melbourne', location: r.point(-37.813, 144.963)} ])
Querying geospatial data home = r.point(-33.42, 149.57) r.table('cities') .getNearest(home, {index:
'location'}) r.table('cities') .get(1)('location') .distance(r.table(‘cities').get(2)('location'))
Accessing external APIs r.http('https://api.github.com/repos/joshhunt/uber') r.table('repos') .insert( r.http('https://api.github.com/repos/joshhunt/uber') .pluck('name', 'ssh_url', 'language',
'description', 'watchers_count') )
Realtime with Changefeeds
Realtime changefeeds Subscribe to change notifications on a database query
Receive old and new value Works great with Javascript because its async
Get notified of every change to the show table r.table('shows')
.changes() .run((update) => { update.each(console.log) })
Change for new document { old_val: null new_val: {name: 'Bilbo
Baggins'} }
Change for updated document { old_val: {name: 'Gandalf the Grey'}
new_val: {name: 'Gandalf the White'} }
Change for deleted document { old_val: {name: 'Saruman'} new_val: null
}
Get notified when the top shows (by streams) changes r.table('shows')
.orderBy({index: r.desc('streams')}) .limit(5) .changes()
Supported queries Subscribe to changes to get, between, filter, map,
min, max, orderBy, limit
Use cases Anything realtime - chat, scores, etc To avoid
making DB requests on every request Decouple and send analytics
Using Rethink with Node.js
Official driver r = require('rethinkdb'); r.connect() .then((conn) => { return
r.table('show') .insert({name: 'The Block'}) .run() .finally( => { conn.close() }) }) .then((output) => { console.log(output); })
RethinkDB Dash Alternate driver with ‘advanced features’ Connection pooling -
don’t worry about conn.close() Cursors are coerced to arrays by default
r.connect() .then((conn) => { return r.table('actors') .filter(r.row('age').gt(20)) .run() .finally( =>
{ conn.close() }) }) .then((cursor) => { return cursor.toArray(); }) .then((result) => { assert(Array.isArray(result)); }) r = require('rethinkdbdash')(); r.table('actors') .filter(r.row('age').gt(20)) .run() .then((result) => { assert(Array.isArray(result)); }) Official driver vs rethinkdbdash
Thinky ORM Very light models for RethinkDB Handles creating indexes
for you Automatically join tables (based on model definition)
Creating Thinky models Show = thinky.createModel('Show', { id: type.string(), title:
type.string(), drm: type.boolean() }) Episode = thinky.createModel('Episode', { id: type.string(), title: type.string().min(2), description: type.string() }) Episode.belongsTo(Show, 'show', 'showId', 'id');
Creating documents with Thinky models show = new Show({title: 'The
Block', drm: false}); episode = new Episode({title: 'Episode 455', description: ‘...'}); episode.show = show; episode.saveAll().then((savedEpisode) => { console.log(savedEpisode.id); })
Retrieving and joining with Thinky models Episode.get(req.params.episodeId) .getJoin().run() .then((episode) =>
{ console.log(episode); assert(episode.show.title); })
Resources rethinkdb.com - Indepth API/query documentation - FAQ (rethinkdb vs
mongodb) - Stability Report - Limitations of RethinkDB
Questions?