多个SearchVectorFields上的SearchRank

问题描述

我正在尝试将全文搜索集成到我的应用程序中。引用Django 3.1文档 如果要跨多个字段进行加权搜索,则应执行以下操作:

<div id="content">
<embed id="plugin" type="application/x-google-chrome-pdf" **src="https://t4.merlin.net/delegate/PrintSnapshotReportPDFGenerateServlet_B"** stream-url="chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/86c74e86-1371-4a3b-b001-e27bdc20d565" headers="content-disposition: inline
content-length: 190951
content-type: application/pdf
date: Mon,21 Sep 2020 10:59:05 GMT
server: Nginx/1.16.1
status: 200
strict-transport-security: max-age=15552000; includeSubDomains
via: HTTP/1.1 t4.merlin.net:443
x-content-type-options: nosniff
x-frame-options: SAMEORIGIN,SAMEORIGIN
x-powered-by: Undertow/1
x-xss-protection: 1
" background-color="0xFF525659" top-toolbar-height="56" javascript="allow" full-frame="">
</div>

我决定为以后要搜索的文本列添加SearchVectorField,但是我认为有关如何使用这些字段的文档不够好,我找不到与该字段相同的参考。以上查询,但使用SearchVectorField

理想情况下,我想要类似以下的内容

from django.contrib.postgres.search import SearchQuery,SearchRank,SearchVector
vector = SearchVector('body_text',weight='A') + SearchVector('blog__tagline',weight='B')
query = SearchQuery('cheese')
Entry.objects.annotate(rank=SearchRank(vector,query)).filter(rank__gte=0.3).order_by('rank')

解决方法

我发现了一种变通方法,据我所见,该变通方法与不使用SearchVectorFields的方法生成相同的SQL查询。

基本上,我只是使用anateate方法查询每个字段,以为每个SearchVectorField生成自定义排名,然后手动对其进行加权。不是很可扩展的方法,但适用于我的情况。

(..Date.tomorrow).cover?(Date.today)
# => true

(Date.yesterday..).cover?(Date.today)
# => true

(Date.yesterday..).cover?(Date.today - 2.days)
#  => false