跳至主要內容

DuckDB 向量儲存

DuckDB 儲存實作使用程序內分析資料庫 DuckDB,提供嵌入式高效能向量搜尋解決方案。它使用 VSS 擴充功能配合 HNSW 索引執行向量相似度搜尋,提供無需外部伺服器的輕量高效向量資料庫。

它是 @mastra/duckdb 套件的一部分,提供支援元資料篩選的高效向量相似度搜尋。

安裝
安裝 的直接連結

npm install @mastra/duckdb@latest

用法
用法 的直接連結

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:'
資料庫檔案路徑。記憶體內資料庫請使用 ':memory:';如要持久儲存,請使用檔案路徑,例如 './vectors.duckdb'。

dimensions?:

number
= 1536
向量嵌入的預設維度

metric?:

'cosine' | 'euclidean' | 'dotproduct'
= cosine
相似度搜尋的預設距離度量

方法
方法 的直接連結

createIndex()
createindex 的直接連結

建立新的向量集合,並可選擇加入 HNSW 索引,以進行快速近似最近鄰搜尋。

indexName:

string
要建立的索引名稱

dimension:

number
向量維度大小(必須與嵌入模型相符)

metric?:

'cosine' | 'euclidean' | 'dotproduct'
= cosine
相似度搜尋所使用的距離度量

upsert()
upsert 的直接連結

在索引中加入或更新向量及其元資料。

indexName:

string
要插入資料的索引名稱

vectors:

number[][]
嵌入向量陣列

metadata?:

Record<string, any>[]
每個向量的元資料

ids?:

string[]
可選的向量 ID(如未提供則自動產生 UUID)

query()
query 的直接連結

搜尋相似向量,並可選擇使用元資料篩選。

indexName:

string
要搜尋的索引名稱

queryVector:

number[]
用來尋找相似向量的查詢向量

topK?:

number
= 10
要傳回的結果數目

filter?:

Filter
使用類似 MongoDB 查詢語法的元資料篩選條件

includeVector?:

boolean
= false
是否在結果中包含向量資料

describeIndex()
describeindex 的直接連結

取得索引的資料。

indexName:

string
要取得資料的索引名稱

傳回:

interface IndexStats {
dimension: number
count: number
metric: 'cosine' | 'euclidean' | 'dotproduct'
}

deleteIndex()
deleteindex 的直接連結

刪除索引及其所有資料。

indexName:

string
要刪除的索引名稱

listIndexes()
listindexes 的直接連結

列出資料庫中的所有向量索引。

傳回:Promise<string[]>

updateVector()
updatevector 的直接連結

按 ID 或元資料篩選條件更新單一向量。必須提供 idfilter,但不可同時提供兩者。

indexName:

string
包含該向量的索引名稱

id?:

string
要更新的向量項目 ID(與 filter 互斥)

filter?:

Record<string, any>
用來識別待更新向量的元資料篩選條件(與 id 互斥)

update:

object
包含向量及/或元資料的更新資料

update.vector?:

number[]
要更新的新向量資料

update.metadata?:

Record<string, any>
要更新的新元資料

deleteVector()
deletevector 的直接連結

按 ID 從索引刪除指定的向量項目。

indexName:

string
包含該向量的索引名稱

id:

string
要刪除的向量項目 ID

deleteVectors()
deletevectors 的直接連結

按 ID 或元資料篩選條件刪除多個向量。必須提供 idsfilter,但不可同時提供兩者。

indexName:

string
包含待刪除向量的索引名稱

ids?:

string[]
待刪除的向量 ID 陣列(與 filter 互斥)

filter?:

Record<string, any>
用來識別待刪除向量的元資料篩選條件(與 ids 互斥)

close()
close 的直接連結

關閉資料庫連線並釋放資源。

await store.close()

回應類型
回應類型 的直接連結

查詢結果會以下列格式傳回:

interface QueryResult {
id: string
score: number
metadata: Record<string, any>
vector?: number[] // Only included if includeVector is true
}

篩選運算子
篩選運算子 的直接連結

DuckDB 向量儲存支援類似 MongoDB 的篩選運算子:

類別運算子
比較$eq, $ne, $gt, $gte, $lt, $lte
邏輯$and, $or, $not, $nor
陣列$in, $nin
元素$exists
文字$contains

篩選範例
篩選範例 的直接連結

// 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 = 最相似)文字嵌入、正規化向量
euclideanL2 距離0–∞(0 = 最相似)圖像嵌入、空間資料
dotproduct內積數值越高越相似向量大小會影響結果時

錯誤處理
錯誤處理 的直接連結

此向量儲存會針對不同失敗情況擲回特定錯誤:

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 陣列為空
  • 違反互斥條件(同時提供 idfilter

使用案例
使用案例 的直接連結

建構支援離線操作的 AI 應用程式,其語意搜尋完全在程序內執行:

const store = new DuckDBVector({
id: 'offline-search',
path: './search.duckdb',
})

本機 RAG 管線
本機 RAG 管線 的直接連結

在本機處理敏感文件,無需將資料傳送至雲端向量資料庫:

const store = new DuckDBVector({
id: 'private-rag',
path: './confidential.duckdb',
dimensions: 1536,
})

開發與測試
開發與測試 的直接連結

無需基礎設施即可快速製作向量搜尋功能原型:

const store = new DuckDBVector({
id: 'dev-store',
path: ':memory:', // Fast in-memory for tests
})