Created
December 16, 2011 17:42
-
-
Save carlopires/1487076 to your computer and use it in GitHub Desktop.
Indexing Redis with Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
""" | |
Created on 16/12/2011 | |
@author: Carlo Pires <[email protected]> | |
""" | |
import json | |
from redis import Redis | |
r = Redis() | |
data = [ | |
{'id': '001', 'name': 'Linus', 'age': '36'}, | |
{'id': '002', 'name': 'Richard', 'age': '30'}, | |
{'id': '003', 'name': 'Eric', 'age': '31'}, | |
{'id': '004', 'name': 'Maria', 'age': '68'}, | |
{'id': '005', 'name': 'Roberto', 'age': '53'}, | |
{'id': '006', 'name': 'Marcelo', 'age': '36'}, | |
] | |
def insert(record): | |
r.hset('names:'+ record['id'], 'data', json.dumps(record)) | |
r.hset('names:'+ record['id'], 'name', record['name'].lower()) | |
r.hset('names:'+ record['id'], 'age', int(record['age'])) | |
r.rpush('names:name', record['id']) | |
r.rpush('names:age', record['id']) | |
# remove indexes, if exists | |
r.delete('names:name') | |
r.delete('names:age') | |
# insert/update data | |
for record in data: | |
insert(record) | |
# list by name: | |
print 'by name:' | |
for row in r.sort('names:name', by='names:*->name', get='names:*->data', desc=False, alpha=True): | |
print row | |
# list by age: | |
print 'by age:' | |
for row in r.sort('names:age', by='names:*->age', get='names:*->data', desc=False, alpha=False): | |
print row |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment