How to bulk insert CSV data into Redis with Node Js

Ashok Raja T
Technology Specialist
November 24, 2019
Rate this article
Views    7356

There may be situations where you may have to bulk insert csv data into Redis Server for testing or to pre-load data to be served for applications. For such scenarios, this article can help you to quickly load csv data into Redis.

First thing first, if you haven’t installed Redis or if you have trouble installing Redis in Ubuntu where only IPV6 is enabled, check out my previous article here.

Bulk Insert CSV Data

Install the required npm packages by executing the bellow command.
npm install csv-parser
npm install ioredis

As a next step, create a new file named index.js and paste the bellow code snippet.

const csv = require('csv-parser')
const fs = require('fs');
var Redis = require("ioredis");
var redis = new Redis();
fs.createReadStream('test-data.csv')
    .pipe(csv())
    .on('data', (data) => {
        redis.set('docid:' + data.docid, JSON.stringify(data));
    })
    .on('end', () => {
        console.log('uploaded all data !!!');
        redis.disconnect();
    });
Note: If you are connecting to a remote server make changes to line no : 4. For more details on connection details with “ioredis” refer this link.

By executing the command node index.js , the entire csv (test-data.csv) would be loaded into Redis. In the above example, I have appended a string docid to the keys to differentiate it from other set of keys.

Redis Manager bulk insert

Note: For this example, I have took sample data from U.S. Food & Drugs site. You can download sample csv files from here.

Subscribe To Our Newsletter
Loading

Leave a comment