Skip to content

Instantly share code, notes, and snippets.

@lumilux
Forked from shinzui/compl1.rb
Created February 28, 2011 08:36
Show Gist options
  • Save lumilux/847089 to your computer and use it in GitHub Desktop.
Save lumilux/847089 to your computer and use it in GitHub Desktop.
# compl1.py - Redis autocomplete example
# download female-names.txt from http://antirez.com/misc/female-names.txt
import redis #redis-py
import sys
r = redis.Redis(host='localhost', port=6379, db=1)
# Create the completion sorted set
if not r.exists('compl'):
print("Loading entries in the Redis DB")
with open('female-names.txt') as f:
for n in f.readlines():
n = n.strip()
for c in xrange(0, len(n)):
prefix = n[0:c]
r.zadd('compl', prefix, 0.)
r.zadd('compl', n+'*', 0.)
else:
print("NOT loading entries, there is already a 'compl' key\n")
# Complete the string "mar"
def complete(r, prefix, count):
results = []
rangelen = 50 # This is not random, try to get replies < MTU size
start = r.zrank('compl', prefix)
if not start: return []
while len(results) != count:
rng = r.zrange('compl', start, start+rangelen-1)
if not rng: break
for entry in rng:
if entry[-1] == '*' and len(results) != count:
results.append(entry[0:-1])
print(results)
return results
for res in complete(r, 'mar', 10):
print(res)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment