gpt4 book ai didi

python - Django/PostgreSQL 全文搜索 - 在 AWS RDS PostgreSQL 上使用 SearchVector 与 SearchVectorField 时的不同搜索结果

转载 作者:行者123 更新时间:2023-11-29 12:15:29 24 4
gpt4 key购买 nike

我正在尝试使用 Django SearchVectorField 来支持全文搜索。但是,当我在我的模型上使用 SearchVectorField 与在我的 View 中实例化一个 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 个结果。使用 SearchVectorFieldfrom_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 生成的值进行比较时,搜索向量看起来非常不同。

有人知道为什么会发生这种情况吗?谢谢!

最佳答案

SearchQuery将用户提供的术语翻译成搜索查询对象,数据库将其与搜索向量进行比较。默认情况下,用户提供的所有单词都通过 Stemming algorithms 传递,然后它会查找所有结果项的匹配项。有两个问题需要解决,首先要提供有关语言的词干提取算法信息。

query = SearchQuery('chance' , config="english")

第二个是替换这一行

rank=SearchRank(F('text_search_vector'), query)

rank=SearchRank('text_search_vector', query)

关于 text_search_vector 中缺失的单词,这是 Stemming algorithms 的标准程序删除称为 stop word 的常用词

关于python - Django/PostgreSQL 全文搜索 - 在 AWS RDS PostgreSQL 上使用 SearchVector 与 SearchVectorField 时的不同搜索结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56674199/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com