跳至正文內容
TursoDB.cn 獨立社群 · MVCC 並行寫入與每 Agent 獨立庫實戰 閱讀解析 →
Turso Database AI 與 Agent

程式碼索引

程式碼索引(Code Indexing)— Turso 官方文件。

當 AI 寫程式代理能以語意方式搜尋程式碼庫(例如「找出身份驗證邏輯」),而不僅限於檔名或 grep 關鍵字比對時,表現會大幅提升。以 Turso 為底層的程式碼索引可以同時結合針對識別符號的全文搜尋(FTS)與針對向量嵌入的相似度搜尋,且全部封裝在單一嵌入式資料庫中。

本指南介紹如何設計資料表結構與查詢,以建置同時支援全文搜尋(FTS)與向量搜尋的程式碼索引器。

Schema 設計

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 儲存從原始碼檔案擷取出的獨立語意區塊——包括函式、結構體(struct)、類別(class)、實作區塊(impl block)等。每個區塊皆包含 name、signature、程式碼 snippet、行號範圍以及選填的向量 embedding。chunk_key 為唯一識別碼(例如 file_path::kind::name),便於進行 Upsert 操作。
  • 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 程式碼區塊

解析檔案後,將其程式碼區塊以 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 維的儲存空間由 1,536 位元組(float32)大幅縮減至 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 ?;

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 倍,signature 命中的權重為 3 倍。

使用 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)讓排序優先偏向函式與型別名稱,符合開發者最常見的搜尋意圖。
  • 透過 vector8() 儲存 Int8 量化向量:相較於 float32 減少 75% 儲存空間,同時對搜尋品質影響極微。
  • 整體系統運行於單一嵌入式資料庫檔案中,無需依賴任何外部服務。

範例

codemogger 是一個實作此模式的 MCP 伺服器,為 AI 寫程式代理提供高效率的程式碼索引服務。

同步自官方 Turso 文件倉庫 ( tursodatabase/turso-docs · MIT 開源授權) 檢視官方原文 ↗
搜尋
按 Esc 關閉 · 由 Pagefind 靜態索引驅動