Tutorialsarun

How to convert and import CSV to Redis

Introduction

When a large amount of static data is requested continuously, a fast key-value cache helps. We already had a large volume of data in an SQL database, so here is how to convert it to CSV and load it into Redis.

How to convert and import CSV to Redis

Step 1: Export data from the SQL database

Export the data from your SQL store to CSV with your favourite tool. We used Sequel Pro to dump the data.

Step 2: Convert the CSV to Redis commands

Our CSV file has the following format. Call it input.csv:

1, key1, value1, created_at, updated_at
2, key2, value2, created_at, updated_at

Convert the CSV to Redis commands. The command below prints SET with the key and value from input.csv and removes double quotes. Edit it to match your file: $1 prints the first column (counting starts at 1, not 0).

awk -F, 'BEGIN {OFS=","} { print "SET",$2, $3}' input.csv | sed 's/\"//g'

Check that the output has the format SET,key1,value1. When it does, save it to output.txt:

awk -F, 'BEGIN {OFS=","} { print "SET",$2, $3}' input.csv | sed 's/\"//g' > output.txt

We will use Redis mass insertion, which requires converting the Redis commands to the Redis protocol.

Step 3: Convert the commands to the Redis protocol

Save the following script as gen_redis_proto.py. It is also available on GitHub. Note that it is written for Python 2.

Python 2 reached end of life on January 1, 2020. Port the script to Python 3 before you rely on it.

#!/usr/bin/env python -tt
# -*- coding: UTF-8 -*-
"""
Generating Redis Protocol

Generate the Redis protocol, in raw format, in order to use 'redis-cli --pipe' command to massively insert/delete.... keys in a redis server
It accepts as input a pipe with redis commands formatted as "SET key value" or "DEL key"...

Usage:

      echo "SET,mykey1,value1\nSET,mykey2,value2" > data.txt
      cat data.txt | python gen_redis_proto.py | redis-cli --pipe

"""

__author__ = "Salimane Adjao Moustapha ([email protected])"
__version__ = "$Revision: 1.0 $"
__date__ = "$Date: 2013/04/30 12:57:19 $"
__copyleft__ = "Copyleft (c) 2013 Salimane Adjao Moustapha"
__license__ = "MIT"

import sys
import fileinput
from itertools import imap

def encode(value):
    "Return a bytestring representation of the value"
    if isinstance(value, bytes):
        return value
    if not isinstance(value, unicode):
        value = str(value)
    if isinstance(value, unicode):
        value = value.encode('utf-8', 'strict')
    return value

def gen_redis_proto(*cmd):
    proto = ""
    proto += "*" + str(len(cmd)) + "\r\n"
    for arg in imap(encode, cmd):
        proto += "$" + str(len(arg)) + "\r\n"
        proto += arg + "\r\n"
    return proto

if __name__ == '__main__':
    for line in fileinput.input():
        sys.stdout.write(gen_redis_proto(*line.rstrip().split(',')))

Now generate the protocol and pipe it into Redis:

cat output.txt | python gen_redis_proto.py | redis-cli --pipe

The CSV data is now cached in Redis memory. To persist it to an .rdb file, run the BGSAVE command.

Questions? Schedule a call

Schedule a call

Leave your number and a good time, and we will call you.

Start building for free

Create a free datayuge account, get your API key and make your first request.

Create free account