代码索引
结合 Turso 全文检索(FTS)与向量相似度检索构建语义代码索引引擎。
相比仅依赖文件名或 grep 关键词查找,如果 AI 编程智能体能够按语义搜索代码库(例如“查找身份认证逻辑”),其工作效率会大幅提升。基于 Turso 构建的代码索引可以在单个嵌入式数据库中同时结合标识符全文检索与向量嵌入相似度检索。
本指南介绍如何设计表结构并编写查询语句,以构建同时支持全文检索(FTS)和向量检索的代码索引器。
表结构设计
CREATE TABLE IF NOT EXISTS codebases (
id INTEGER PRIMARY KEY AUTOINCREMENT,
root_path TEXT NOT NULL UNIQUE,
name TEXT NOT NULL DEFAULT '',
indexed_at INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS chunks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
codebase_id INTEGER NOT NULL REFERENCES codebases(id),
file_path TEXT NOT NULL,
chunk_key TEXT NOT NULL UNIQUE,
language TEXT NOT NULL,
kind TEXT NOT NULL,
name TEXT NOT NULL DEFAULT '',
signature TEXT NOT NULL DEFAULT '',
snippet TEXT NOT NULL,
start_line INTEGER NOT NULL,
end_line INTEGER NOT NULL,
file_hash TEXT NOT NULL,
indexed_at INTEGER NOT NULL,
embedding F8_BLOB(384),
embedding_model TEXT DEFAULT ''
);
CREATE TABLE IF NOT EXISTS indexed_files (
id INTEGER PRIMARY KEY AUTOINCREMENT,
codebase_id INTEGER NOT NULL REFERENCES codebases(id),
file_path TEXT NOT NULL,
file_hash TEXT NOT NULL,
chunk_count INTEGER NOT NULL DEFAULT 0,
indexed_at INTEGER NOT NULL,
UNIQUE(codebase_id, file_path)
);
各表协同方式
codebases用于登记每个项目根目录,单个数据库文件即可索引多个代码库。chunks存储从源文件中提取的语义代码块——例如函数、结构体、类、impl代码块等。每个代码块包含name、signature、代码片段snippet、起止行号以及可选的向量embedding。chunk_key是用于 upsert 更新的唯一标识(例如file_path::kind::name)。indexed_files追踪已索引的文件列表及其内容哈希值,实现增量重建索引——仅重新处理发生变动的文件。
连接数据库
使用 FTS 索引特性需要在连接时开启实验性选项:
import { connect } from "@tursodatabase/database";
const db = await connect(".index/code.db", {
experimental: ["index_method"],
});
await db.exec(SCHEMA);
experimental: ["index_method"] 选项用于启用 Turso 的 USING fts 索引语法以及 fts_match() / fts_score() 函数。
索引源文件
插入或更新代码块(Upsert)
解析源文件后,将提取出的代码块写入数据库。发生冲突更新时将 embedding 置为 NULL,以便在代码内容发生变化时触发重新生成向量嵌入:
INSERT INTO chunks (codebase_id, file_path, chunk_key, language, kind, name,
signature, snippet, start_line, end_line, file_hash, indexed_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(chunk_key) DO UPDATE SET
language = excluded.language,
kind = excluded.kind,
name = excluded.name,
signature = excluded.signature,
snippet = excluded.snippet,
start_line = excluded.start_line,
end_line = excluded.end_line,
file_hash = excluded.file_hash,
indexed_at = excluded.indexed_at,
embedding = NULL,
embedding_model = '';
记录已索引文件
INSERT INTO indexed_files (codebase_id, file_path, file_hash, chunk_count, indexed_at)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(codebase_id, file_path) DO UPDATE SET
file_hash = excluded.file_hash,
chunk_count = excluded.chunk_count,
indexed_at = excluded.indexed_at;
跳过未变更文件
解析文件之前,先查询该文件的内容哈希是否发生变化:
SELECT file_hash FROM indexed_files WHERE codebase_id = ? AND file_path = ?;
若哈希值一致,则直接跳过,无需重复解析。
存储向量嵌入
可使用 Turso 的 vector8() 函数将向量以 int8 量化形式存储,使 384 维向量的存储体积从 float32 的 1,536 字节压缩至 395 字节:
UPDATE chunks SET embedding = vector8(?), embedding_model = ? WHERE chunk_key = ?;
vector8() 接收经 JSON 序列化的浮点数组,量化过程由 Turso 内部自动完成。
查询尚未生成向量或需要按新模型重新计算向量的代码块:
SELECT chunk_key, name, signature, file_path, kind, snippet
FROM chunks
WHERE codebase_id = ? AND (embedding IS NULL OR embedding_model != ?)
LIMIT ?;
全文检索(FTS)
Turso 提供支持加权 BM25 评分的内置 FTS 索引,独立于 SQLite 原有的 fts5 虚表机制。
创建 FTS 索引
为每个代码库创建一张 FTS 表,并从 chunks 表中导入数据:
-- Create the FTS table
CREATE TABLE IF NOT EXISTS fts_1 (
chunk_id INTEGER NOT NULL REFERENCES chunks(id) ON DELETE CASCADE,
name TEXT NOT NULL DEFAULT '',
signature TEXT NOT NULL DEFAULT ''
);
-- Populate from chunks
INSERT INTO fts_1 (chunk_id, name, signature)
SELECT id, name, signature FROM chunks WHERE codebase_id = 1;
-- Create the FTS index with weighted columns
CREATE INDEX IF NOT EXISTS idx_fts_1 ON fts_1
USING fts (name, signature)
WITH (
tokenizer = 'default',
weights = 'name=5.0,signature=3.0'
);
weights 参数用于控制各字段在 BM25 评分中的权重——在此示例中,函数/类型名称(name)的匹配权重为 5.0,签名(signature)的匹配权重为 3.0。
执行 FTS 检索
SELECT chunk_id, fts_score(name, signature, ?1) AS score
FROM fts_1
WHERE fts_match(name, signature, ?1)
ORDER BY score DESC
LIMIT ?;
再根据命中的 chunk_id 查询完整的代码块信息:
SELECT chunk_key, file_path, name, kind, signature, snippet, start_line, end_line
FROM chunks WHERE id = ?;
向量检索
对于语义或自然语言查询,可使用余弦距离进行向量检索:
SELECT chunk_key, file_path, name, kind, signature, snippet, start_line, end_line,
vector_distance_cos(embedding, vector8(?)) AS distance
FROM chunks
WHERE embedding IS NOT NULL
ORDER BY distance ASC
LIMIT ?;
余弦相似度分数可通过 1 - distance 计算得到。
混合检索
为了获得更佳的召回效果,建议结合倒数排名融合算法(Reciprocal Rank Fusion,简称 RRF)融合两种检索结果:分别执行 FTS 查询与向量查询,再在应用层合并排序:
// Run both searches
const ftsResults = await ftsSearch(query, limit);
const vecResults = await vectorSearch(queryEmbedding, limit);
// Reciprocal Rank Fusion
const k = 60; // RRF constant
const scores = new Map();
ftsResults.forEach((r, i) => {
const key = r.chunk_key;
scores.set(key, (scores.get(key) || 0) + 1 / (k + i + 1));
});
vecResults.forEach((r, i) => {
const key = r.chunk_key;
scores.set(key, (scores.get(key) || 0) + 1 / (k + i + 1));
});
// Sort by combined score
const merged = [...scores.entries()]
.sort((a, b) => b[1] - a[1])
.slice(0, limit);
清理已删除文件
当代码库中有文件被删除时,清理对应的代码块与文件索引记录:
DELETE FROM chunks WHERE codebase_id = ? AND file_path = ?;
DELETE FROM indexed_files WHERE codebase_id = ? AND file_path = ?;
清理过期数据后,重建 FTS 表以保证索引一致性:
DROP TABLE IF EXISTS fts_1;
-- Then recreate and repopulate as shown above
核心设计要点
- 增量索引:依托文件哈希对比,仅重新解析和嵌入发生变动的文件,即便面对大型代码库也能保持高效更新。
- 双模式检索:FTS 擅长精确查找标识符与关键字,向量检索擅长理解语义与自然语言查询,混合检索兼得二者之长。
- 加权 FTS:通过
name=5.0, signature=3.0权重配置,优先突出函数名与类型名匹配,贴合开发者的日常检索习惯。 - Int8 量化向量:借助
vector8()将向量存储体积相比 float32 缩减 75%,且几乎不影响检索精度。 - 整套索引方案完全运行在单个嵌入式数据库文件中,无需任何外部服务。
参考示例
codemogger 是一个基于该模式实现的 MCP 服务器,可作为 AI 编程智能体的代码索引工具使用。