[英]Django/PostgreSQL Full Text Search - Different search results when using SearchVector versus SearchVectorField on AWS RDS PostgreSQL
我正在嘗試使用 Django SearchVectorField
來支持全文搜索。 但是,當我在我的模型上使用SearchVectorField
與在我的視圖中實例化SearchVector
類時,我得到了不同的搜索結果。 該問題與 AWS RDS PostgreSQL 實例隔離。 兩者在我的筆記本電腦上的表現相同。
讓我試着用一些代碼來解釋它:
# models.py
class Tweet(models.Model):
def __str__(self):
return self.tweet_id
tweet_id = models.CharField(max_length=25, unique=True)
text = models.CharField(max_length=1000)
text_search_vector = SearchVectorField(null=True, editable=False)
class Meta:
indexes = [GinIndex(fields=['text_search_vector'])]
我已經用搜索向量填充了所有行,並在數據庫上建立了一個觸發器以保持該字段是最新的。
# views.py
query = SearchQuery('chance')
vector = SearchVector('text')
on_the_fly = Tweet.objects.annotate(
rank=SearchRank(vector, query)
).filter(
rank__gte=0.001
)
from_field = Tweet.objects.annotate(
rank=SearchRank(F('text_search_vector'), query)
).filter(
rank__gte=0.001
)
# len(on_the_fly) == 32
# len(from_field) == 0
on_the_fly
使用SearchVector
實例,返回 32 個結果。 使用from_field
的SearchVectorField
返回 0 個結果。
空結果提示我進入 shell 進行調試。 這是我的python manage.py shell
環境中命令行的一些輸出:
>>> qs = Tweet.objects.filter(
... tweet_id__in=[949763170863865857, 961432484620787712]
... ).annotate(
... vector=SearchVector('text')
... )
>>>
>>> for tweet in qs:
... print(f'Doc text: {tweet.text}')
... print(f'From db: {tweet.text_search_vector}')
... print(f'From qs: {tweet.vector}\n')
...
Doc text: @Espngreeny Run your 3rd and long play and compete for a chance on third down.
From db: '3rd':4 'chanc':12 'compet':9 'espngreeni':1 'long':6 'play':7 'run':2 'third':14
From qs: '3rd':4 'a':11 'and':5,8 'chance':12 'compete':9 'down':15 'espngreeny':1 'for':10 'long':6 'on':13 'play':7 'run':2 'third':14 'your':3
Doc text: No chance. It was me complaining about Girl Scout cookies. <url-removed-for-stack-overflow>
From db: '/aggcqwddbh':13 'chanc':2 'complain':6 'cooki':10 'girl':8 'scout':9 't.co':12 't.co/aggcqwddbh':11
From qs: '/aggcqwddbh':13 'about':7 'chance':2 'complaining':6 'cookies':10 'girl':8 'it':3 'me':5 'no':1 'scout':9 't.co':12 't.co/aggcqwddbh':11 'was':4
將數據庫中的值與通過 Django 生成的值進行比較時,您可以看到搜索向量看起來非常不同。
有沒有人對為什么會發生這種情況有任何想法? 謝謝!
SearchQuery將用戶提供的術語轉換為搜索查詢對象,數據庫將其與搜索向量進行比較。 默認情況下,用戶提供的所有單詞都會通過詞干算法,然后它會查找所有結果術語的匹配項。 有兩個問題需要解決,首先給出關於語言的詞干算法信息。
query = SearchQuery('chance' , config="english")
其次是替換這一行
rank=SearchRank(F('text_search_vector'), query)
和
rank=SearchRank('text_search_vector', query)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.