search

mail@pastecode.io avatar
unknown
python
2 years ago
770 B
2
Indexable
Never
from django.contrib.postgres.search import SearchQuery, SearchVector, SearchRank
from restapi.models import Article

@api_view()
def search(request: Request) -> Response:
    q = request.query_params.get('q', '')

    if q:
        vector = SearchVector('headline')
        query = SearchQuery(q)
        articles = [
            {'headline': article.headline,
            'feed': article.feed,
            'article_id': article.article_id,
            'asset_class': article.asset_class,
            'sentiment': article.sentiment_classification
            } for article in Article.objects.annotate(rank=SearchRank(vector, query)).filter(rank__gte=0.001).order_by('-rank')]
    else:
        articles = ''

    return Response(data={'articles': articles}, status=200)