search

 avatar
unknown
python
3 years ago
770 B
3
Indexable
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)
Editor is loading...