> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-TW/llms.txt # DuckDB 向量儲存 DuckDB 儲存實作使用處理程序內分析資料庫 [DuckDB](https://duckdb.org/),提供內嵌式高效能向量搜尋解決方案。它透過 VSS 擴充功能與 HNSW 索引執行向量相似度搜尋,提供不需外部伺服器的輕量高效向量資料庫。 它是 `@mastra/duckdb` 套件的一部分,可搭配中繼資料篩選進行高效率的向量相似度搜尋。 ## 安裝 **npm**: ```bash npm install @mastra/duckdb@latest ``` **pnpm**: ```bash pnpm add @mastra/duckdb@latest ``` **Yarn**: ```bash yarn add @mastra/duckdb@latest ``` **Bun**: ```bash bun add @mastra/duckdb@latest ``` ## 使用方式 ```typescript import { DuckDBVector } from "@mastra/duckdb"; // Create a new vector store instance const store = new DuckDBVector({ id: "duckdb-vector", path: ":memory:", // or './vectors.duckdb' for file persistence }); // Create an index await store.createIndex({ indexName: "myCollection", dimension: 1536, metric: "cosine", }); // Add vectors with metadata const vectors = [[0.1, 0.2, ...], [0.3, 0.4, ...]]; const metadata = [ { text: "first document", category: "A" }, { text: "second document", category: "B" }, ]; await store.upsert({ indexName: "myCollection", vectors, metadata, }); // Query similar vectors const queryVector = [0.1, 0.2, ...]; const results = await store.query({ indexName: "myCollection", queryVector, topK: 10, filter: { category: "A" }, }); // Clean up await store.close(); ``` ## 建構函式選項 **id** (`string`): 向量儲存執行個體的不重複識別碼 **path** (`string`): 資料庫檔案路徑。使用 ':memory:' 代表記憶體內資料庫;若要持久儲存,請使用 './vectors.duckdb' 之類的檔案路徑。 (Default: `':memory:'`) **dimensions** (`number`): 向量嵌入的預設維度 (Default: `1536`) **metric** (`'cosine' | 'euclidean' | 'dotproduct'`): 相似度搜尋的預設距離度量 (Default: `cosine`) ## 方法 ### `createIndex()` 建立新的向量集合,並可選擇使用 HNSW 索引進行快速近似最近鄰搜尋。 **indexName** (`string`): 要建立的索引名稱 **dimension** (`number`): 向量維度大小(必須與嵌入模型相符) **metric** (`'cosine' | 'euclidean' | 'dotproduct'`): 相似度搜尋使用的距離度量 (Default: `cosine`) ### `upsert()` 在索引中新增或更新向量及其中繼資料。 **indexName** (`string`): 要插入資料的索引名稱 **vectors** (`number[][]`): 嵌入向量陣列 **metadata** (`Record[]`): 每個向量的中繼資料 **ids** (`string[]`): 選用的向量 ID(未提供時會自動產生 UUID) ### `query()` 搜尋相似向量,並可選擇套用中繼資料篩選。 **indexName** (`string`): 要搜尋的索引名稱 **queryVector** (`number[]`): 用於尋找相似向量的查詢向量 **topK** (`number`): 要傳回的結果數量 (Default: `10`) **filter** (`Filter`): 使用類 MongoDB 查詢語法的中繼資料篩選條件 **includeVector** (`boolean`): 結果是否包含向量資料 (Default: `false`) ### `describeIndex()` 取得索引的相關資訊。 **indexName** (`string`): 要描述的索引名稱 傳回: ```typescript interface IndexStats { dimension: number count: number metric: 'cosine' | 'euclidean' | 'dotproduct' } ``` ### `deleteIndex()` 刪除索引及其中所有資料。 **indexName** (`string`): 要刪除的索引名稱 ### `listIndexes()` 列出資料庫中的所有向量索引。 傳回:`Promise` ### `updateVector()` 依 ID 或中繼資料篩選條件更新單一向量。必須提供 `id` 或 `filter` 其中一項,但不能同時提供兩者。 **indexName** (`string`): 包含該向量的索引名稱 **id** (`string`): 要更新的向量項目 ID(不可與 filter 同時使用) **filter** (`Record`): 用於識別待更新向量的中繼資料篩選條件(不可與 id 同時使用) **update** (`object`): 包含向量及/或中繼資料的更新資料 **update.vector** (`number[]`): 要更新的新向量資料 **update.metadata** (`Record`): 要更新的新中繼資料 ### `deleteVector()` 依 ID 從索引中刪除指定的向量項目。 **indexName** (`string`): 包含該向量的索引名稱 **id** (`string`): 要刪除的向量項目 ID ### `deleteVectors()` 依 ID 或中繼資料篩選條件刪除多個向量。必須提供 `ids` 或 `filter` 其中一項,但不能同時提供兩者。 **indexName** (`string`): 包含待刪除向量的索引名稱 **ids** (`string[]`): 要刪除的向量 ID 陣列(不可與 filter 同時使用) **filter** (`Record`): 用於識別待刪除向量的中繼資料篩選條件(不可與 ids 同時使用) ### `close()` 關閉資料庫連線並釋放資源。 ```typescript await store.close() ``` ## 回應型別 查詢結果會以下列格式傳回: ```typescript interface QueryResult { id: string score: number metadata: Record vector?: number[] // Only included if includeVector is true } ``` ## 篩選運算子 DuckDB 向量儲存支援類 MongoDB 的篩選運算子: | 類別 | 運算子 | | -- | ------------------------------------------ | | 比較 | `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte` | | 邏輯 | `$and`, `$or`, `$not`, `$nor` | | 陣列 | `$in`, `$nin` | | 元素 | `$exists` | | 文字 | `$contains` | ### 篩選範例 ```typescript // Allegato operators const results = await store.query({ indexName: "docs", queryVector: [...], filter: { $and: [ { category: "electronics" }, { price: { $gte: 100, $lte: 500 } }, ], }, }); // Nested field access const results = await store.query({ indexName: "docs", queryVector: [...], filter: { "user.profile.tier": "premium" }, }); ``` ## 距離度量 | 度量 | 說明 | 分數解讀 | 適用情境 | | ------------ | ----- | ---------- | ---------- | | `cosine` | 餘弦相似度 | 0–1(1 最相似) | 文字嵌入、正規化向量 | | `euclidean` | L2 距離 | 0–∞(0 最相似) | 影像嵌入、空間資料 | | `dotproduct` | 內積 | 越高越相似 | 向量大小很重要時 | ## 錯誤處理 此儲存會針對不同失敗情況擲回特定錯誤: ```typescript try { await store.query({ indexName: 'my-collection', queryVector: queryVector, }) } catch (error) { if (error.message.includes('not found')) { console.error('The specified index does not exist') } else if (error.message.includes('Invalid identifier')) { console.error('Index name contains invalid characters') } else { console.error('Vector store error:', error.message) } } ``` 常見錯誤情況包括: - 索引名稱格式無效 - 找不到索引/資料表 - 查詢向量與索引的維度不符 - 刪除/更新操作中的 filter 或 ids 陣列為空 - 違反互斥限制(同時提供 `id` 與 `filter`) ## 使用情境 ### 內嵌式語意搜尋 建置支援離線使用的 AI 應用程式,並讓語意搜尋完全在處理程序內執行: ```typescript const store = new DuckDBVector({ id: 'offline-search', path: './search.duckdb', }) ``` ### 本機 RAG 管線 在本機處理敏感文件,無須將資料傳送至雲端向量資料庫: ```typescript const store = new DuckDBVector({ id: 'private-rag', path: './confidential.duckdb', dimensions: 1536, }) ``` ### 開發與測試 無須基礎架構即可快速製作向量搜尋功能原型: ```typescript const store = new DuckDBVector({ id: 'dev-store', path: ':memory:', // Fast in-memory for tests }) ``` ## 相關內容 - [中繼資料篩選條件](https://mastra.zisheng.pro/zh-TW/reference/rag/metadata-filters) - [DuckDB 文件](https://duckdb.org/docs/)