跳到主要内容

libSQL Vector 存储

libSQL 存储实现通过 libSQL(带 Vector 扩展的 SQLite 分支)以及带 Vector 扩展的 Turso 提供与 SQLite 兼容的 Vector 搜索,是一种轻量且高效的 Vector 数据库解决方案。 它属于 @mastra/libsql 包,可提供支持元数据筛选的高效 Vector 相似度搜索。

安装
安装的直接链接

npm install @mastra/libsql@latest

用法
用法的直接链接

import { LibSQLVector } from "@mastra/libsql";

// Create a new vector store instance
const store = new LibSQLVector({
id: 'libsql-vector',
url: process.env.DATABASE_URL,
// Optional: for Turso cloud databases
authToken: process.env.DATABASE_AUTH_TOKEN,
});

// Create an index
await store.createIndex({
indexName: "myCollection",
dimension: 1536,
});

// 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, // top K results
filter: { category: "A" } // optional metadata filter
});

构造函数选项
构造函数选项的直接链接

url:

string
libSQL 数据库 URL。内存数据库使用 ':memory:',本地文件使用 'file:dbname.db',也可使用 'libsql://your-database.turso.io' 之类的 libSQL 兼容连接字符串。

authToken?:

string
Turso 云数据库的身份验证 token

syncUrl?:

string
数据库复制 URL(Turso 专用)

syncInterval?:

number
数据库同步间隔,以毫秒为单位(Turso 专用)

方法
方法的直接链接

createIndex()
createindex的直接链接

创建新的 Vector 集合。索引名称必须以字母或下划线开头,并且只能包含字母、数字和下划线字符。维度必须是正整数。

indexName:

string
要创建的索引名称

dimension:

number
Vector 维度大小(必须与嵌入模型匹配)

metric?:

'cosine' | 'euclidean' | 'dotproduct'
= cosine
相似度搜索使用的距离度量。注意:libSQL 目前仅支持余弦相似度。

upsert()
upsert的直接链接

在索引中添加或更新 Vector 及其元数据。该方法使用事务确保所有 Vector 以原子方式插入;如果任何一次插入失败,整个操作都会回滚。

indexName:

string
要插入数据的索引名称

vectors:

number[][]
嵌入 Vector 数组

metadata?:

Record<string, any>[]
每个 Vector 的元数据

ids?:

string[]
可选的 Vector ID(未提供时自动生成)

query()
query的直接链接

搜索相似 Vector,并可选择使用元数据筛选。

indexName:

string
要搜索的索引名称

queryVector:

number[]
用于查找相似 Vector 的查询 Vector

topK?:

number
= 10
要返回的结果数量

filter?:

Filter
元数据筛选条件

includeVector?:

boolean
= false
结果中是否包含 Vector 数据

minScore?:

number
= 0
最低相似度分数阈值

describeIndex()
describeindex的直接链接

获取索引信息。

indexName:

string
要描述的索引名称

返回:

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

deleteIndex()
deleteindex的直接链接

删除索引及其中的所有数据。

indexName:

string
要删除的索引名称

listIndexes()
listindexes的直接链接

列出数据库中的所有 Vector 索引。

返回:Promise<string[]>

truncateIndex()
truncateindex的直接链接

删除索引中的所有 Vector,同时保留索引结构。

indexName:

string
要清空的索引名称

updateVector()
updatevector的直接链接

按 ID 或元数据筛选条件更新单个 Vector。必须提供 idfilter,但不能同时提供两者。

indexName:

string
包含该 Vector 的索引名称

id?:

string
要更新的 Vector 条目 ID(与 filter 互斥)

filter?:

Record<string, any>
用于识别待更新 Vector 的元数据筛选条件(与 id 互斥)

update:

object
包含 Vector 和/或元数据的更新数据

update.vector?:

number[]
要更新的新 Vector 数据

update.metadata?:

Record<string, any>
要更新的新元数据

deleteVector()
deletevector的直接链接

按 ID 从索引中删除指定的 Vector 条目。

indexName:

string
包含该 Vector 的索引名称

id:

string
要删除的 Vector 条目 ID

deleteVectors()
deletevectors的直接链接

按 ID 或元数据筛选条件删除多个 Vector。必须提供 idsfilter,但不能同时提供两者。

indexName:

string
包含待删除 Vector 的索引名称

ids?:

string[]
要删除的 Vector ID 数组(与 filter 互斥)

filter?:

Record<string, any>
用于识别待删除 Vector 的元数据筛选条件(与 ids 互斥)

响应类型
响应类型的直接链接

查询结果以以下格式返回:

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

错误处理
错误处理的直接链接

该存储会针对不同的失败情况抛出特定错误:

try {
await store.query({
indexName: 'my-collection',
queryVector: queryVector,
})
} catch (error) {
// Handle specific error cases
if (error.message.includes('Invalid index name format')) {
console.error(
'Index name must start with a letter/underscore and contain only alphanumeric characters',
)
} else if (error.message.includes('Table not found')) {
console.error('The specified index does not exist')
} else {
console.error('Vector store error:', error.message)
}
}

常见错误情况包括:

  • 索引名称格式无效
  • Vector 维度无效
  • 未找到表/索引
  • 数据库连接问题
  • upsert 期间事务失败

用法示例
用法示例的直接链接

使用 fastembed 的本地嵌入
使用 fastembed 的本地嵌入的直接链接

嵌入是 memory 的 semanticRecall 用来按语义(而非关键词)检索相关消息的数值 Vector。此设置使用 @mastra/fastembed 生成 Vector 嵌入。

安装 fastembed 以开始使用:

npm install @mastra/fastembed@latest

将以下内容添加到 Agent:

src/mastra/agents/example-libsql-agent.ts
import { Memory } from '@mastra/memory'
import { Agent } from '@mastra/core/agent'
import { LibSQLStore, LibSQLVector } from '@mastra/libsql'
import { fastembed } from '@mastra/fastembed'

export const libsqlAgent = new Agent({
id: 'libsql-agent',
name: 'libSQL Agent',
instructions:
'You are an AI agent with the ability to automatically recall memories from previous interactions.',
model: 'openai/gpt-5.6-sol',
memory: new Memory({
storage: new LibSQLStore({
id: 'libsql-agent-storage',
url: 'file:libsql-agent.db',
}),
vector: new LibSQLVector({
id: 'libsql-agent-vector',
url: 'file:libsql-agent.db',
}),
embedder: fastembed,
options: {
lastMessages: 10,
semanticRecall: {
topK: 3,
messageRange: 2,
},
generateTitle: true, // Explicitly enable automatic title generation
},
}),
})