From: Michael Tremer Date: Wed, 17 Oct 2018 12:40:53 +0000 (+0100) Subject: blog: Fix search with multiple terms X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=a47ddc3d3c7321fea49fe2ed93a38dc1c35ceb20;p=ipfire.org.git blog: Fix search with multiple terms Signed-off-by: Michael Tremer --- diff --git a/src/backend/blog.py b/src/backend/blog.py index e39b0ec7..913ed2db 100644 --- a/src/backend/blog.py +++ b/src/backend/blog.py @@ -88,12 +88,33 @@ class Blog(misc.Object): ORDER BY COALESCE(updated_at, created_at) DESC LIMIT %s", limit) def search(self, query, limit=None): + query = self._parse_search_query(query) + return self._get_posts("SELECT blog.* FROM blog \ LEFT JOIN blog_search_index search_index ON blog.id = search_index.post_id \ WHERE search_index.document @@ to_tsquery('english', %s) \ ORDER BY ts_rank(search_index.document, to_tsquery('english', %s)) DESC \ LIMIT %s", query, query, limit) + def _parse_search_query(self, query): + q = [] + for word in query.split(): + # Is this lexeme negated? + negated = word.startswith("!") + + # Remove any special characters + word = re.sub(r"\W+", "", word, flags=re.UNICODE) + if not word: + continue + + # Restore negation + if negated: + word = "!%s" % word + + q.append(word) + + return " & ".join(q) + def create_post(self, title, text, author, tags=[], lang="markdown"): """ Creates a new post and returns the resulting Post object