【问题标题】:How to implement PostgresQL tsvector for full-text search using Sequelize?如何使用 Sequelize 实现 PostgresQL tsvector 进行全文搜索?
【发布时间】:2026-02-14 14:30:01
【问题描述】:

我正在阅读本教程: https://www.digitalocean.com/community/tutorials/how-to-use-full-text-search-in-postgresql-on-ubuntu-16-04

建议将document 列添加为tsvector 并对其应用索引。

ALTER TABLE news ADD "document" tsvector;
CREATE INDEX idx_fts_search ON news USING gin(document);
SELECT title, content FROM news WHERE document @@ to_tsquery('Travel | Cure');

如何使用 sequelize 实现 document 列?没有tsvector数据类型:http://docs.sequelizejs.com/variable/index.html

(现在是试用 Knex.js 的好时机吗?)

【问题讨论】:

  • 您应该能够将类型指定为字符串。您不必使用内置类型。您只需做一些工作即可从数据库中获取值。作为参考,我在 Postgres 中使用了 CITEXT 作为类型,从未遇到过问题。

标签: postgresql sequelize.js


【解决方案1】:

Sequelize 版本 6.5.0+ 支持 TSVECTOR 数据类型。但是到目前为止我还没有找到任何文档,所以:

声明:

sequelize.define('User', {
  myVector: { type: DataTypes.TSVECTOR },
  ...
})

填充它:

User.myVector = sequelize.fn('to_tsvector', 'My Content About Travel and Apparently Some Cures')

在查询中使用它:

User.findAll({
  where: { 
    myVector: { [Op.match]: sequelize.fn('to_tsquery', 'Travel | Cure') }
  }
})

探索拉取请求以了解更多详情:https://github.com/sequelize/sequelize/pull/12955

【讨论】:

    【解决方案2】:

    CREATE INDEX 之前尝试UPDATE news

    ALTER TABLE news ADD COLUMN document tsvector;
    
    UPDATE news SET document = to_tsvector(coalesce(title,'') || ' ' || coalesce(content,''));
    
    CREATE INDEX idx_fts_search ON news USING gin(document);
    SELECT title, content FROM news WHERE document @@ to_tsquery('Travel | Cure');
    

    【讨论】: