乐闻世界logo
搜索文章和话题

How to use SQLite's Full-Text Search (FTS) functionality?

2月18日 21:33

SQLite's Full-Text Search (FTS) functionality provides efficient text search capabilities:

  1. FTS Extension Modules

    • SQLite provides three versions: FTS3, FTS4, FTS5
    • FTS5 is the latest version with the most powerful features
    • Need to enable corresponding extensions during compilation
  2. Creating FTS Tables

    sql
    -- Create full-text search table using FTS5 CREATE VIRTUAL TABLE articles_fts USING fts5(title, content); -- Create full-text search table using FTS4 CREATE VIRTUAL TABLE articles_fts USING fts4(title, content);
  3. Inserting Data

    sql
    -- Insert data into FTS table INSERT INTO articles_fts (title, content) VALUES ('SQLite Tutorial', 'SQLite is a lightweight database...');
  4. Full-Text Search Queries

    sql
    -- Simple search SELECT * FROM articles_fts WHERE articles_fts MATCH 'SQLite'; -- Phrase search SELECT * FROM articles_fts WHERE articles_fts MATCH '"lightweight database"'; -- Boolean search SELECT * FROM articles_fts WHERE articles_fts MATCH 'SQLite AND database'; -- Prefix search SELECT * FROM articles_fts WHERE articles_fts MATCH 'data*';
  5. FTS5 Advanced Features

    • External Content Table: Associate FTS table with regular table
    sql
    CREATE TABLE articles(id, title, content); CREATE VIRTUAL TABLE articles_fts USING fts5(title, content, content='articles', content_rowid='id');
    • Trigger Auto-Sync: Use triggers to keep FTS table synchronized with source table
    • Ranking Function: Use bm25() function for result ranking
  6. Performance Optimization

    • Create FTS indexes for large documents
    • Use batch inserts to improve performance
    • Regularly optimize FTS tables
    sql
    INSERT INTO articles_fts(articles_fts) VALUES('optimize');
  7. Use Cases

    • Document search systems
    • Log analysis
    • Product search
    • Content management systems
    • Code search

FTS functionality enables SQLite to handle complex text search requirements and is an important tool for building search features.

标签:Sqlite