跳至主要內容

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
})