官术网_书友最值得收藏!

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:

主站蜘蛛池模板: 宝兴县| 东乡县| 霍林郭勒市| 洛阳市| 外汇| 萝北县| 庆阳市| 治多县| 镇坪县| 昭觉县| 溧阳市| 谢通门县| 资兴市| 醴陵市| 遂溪县| 天门市| 泗水县| 蚌埠市| 义乌市| 新河县| 新龙县| 平武县| 临武县| 泰兴市| 凤山县| 台安县| 革吉县| 锡林浩特市| 屏边| 白玉县| 台南市| 江油市| 扎鲁特旗| 河源市| 尉犁县| 张家口市| 元氏县| 洪泽县| 贵德县| 乌鲁木齐市| 读书|