Search code examples
pythonflaskredisredisearch

Auto Complete using redis and Flask


I am new to Redis and Redisearch. I want to create an autocomplete using redis in flask app.

Below is what I have tried so far,

autocomplete.py:

import redis
import redisearch
from flask import Flask,request,jsonify,render_template
app = Flask("autocomplete")
#creating a redis connection
r = redis.Redis(host='localhost', port=6379,db=0)

@app.route('/')
def home():
    return "This is Home Page"

#route to add a value to autocomplete list
@app.route('/add')
def addValue():
    try:
        name = request.args.get('name')
        n = name.strip()         
        for l in range(1,len(n)):             
            prefix = n[0:l]             
            r.zadd('compl',{prefix:0})
        r.zadd('compl',{n+"*":0})
        return "Success"
         
    except:
        return "Failed"


#route to get the autocomplete
@app.route('/autocomplete')
def autocomplete():    
    prefix = request.args.get('prefix')
    results = []
    rangelen = 50
    count=5
    start = r.zrank('compl',prefix)    
    if not start:
        return []
    while (len(results) != count):         
         range = r.zrange('compl',start,start+rangelen-1)         
         start += rangelen
         if not range or len(range) == 0:
             break
         for entry in range:
             entry=entry.decode('utf-8')
             minlen = min(len(entry),len(prefix))   
             if entry[0:minlen] != prefix[0:minlen]:    
                count = len(results)
                break              
             if entry[-1] == "*" and len(results) != count:                 
                results.append(entry[0:-1])
    
    return jsonify(results)

Currently the values for @app.route('/add') and prefixes for @app.route('/autocomplete') is fetched through the URL itself. However, I want the prefixes/text for @app.route('/autocomplete') to be fetched through an input textbox to create dynamic autocomplete.

I would be really grateful if anyone could guide me in implementing the same.

This is a sample output: autocomplete

I have also referred to https://redis.com/ebook/part-2-core-concepts/chapter-6-application-components-in-redis/6-1-autocomplete/ but was unable to understand on how to implement it

EDIT : I found a solution for this at https://github.com/RediSearch/redisearch-py/blob/master/redisearch/auto_complete.py


Solution

  • You can use redisearch's autocompleter. Example using flask is available on Github https://github.com/Redislabs-Solution-Architects/redisearch_demo_and_preso