【发布时间】:2019-11-02 13:53:43
【问题描述】:
我正在尝试使用 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
使用SearchVector 实例的on_the_fly 查询集返回32 个结果。使用SearchVectorField 的from_field 查询集返回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 生成的值进行比较时,您可以看到搜索向量看起来非常不同。
有没有人知道为什么会发生这种情况?谢谢!
【问题讨论】:
-
用
'text_search_vector'替换F('text_search_vector')
标签: python django python-3.x postgresql amazon-web-services