]> git.ipfire.org Git - ipfire.org.git/commitdiff
blog: Fix search with multiple terms
authorMichael Tremer <michael.tremer@ipfire.org>
Wed, 17 Oct 2018 12:40:53 +0000 (13:40 +0100)
committerMichael Tremer <michael.tremer@ipfire.org>
Wed, 17 Oct 2018 15:12:45 +0000 (16:12 +0100)
Signed-off-by: Michael Tremer <michael.tremer@ipfire.org>
src/backend/blog.py

index e39b0ec739f9419596ca4a7a1e479d556aea65f6..913ed2db8b53afcefe99f87224123f9a01880abd 100644 (file)
@@ -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