Stemming and ranking results

Django provides a SearchQuery class to translate the terms into a search query object. By default, the terms are passed through stemming algorithms, which helps you to obtain better matches. You also may want to order results by relevancy. PostgreSQL provides a ranking function that orders results based on how often the query terms appear and how close together they are. Edit the views.py file of your blog application and add the following imports:

from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank

Then, take a look at the following lines:

results = Post.objects.annotate(                search=SearchVector('title', 'body'),          ).filter(search=query)

Replace them with the following ones:

search_vector ...

Get Django 2 by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.