Sqlite 使用 fts5 table 执行所有查询而不是 main table

Sqlite using fts5 table to perform all queries instead of main table

假设我有两个 table:usersusers_fts,其中 users_fts 是搜索 table。所以 users 有两个字段 namesurname.

通常我会为这两个 em' 创建索引。但是既然我有 users_fts,我是否需要在 users 中为 namesurname 创建索引?使用 users_fts 执行所有查询而不是使用主 table users 是否有任何警告?

SQLite 提供全文搜索,我假设这就是您使用的 table 名称。我将使用 FTS5 展示示例代码,但如果需要,您可以向后调整它。如果你有 users table 类似的东西:

CREATE TABLE users(
    id INTEGER PRIMARY KEY, 
    name TEXT NOT NULL, 
    surname TEXT NOT NULL
);

然后您使用如下方式进行了全文搜索 table:

CREATE VIRTUAL TABLE users_fts USING fts5(
    name, 
    surname, 
    content='user', 
    content_rowid='id'
);

在这一点上,我们必须确保 users table 中的记录被索引以进行全文搜索,这可以使用 users 上的触发器来完成table 自动执行。触发器看起来像:

CREATE TRIGGER users_ai AFTER INSERT ON users
    BEGIN
        INSERT INTO users_fts (rowid, name, surname)
        VALUES (new.id, new.name, new.surname);
    END;

CREATE TRIGGER users_ad AFTER DELETE ON users
    BEGIN
        INSERT INTO users_fts (users_fts, rowid, name, surname)
        VALUES ('delete', old.id, old.name, old.surname);
    END;

CREATE TRIGGER users_au AFTER UPDATE ON users
    BEGIN
        INSERT INTO users_fts (users_fts, rowid, name, surname)
        VALUES ('delete', old.id, old.name, old.surname);
        INSERT INTO users_fts (rowid, name, surname)
        VALUES (new.id, new.name, new.surname);
    END;

所有这些准备就绪后,您现在可以使用 users_fts table 执行全文搜索。

那么 users table 上的索引如何影响 users_fts table?如果您仅使用 users_fts table 进行搜索,那么 users table 上的索引无关紧要。我不知道您打算如何填充 users_fts table,但是如果您在 users table 上使用触发器,那么建议在 users table还是无所谓。如果您手动保持 users_fts table 最新,那么答案是 users table 上的索引可能 影响表现。我认识的大多数人都使用触发器方法,这就是我所做的,让您忘记手动维护全文搜索,并且您可以获得额外的好处,即您可以忽略源 table 上的索引来填充全文搜索。请记住,这是您根本不查询 users table 的场景 - 如果您对 users table 有任何查询,那么您 可能需要支持索引。

您还询问了使用 users_fts table 进行查询的方法是否有任何注意事项 - 只要您保持 users_fts table到目前为止,这种方法没有任何缺点。如果您需要全文搜索功能和排名,这是融入 SQLite 的一种非常方便的方法。它将需要更多存储空间 space,但您可以通过使用外部内容 table 将影响降至最低(我在创建 users_fts table 时展示了它)。您可以在 https://www.sqlite.org/fts5.html

的 FTS5 扩展文档的第 4.4.2 节中阅读有关它的一些详细信息

这种方法适用于全文搜索功能,只要您维护索引,它就应该运行良好,并为您提供更多的搜索和排名功能。根据我的经验,大多数全文搜索都比使用标准 SQL 函数和运算符(例如 LIKE 等)的速度更快,而且功能更强大。