- Django 2 by Example
- Antonio Melé
- 189字
- 2021-06-25 21:19:08
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 = SearchVector('title', 'body')
search_query = SearchQuery(query)
results = Post.objects.annotate(
search=search_vector,
rank=SearchRank(search_vector, search_query)
).filter(search=search_query).order_by('-rank')
In the preceding code, we created a SearchQuery object, filtered results by it, and used SearchRank to order the results by relevancy. You can open http://127.0.0.1:8000/blog/search/ in your browser and test different searches to test stemming and ranking. The following is an example of ranking by the number of occurrences for the word django in the title and body of the posts: