Weighting queries

You can boost specific vectors so that more weight is attributed to them when ordering results by relevancy. For example, you can use this to give more relevance to posts that are matched by title rather than by content. Edit the previous lines of the views.py file of your blog application and make them look like this:

search_vector = SearchVector('title', weight='A') + SearchVector('body', weight='B')
search_query = SearchQuery(query)
results = Post.objects.annotate(
rank=SearchRank(search_vector, search_query)
).filter(rank__gte=0.3).order_by('-rank')

In the preceding code, we apply different weights to the search vectors built using the title and body fields. The default weights are D, C, B, and A that refer to the numbers 0.1, 0.2, 0.4, and 1.0, respectively. We apply a weight of 1.0 to the title search vector and a weight of 0.4 to the body vector: title matches will prevail over body content matches. We filter the results to display only the ones with a rank higher than 0.3.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.22.23