【问题标题】:Django Full Text Search Not Matching Partial WordsDjango全文搜索不匹配部分单词
【发布时间】:2018-01-12 23:21:22
【问题描述】:

我正在使用 Django 全文搜索来搜索多个字段,但在使用部分字符串进行搜索时出现问题。

假设我们有一个名为“Sample Report”的报告对象。

vector = SearchVector('name') + SearchVector('author__username')

search = SearchQuery('Sa')

Report.objects.exclude(visible=False).annotate(search=vector).filter(search=search)

以下 QuerySet 为空,但如果我包含完整的单词“Sample”,则报告将出现在 QuerySet 中。

有没有办法在 django 全文搜索中使用 icontains 或前缀?

【问题讨论】:

标签: python django search full-text-search psql


【解决方案1】:

这适用于 Django 1.11:

tools = Tool.objects.annotate(
    search=SearchVector('name', 'description', 'expert__user__username'),
).filter(search__icontains=form.cleaned_data['query_string'])

注意过滤器中的icontains

【讨论】:

  • 当我尝试使用 SearchQuery 进行搜索查询时,出现数据库错误 ERROR: function replace(tsquery, unknown, unknown) does not exist at character 1603 HINT: No function matches the given name and argument types. You might need to add explicit type casts.
【解决方案2】:

@santiagopim 解决方案是正确的,但如果您收到以下错误,请解决 Matt 的评论:

ERROR:  function replace(tsquery, unknown, unknown) does not exist 
at character 1603 HINT:  No function matches the given name 
and argument types. You might need to add explicit type casts.

您必须删除对SearchQuery 的调用并只使用纯字符串。

如果您需要使用 SearchQuery,我知道这并不能解决根本问题,但如果您像我一样只需要快速修复,您可以尝试以下方法。


vector = SearchVector('name') + SearchVector('author__username')

# NOTE: I commented out the line below
# search = SearchQuery('Sa')
search = 'Sa'

Report.objects.exclude(visible=False).annotate(search=vector)\
.filter(search__icontains =search)

这个other answer 可能会有所帮助。

【讨论】:

    猜你喜欢
    • 2023-01-02
    • 2017-01-20
    • 2014-01-27
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多