【问题标题】:How to specify the SearchVector content manually in Django for Postgres?如何在 Django for Postgres 中手动指定 SearchVector 内容?
【发布时间】:2021-11-08 11:14:46
【问题描述】:

Django 支持使用 SearchVectorField 的 Postgres 全文搜索。必须在 Postgres 端使用 to_tsvector 准备数据,这由 Django 中的 SearchVector 函数完成:

class SomeSearchableModel(PostgresModel):
    searchable = SearchVectorField()

我需要使用未存储在表的其他列中的数据填充此列。默认的方法是:

class SomeSearchableModel(PostgresModel):
    text = TextField()
    searchable = SearchVectorField()

每次保存时:

    obj.searchable=SearchVector('text') # Column name to be read

此应用程序不会在数据库中以可用格式保存可搜索数据。内容是在一些后端脚本中准备的。

如何手动提供SearchVectorField 内容?

喜欢:

    obj.searchable=SearchVector(some_processed_text)

PostgreSQL 查询部分是:INSERT INTO ... SET searchable=to_tsvector(...)

无法在 Postgres 中计算内容。

【问题讨论】:

    标签: python django postgresql


    【解决方案1】:

    我认为您只是使用搜索查找。

    取自 - https://docs.djangoproject.com/en/3.2/ref/contrib/postgres/search/#the-search-lookup

    Entry.objects.filter(body_text__search='Cheese')
    

    【讨论】:

    • 不,谢谢。这会进行全表扫描,将列(此处为:body_text)即时转换为 SearchVector,并在查询后丢弃所有内容。不适合一百万行(或更多)。
    【解决方案2】:

    SearchVector 的参数可以是任何表达式或字段名称。多个参数将使用空格连接在一起,以便搜索文档包含所有参数。  SearchVector(Value('some text'))

    感谢 Swen 的回答。

    【讨论】:

      猜你喜欢
      • 2018-04-24
      • 2018-09-26
      • 1970-01-01
      • 2019-05-01
      • 1970-01-01
      • 2017-11-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-21
      相关资源
      最近更新 更多