SQLite 的全文搜索(FTS)功能提供高效的文本搜索能力:
-
FTS 扩展模块
- SQLite 提供 FTS3、FTS4、FTS5 三个版本
- FTS5 是最新版本,功能最强大
- 需要在编译时启用相应的扩展
-
创建 FTS 表
sql-- 使用 FTS5 创建全文搜索表 CREATE VIRTUAL TABLE articles_fts USING fts5(title, content); -- 使用 FTS4 创建全文搜索表 CREATE VIRTUAL TABLE articles_fts USING fts4(title, content); -
插入数据
sql-- 插入数据到 FTS 表 INSERT INTO articles_fts (title, content) VALUES ('SQLite Tutorial', 'SQLite is a lightweight database...'); -
全文搜索查询
sql-- 简单搜索 SELECT * FROM articles_fts WHERE articles_fts MATCH 'SQLite'; -- 短语搜索 SELECT * FROM articles_fts WHERE articles_fts MATCH '"lightweight database"'; -- 布尔搜索 SELECT * FROM articles_fts WHERE articles_fts MATCH 'SQLite AND database'; -- 前缀搜索 SELECT * FROM articles_fts WHERE articles_fts MATCH 'data*'; -
FTS5 高级功能
- 外部内容表:将 FTS 表与普通表关联
sqlCREATE TABLE articles(id, title, content); CREATE VIRTUAL TABLE articles_fts USING fts5(title, content, content='articles', content_rowid='id');- 触发器自动同步:使用触发器保持 FTS 表与源表同步
- 排名函数:使用
bm25()函数进行结果排序
-
性能优化
- 为大型文档创建 FTS 索引
- 使用批量插入提高性能
- 定期优化 FTS 表
sqlINSERT INTO articles_fts(articles_fts) VALUES('optimize'); -
使用场景
- 文档搜索系统
- 日志分析
- 产品搜索
- 内容管理系统
- 代码搜索
FTS 功能使 SQLite 能够处理复杂的文本搜索需求,是构建搜索功能的重要工具。