Add searching for "exact phrases" to search.

master
Snakes 2022-07-04 04:19:41 -04:00
parent 67dff25a5a
commit 95f9fbfab1
1 changed files with 12 additions and 24 deletions

View File

@ -19,22 +19,22 @@ def searchparse(text):
text = text.lower() text = text.lower()
criteria = {x[0]:x[1] for x in query_regex.findall(text)} criteria = {x[0]:x[1] for x in query_regex.findall(text)}
for x in criteria: for x in criteria:
if x in valid_params: if x in valid_params:
text = text.replace(f"{x}:{criteria[x]}", "") text = text.replace(f"{x}:{criteria[x]}", "")
text = text.strip() text = text.strip()
re_search_token = re.compile('"([^"]*)"|(\S+)')
if text: if text:
criteria['q']=text criteria['q'] = []
for m in re_search_token.finditer(text):
token = m[1] if m[1] else m[2]
# Escape SQL pattern matching special characters
token = token.replace('\\', '').replace('_', '\_').replace('%', '\%')
criteria['q'].append(token)
return criteria return criteria
@app.get("/search/posts") @app.get("/search/posts")
@auth_required @auth_required
def searchposts(v): def searchposts(v):
@ -50,15 +50,6 @@ def searchposts(v):
posts = g.db.query(Submission.id).filter(Submission.author_id.notin_(v.userblocks)) posts = g.db.query(Submission.id).filter(Submission.author_id.notin_(v.userblocks))
if not v.paid_dues: posts = posts.filter_by(club=False) if not v.paid_dues: posts = posts.filter_by(club=False)
@ -91,9 +82,8 @@ def searchposts(v):
else: posts = posts.filter(Submission.author_id == author.id) else: posts = posts.filter(Submission.author_id == author.id)
if 'q' in criteria: if 'q' in criteria:
words=criteria['q'].split() words = [or_(Submission.title.ilike('%'+x+'%'), Submission.body.ilike('%'+x+'%')) \
words = criteria['q'].replace('\\', '').replace('_', '\_').replace('%', '\%').strip().split() for x in criteria['q']]
words = [or_(Submission.title.ilike('%'+x+'%'), Submission.body.ilike('%'+x+'%')) for x in words]
posts = posts.filter(*words) posts = posts.filter(*words)
if 'over18' in criteria: posts = posts.filter(Submission.over_18==True) if 'over18' in criteria: posts = posts.filter(Submission.over_18==True)
@ -206,9 +196,7 @@ def searchcomments(v):
else: comments = comments.filter(Comment.author_id == author.id) else: comments = comments.filter(Comment.author_id == author.id)
if 'q' in criteria: if 'q' in criteria:
words = criteria['q'].replace('\\', '').replace('_', '\_').replace('%', '\%').strip().split() words = [Comment.body.ilike('%'+x+'%') for x in criteria['q']]
words = [Comment.body.ilike('%'+x+'%') for x in words]
comments = comments.filter(*words) comments = comments.filter(*words)
if 'over18' in criteria: comments = comments.filter(Comment.over_18 == True) if 'over18' in criteria: comments = comments.filter(Comment.over_18 == True)