from apps.articles.models import Article from .base import SearchBackend # Matches the stored search_vector column, GIN index, and maintaining # trigger created by apps/search/migrations/0002_postgres_search_vector.py # — the query reads that column directly instead of recomputing a # tsvector over every article's full text on every search (C5). _VECTOR = "articles_article.search_vector" _QUERY = "plainto_tsquery('english', %s)" class PostgresSearchBackend(SearchBackend): def search(self, query: str, user, limit: int = 50): if not query.strip(): return Article.objects.none() return ( Article.objects.filter(feed__subscriptions__user=user) .select_related("feed") .extra( select={"rank": f"ts_rank({_VECTOR}, {_QUERY})"}, select_params=[query], where=[f"{_VECTOR} @@ {_QUERY}"], params=[query], ) .order_by("-rank", "-published_at")[:limit] )