Skip to content

Instantly share code, notes, and snippets.

Created September 13, 2010 19:24
Show Gist options
  • Save j4mie/577852 to your computer and use it in GitHub Desktop.
Save j4mie/577852 to your computer and use it in GitHub Desktop.
# - Redis autocomplete example
# download female-names.txt from
# Ruby original:
# Requires
from redis import Redis
r = Redis()
KEY = 'compl'
# Create the completion sorted set
if not r.exists(KEY):
print "Loading entries in the Redis DB"
for line in open('female-names.txt').readlines():
line = line.strip()
for end_index in range(1, len(line)):
prefix = line[0:end_index]
r.zadd(KEY, prefix, 0)
r.zadd(KEY, line + '*', 0)
print "NOT loading entries, there is already a %s key" % KEY
def complete(r, prefix, count):
results = []
rangelen = 50
start = r.zrank(KEY, prefix)
if not start:
return []
while len(results) != count:
range = r.zrange(KEY, start, start + rangelen - 1)
start += rangelen
if not range or len(range) == 0:
for entry in range:
minlen = min((len(entry), len(prefix)))
if entry[0:minlen] != prefix[0:minlen]:
count = len(results)
if entry[-1] == '*' and len(results) != count:
return results
# Complete the string "marcell"
for result in complete(r, "marcell", 50):
print result
Copy link

j4mie commented Sep 13, 2010

Fairly sure this isn't the most Pythonic way of doing it, but it was an exercise in making a direct Ruby -> Python port. Feel free to fork and fix...

Copy link

jedp commented Apr 18, 2011

Awesome - thanks for sharing this. I branched it and gave i support for multi-word phrases.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment