RethinkDB: Open Source Real-Time Database
Tags: node, realtime, javascript, database
Published: 2020-07-11 18:59:14

*This post published on my blog [before](https://aligoren.com/rethinkdb-open-source-real-time-database/)*

---

Hi everyone.

Today I'll talk about RethinkDB.

It's an open-source solution for a realtime database.

## Whats is RethinkDB

RethinkDB is a database that is document-oriented based on NoSQL. This means we'll be using a NoSQL database system.

## Where to Get It?

You can use Rethink's official website to get it.

[https://rethinkdb.com/](https://rethinkdb.com/)

If you're using Windows. You can use this link: [https://rethinkdb.com/docs/install/windows/](https://rethinkdb.com/docs/install/windows/)

## Let's Start

I'll be using Windows as an OS. But it works on various systems. I extracted the rethinkdb.exe file. There is only a single file under the location below.

```bash
C:\RethinkDB
```

So, I'll run this command on the terminal:

```bash
C:\RethinkDB\rethink
```
![RethinkDB terminal](https://dev-to-uploads.s3.amazonaws.com/i/4h7jwpstessfcxrk5qj3.png)

It works!

## Administration Interface

RethinkDB is coming with a built-in web-based administration interface. You can open it using this address: [http://localhost:8080/](http://localhost:8080/)

If port 8080 using by other processes, it should show an error. You can expose it to the network. If you really do that, use this flag: `--bind all`. When you do that, RethinkDB will be accessible on the network.

![RethinkDB administration page](https://dev-to-uploads.s3.amazonaws.com/i/fqqutometb6wl4blk64x.png)

### Dashboard

On this page, you will see some statistical information about servers, tables, indexes, etc.

The first page always will be Dashboard. The cluster performance chart is a real-time chart.

### Tables

You can see your databases and tables on this page. Also, you can create databases or tables or remove them.

![RethinkDB Tables](https://dev-to-uploads.s3.amazonaws.com/i/b259iz9oubt7ogt1mrpc.png)

### Servers

You can see your servers on this page.

![RethinkDB Servers](https://dev-to-uploads.s3.amazonaws.com/i/96k0sbt66rm8vgpvj49s.png)

### Data Explorer

You can create your queries on this page. This is more like a playground. You don't have to use this page.

![RethinkDB Data Explorer](https://dev-to-uploads.s3.amazonaws.com/i/ojn9qt9slg0qokzeamym.png)

### Logs

You can see all logs here.

![RethinkDB Logs](https://dev-to-uploads.s3.amazonaws.com/i/lhk7t7btfvzo8kw9ixad.png)

## Creating a New Database

Let's go to the **Tables** page and click **Add Database** button.

![RethinkDB Create Database](https://dev-to-uploads.s3.amazonaws.com/i/bm5y68otxwrub940ok3q.png)

Its name will be **ecommerce**.

![RethinkDB Database Name](https://dev-to-uploads.s3.amazonaws.com/i/4t8gm1ls0y71fw5cdqbv.png)

If you're sure of your database name, click **Add** button.

## Creating a New Table

Press the "Add Table" button in the database where you want to add a table on the same page.

![RethinkDB Table Name](https://dev-to-uploads.s3.amazonaws.com/i/5l77p5n1ynod3t3ftpgm.png)

If you're sure of your table name, click **Create table** button.

It should be like that;

![RethinkDB Database and Table](https://dev-to-uploads.s3.amazonaws.com/i/5i2oc5tmlp3zdg0a7ufk.png)

## Insert Data

Our first example will be like that;

```javascript
const r = require('rethinkdb');

const newProduct = [
  {
    productName: 'iPhone',
    productId: 1,
    amount: 1
  }
];
    
r.db('ecommerce').table('orders').insert(newProduct);
```

You will be an output like that;

```json
{
	"deleted": 0 ,
	"errors": 0 ,
	"generated_keys": [
		"3dbdfc12-8bba-442e-ad5b-f0827710a134"
	],
	"inserted": 1 ,
	"replaced": 0 ,
	"skipped": 0 ,
	"unchanged": 0
}
```

## Select Data

If you want to get all the data in a table, use this command;

```javascript
const r = require('rethinkdb');

r.db('ecommerce').table('orders');
```

## Filter Data

Data filtering works a little bit differently here. So, we'll use the `filter` method. But its behavior is different than JavaScript's `filter` method.

```javascript
const r = require('rethinkdb');

r.db('ecommerce').table('orders').filter(r.row('productName').eq('iPhone'));
```

The output fill be like that;

```json
{
"amount": 1 ,
	"id": "3dbdfc12-8bba-442e-ad5b-f0827710a134" ,
	"productId": 1 ,
	"productName": "iPhone"
}
```

- `r.row` refers to the currently visited document.
- `r.row('productName')` refers to the value of the field `productName` of the visited document.
- The `eq` command returns true if two values are equal

These are ReQL commands.

## Filter Data by Primary Keys

If you need to filter data by primary keys use this ReQL command;

```javascript
const r = require('rethinkdb');

r
 .db('ecommerce')
 .table('orders')
 .get('3dbdfc12-8bba-442e-ad5b-f0827710a134');
```

## Real-Time Feeds

So let's say we'll update the basket in real-time. What should we do? I'll use RethinkDB's official Node.JS driver for this example. 

You can see official drivers here: [https://rethinkdb.com/docs/install-drivers/](https://rethinkdb.com/docs/install-drivers/)

Firstly, I'll create an empty NodeJS project and I'll install the JavaScript driver of the RethinkDB using this command;

```bash
npm install rethinkdb
```

I'll create a file called **index.js**. We'll write some codes like that;

```javascript
const r = require('rethinkdb');

const rethinkDbConnectionObject = {
    host: 'localhost',
    port: 28015
};

r.connect(rethinkDbConnectionObject, (err, conn) => {
    if (err) {
        console.error('Error:', err);
        return;
    }

    console.log('RethinkDB works');

    r.db('ecommerce').table('orders').changes().run(conn, (err, cursor) => {
        if(err) {
            console.error('Error:', err);
            return;
        }

        cursor.each((err, row) => {
            if(err) {
                console.error('Error:', err);
                return;
            }

            console.log(row)
        });
    });
});
```

And run this command;

```bash
node index.js
```

Now, let's back to the playground to insert data.

```javascript
const newProduct = [
  {
    productName: 'Vestel',
    productId: 5111,
    amount: 2
  }
];
    
r.db('ecommerce').table('orders').insert(newProduct);
```

Our client-side project got the new data that we inserted now in real-time. The script we started before shows this output;

```json
RethinkDB works
{
  new_val: {
    amount: 2,
    id: '4d79cf49-e661-49c6-a74a-21d7502bd85b',
    productId: 5111,
    productName: 'Vestel'
  },
  old_val: null
}
```

Let's say we want to update amounts of all orders

```javascript
r.db('ecommerce').table('orders').update({ amount: 1 });
```

We'll see an output like that;

```javascript
{
  new_val: {
    amount: 1,
    id: '4d79cf49-e661-49c6-a74a-21d7502bd85b',
    productId: 5111,
    productName: 'Vestel'
  },
  old_val: {
    amount: 2,
    id: '4d79cf49-e661-49c6-a74a-21d7502bd85b',
    productId: 5111,
    productName: 'Vestel'
  }
}
{
  new_val: {
    amount: 1,
    id: 'b126f221-f7fd-43e8-b0b8-1ff472a08981',
    productId: 51,
    productName: 'Xaomi'
  },
  old_val: {
    amount: 6,
    id: 'b126f221-f7fd-43e8-b0b8-1ff472a08981',
    productId: 51,
    productName: 'Xaomi'
  }
}
{
  new_val: {
    amount: 1,
    id: '69507d9a-2680-478f-a68b-85fe5035744c',
    productId: 3,
    productName: 'Huawei'
  },
  old_val: {
    amount: 2,
    id: '69507d9a-2680-478f-a68b-85fe5035744c',
    productId: 3,
    productName: 'Huawei'
  }
}
{
  new_val: {
    amount: 1,
    id: 'acbac94b-2947-448c-8a43-02bb0b2fe9b8',
    productId: 2,
    productName: 'Samsung'
  },
  old_val: {
    amount: 5,
    id: 'acbac94b-2947-448c-8a43-02bb0b2fe9b8',
    productId: 2,
    productName: 'Samsung'
  }
}
```

It worked as we expected :)

## Conclusion

- If you don't want to use socket.io, you can use RethinkDB.
- It really fasts for basic projects. I didn't have a chance to try it for a big project.
- It has good drivers for many programming languages
- You can understand ReQL easily. Because it's JavaScript's itself


That's all. Thanks for reading.

## Resources

- [Ten-minute guide with RethinkDB and JavaScript](https://rethinkdb.com/docs/guide/javascript/)
- [RethinkDB nedir? (in Turkish)](https://indatawetrust.blogspot.com/2017/07/rethinkdb-nedir.html)