Storing data in Redis

Redis (REmote DIctionary Server) is an in-memory, key-value database, written in C. In the in-memory mode, Redis is extremely fast, with writing and reading being almost equally fast. Redis follows the publish/subscribe model and uses Lua scripts as stored procedures. Publish/subscribe makes use of channels to which a client can subscribe in order to receive messages. The most recent Redis version at the time of writing was 2.8.12. Redis can be downloaded from the home page at http://redis.io/. After unpacking the Redis distribution, issue the following command to compile the code and create all the binaries:

$ make

Run the server as follows:

$ src/redis-server

Now let's install a Python driver:

$ sudo pip install redis
$ pip freeze|grep redis
redis==2.10.1

It's pretty easy to use Redis when you realize it's a giant dictionary. However, Redis does have its limitations. Sometimes, it's just convenient to store a complex object as a JSON string (or other format). That's what we are going to do with a pandas DataFrame. Connect to Redis as follows:

r = redis.StrictRedis()

Create a key-value pair with a JSON string:

r.set('sunspots', data)

Retrieve the data with the following line:

blob = r.get('sunspots')

The code is straightforward and given in the redis_demo.py file in this book's code bundle:

import redis
import statsmodels.api as sm
import pandas as pd

r = redis.StrictRedis()
data_loader = sm.datasets.sunspots.load_pandas()
df = data_loader.data
data = df.T.to_json()
r.set('sunspots', data)
blob = r.get('sunspots')
print pd.read_json(blob)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.12.207