Last active
October 11, 2018 08:27
-
-
Save varunchitale/d32e762a2f05694a44273c7728679a40 to your computer and use it in GitHub Desktop.
Simple Python function to retrieve propmts
This file contains hidden or 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
def prompts(cursor, search_string): | |
''' | |
In: cursor module, search_string a tsquery acceptable search string | |
Out: Prompts dict | |
''' | |
default_data = {'prompts':[{'id' : 0, 'key': 'No prompts available'}]} | |
prompts_data = {} | |
query_get_prompts = """ | |
select ngram from analytics.mv_prompts | |
where tsquery(%s || ':*') @@ to_tsvector(ngram) | |
limit 10 | |
""" | |
cursor.execute(query_get_prompts, [search_string]) | |
data = cursor.fetchall() | |
prompts_data['prompts'] = [dict(key = rec[0], id = data.index(rec)) for rec in data] | |
if not prompts_data: | |
return default_data | |
return prompts_data | |
@app.route('/autocomplete', methods=['GET']) | |
def autocomplete(): | |
#cursor of connection object of psycopg2 should be defined | |
global cursor | |
search_string = str(request.args.get('input')) | |
data = {'prompts':[{'id' : 0, 'key': str(search_string)}]} | |
#Parsing the search string to make it tsquery parsable, if that's a word | |
search_string = re.sub(r'\%20|\s',' & ',search_string) | |
search_string = re.sub(r'\s\&\s$','',search_string.lower()) | |
if len(search_string) < 3: | |
#String to short to waste our precious time on searching | |
return json.dumps(data) | |
data = prompts(cursor = cursor, search_string = search_string) | |
return json.dumps(data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment