- 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:

- 網絡云百問百答
- CorelDRAW X6 中文版圖形設計實戰從入門到精通
- 智慧城市中的移動互聯網技術
- WordPress 5 Complete
- 網絡互聯技術(實踐篇)
- 網絡安全技術與解決方案(修訂版)
- Bonita Open Solution 5.x Essentials
- 物聯網場景設計與開發(初級)
- Learning Node.js Development
- 沖擊:5G如何改變世界
- TCP/IP基礎(第2版)
- 物聯網M2M開發技術:基于無線CPU-Q26XX
- React Design Patterns and Best Practices(Second Edition)
- Corona SDK Application Design
- 智慧的物聯網:感知中國和世界的技術