SQLite FTS4

1.0.3 · active · verified Mon Apr 13

sqlite-fts4 is a Python library providing custom SQLite functions designed for efficient full-text search (FTS4) ranking and decoding. It offers functions like `rank_score`, `rank_bm25`, `decode_matchinfo`, and `annotate_matchinfo` to enhance the utility of SQLite's built-in FTS4 extension. The library, currently at version 1.0.3, is actively maintained with a focus on stability and compatibility, addressing specific issues such as big-endian system support.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to establish an SQLite connection, register the `sqlite-fts4` custom functions, create an FTS4 virtual table, insert data, and then perform a full-text search with relevance ranking using `rank_score`.

import sqlite3
from sqlite_fts4 import register_functions

# Connect to an in-memory SQLite database
conn = sqlite3.connect(':memory:')

# Register all custom FTS4 functions
register_functions(conn)

# Create an FTS4 virtual table
conn.execute("CREATE VIRTUAL TABLE docs USING fts4(title, body);")

# Insert some data
conn.execute("INSERT INTO docs (title, body) VALUES (?, ?)", ("Hello World", "This is a test document with some words."))
conn.execute("INSERT INTO docs (title, body) VALUES (?, ?)", ("Python SQLite FTS4", "Exploring full-text search capabilities in Python with SQLite FTS4."))

# Perform a search and rank results using rank_score
# 'pcx' is required for rank_score()
cursor = conn.execute(
    "SELECT title, body, rank_score(matchinfo(docs, 'pcx')) as score FROM docs WHERE docs MATCH ? ORDER BY score DESC",
    ("python search",)
)

for row in cursor.fetchall():
    print(f"Title: {row[0]}, Score: {row[2]:.2f}")

conn.close()

view raw JSON →