DEV Community

Cover image for How To Store And Retrieve RedisJSON on Redis Cloud using Node.js
Tochukwu Adams
Tochukwu Adams

Posted on • Updated on

How To Store And Retrieve RedisJSON on Redis Cloud using Node.js

Image: linuxscriptshub.com

Overview

If you have been developing server-side applications that means you have been using some sort of database for storing and retrieving data. When it comes to picking a database most time our top priorities are speed and availability. Although there are other databases, of late, Redis has gained popularity when it comes to NoSQL databases.

In the past couple of months, I have been using the Redis database to manage some of my applications and as my applications scaled, I discovered I was utilizing more of Redis features. One of those features is the Redis Stack. Before we dive into the Redis Stack let me give a brief introduction to Redis and its importance.

What is Redis?

Redis is an open-source in-memory key/value pair database. This is to say that data-sets are stored in your RAM instead of your disk (SSD, HDD) in key and value format. Some of the pros of using Redis are its speed and high availability. If you are developing e-commerce, inventory, micro-services and speed is your priority then Redis is a better solution. You can use the Redis cloud database to manage your application due to its low latency and in-memory storage capabilities.

Redis Stack

Redis Stack is an extension of Redis that enables a user to create a data-driven application by providing dynamic data models making it easier for someone to create queryable objects. Redis Stack has different modules but in this tutorial, we will be utilizing the RedisJSON module. The RedisJSON modules allow storing and updating of data in JSON format.

Goal

The aim of this article is to learn how to use RedisJSON to store records in JSON format on a Redis Cloud database. For this project we will be creating a simple Node app that stores rider's details. So we have delivery men, and we want to store their records on our Redis cloud database.

Prerequisite:

You need, the following installed:
1. Node
2. YARN or NPM package installer

Let’s set up a Redis Cloud Database and connect it to our Node application, and like I mentioned earlier we will be utilizing one of the Redis Stack modules RedisJSON.

Redis Cloud

If you are asking why Redis Cloud? One of the cons of Redis is that data are store in memory which requires large RAM with Redis Enterprise Cloud you can store data in real-time in memory and still maintain persistence. Redis Cloud provides a multiple cloud platform (AWS, Azure, Google Cloud) where you can deploy your Redis dataset with ease without fear for data loss and it supports Redis commands and modules. If you are a newcomer to Redis Cloud you can use this link to create a free account. After creating an account, you will be assigned a free 30 MB storage or you can start a subscription plan.

Once you have setup a Redis Cloud account you will have an interface similar to the image below.

image

Environment Setup

Lets setup our Node app. Open your terminal or command line on your system, create a project directory or folder.

$ mkdir redisjson-node-js

After creating the project folder CD into the folder and create a package.json file with the command below. You can use YARN or NPM.

$ yarn init

Before creating a database connection on our app, we do need to install a Redis Client package. I am using the redis npm package. The Redis Client enables our app to interact with Redis server.

$ yarn add express

$ yarn add redis

Create a JavaScript file. You can name yours whatever you like.

$ touch index.js

Lets get our hands dirty!

const express = require('express')

// enables our application to interact with redis server
const { createClient } = require('redis');

const app = express();
app.use(express.json());

// database connection
const redis = createClient({
      // url: 'redis://default:Q*Y***H*q***l*rm**Sk**y*9@redis-*3*0*.c62.us-****-2-4.ec2.cloud.redislabs.com:*3*0*
    url: 'redis://username:password@host:port'
});
redis.on('connect', () => console.log('DB connected'));   
redis.on('error', (err) => console.log('Redis Connection Error', err));
redis.connect();

// at the bottom of the script
app.listen(3000, () => console.log('app is running on port 3000'));

Enter fullscreen mode Exit fullscreen mode
How to get your Redis cloud database credentials:

Go to you account under configuration tab.

For username and password - scroll down to security session there lies your username and password

image

Host and port: On the General section, your public endpoint is your host and the digits after the colon is your port number.

image

The code below should be placed in between the database connection and app.listen function.

app.use('/home', (req, res) => {
    return res.send('welcome home');
});

// store rider details
app.post('/riders', async (req, res) => {

    const {first_name, last_name, email, coordinates} = req.body;
    // convert current date to milliseconds
    const date = Math.floor(Date.now() / 1000);

    // checks if the path exist
    const pathExist = await redis.json.type('employee');
    let rider;
    if (pathExist) {
        rider = await redis.json.arrAppend('employee', '.riders', 
        {
            first_name,
            last_name,
            email,
            coordinates,
            update_at: date
        }

        )
    }  else  {
        rider = await redis.json.set('employee', '$', {
            riders: [
            {
                first_name,
                last_name,
                email,
                coordinates,
                update_at: date

            }
        ]}
        )
        }

    return res.send({
        message: 'rider created successfully',
        data: rider
    });

});

// Get all riders
app.get('/riders', async (req, res) => {
    const rider = await redis.json.get('employee');
    return res.send(rider)
})

// at the bottom of the script
app.listen(3091, () => console.log('app is running on port 3091'));
Enter fullscreen mode Exit fullscreen mode

Before storing the record we have to check if the path exist to avoid overriding existing records.

Commands

JSON.SET: Will creates a new path if it does not exist and add the values to a JSON object. If the path exists it will override the existing JSON value with the new values.

JSON.ARRAPPEND: Adds the JSON values to the end of the array.

JSON.TYPE: If the path does not exit it returns null.

JSON.GET: Fetches all the values on the specified path.

Conclusion

In this tutorial we have learnt how to create a Redis cloud database, store and retrieve records in JSON format using the RedisJSON stack modules and we have also seen the benefits of using Redis cloud to store our records.

Related:

Benefits of using using Redis Cloud

Redis Developer Hub

RedisInsight Desktop GUI

Top comments (0)