SQLite全文索引fts4和fts5支持contentless和content表,这两个表结构的区别就是contentless只有索引,不存储原文,所以数据库不会增加很大,缺点是源表修改后,contentless表无法更新。conentless表建立语句如下:
CREATE VIRTUAL TABLE f1 USING fts5(a, b, c, content='');
字段a,b,c是要全文索引的字段,建立以后要执行初始化插入数据:
INSERT INTO t1(rowid, a, b, c) VALUES(1, 'a b c', 'd e f', 'g h i');
注意fts4有docid字段,fts5已经没有了,而是用rowid代替。
fts5 content表建表语句:
源表 CREATE TABLE tbl (a, b, c, d INTEGER PRIMARY KEY);
fts5表 CREATE VIRTUAL TABLE fts USING fts5(a, c, content=tbl, content_rowid=d);
fts5建表语句就直接初始化数据了,但是content表会增加数据库文件将近一倍的大小。
如果要保持content表跟源表同步变化,必须使用触发器trigger来实现:
-- Create a table. And an external content fts5 table to index it.
CREATE TABLE tbl(a INTEGER PRIMARY KEY, b, c);
CREATE VIRTUAL TABLE fts_idx USING fts5(b, c, content='tbl', content_rowid='a');
-- Triggers to keep the FTS index up to date.
CREATE TRIGGER tbl_ai AFTER INSERT ON tbl BEGIN
INSERT INTO fts_idx(rowid, b, c) VALUES (new.a, new.b, new.c);
END;
CREATE TRIGGER tbl_ad AFTER DELETE ON tbl BEGIN
INSERT INTO fts_idx(fts_idx, rowid, b, c) VALUES('delete', old.a, old.b, old.c);
END;
CREATE TRIGGER tbl_au AFTER UPDATE ON tbl BEGIN
INSERT INTO fts_idx(fts_idx, rowid, b, c) VALUES('delete', old.a, old.b, old.c);
INSERT INTO fts_idx(rowid, b, c) VALUES (new.a, new.b, new.c);
END;
网友评论