跳到主要内容

Cloudflare Vector 存储

CloudflareVector 类使用 Cloudflare Vectorize 提供 Vector 搜索。Cloudflare Vectorize 是一项与 Cloudflare 边缘网络集成的 Vector 数据库服务。

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

accountId:

string
Cloudflare 账户 ID

apiToken:

string
具有 Vectorize 权限的 Cloudflare API token

方法
方法的直接链接

createIndex()
createindex的直接链接

indexName:

string
要创建的索引名称

dimension:

number
Vector 维度(必须与你的嵌入模型匹配)

metric?:

'cosine' | 'euclidean' | 'dotproduct'
= cosine
用于相似度搜索的距离度量(dotproduct 会映射为 dot-product)

upsert()
upsert的直接链接

indexName:

string
要向其中执行 upsert 的索引名称

vectors:

number[][]
嵌入 Vector 数组

metadata?:

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

ids?:

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

query()
query的直接链接

indexName:

string
要查询的索引名称

queryVector:

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

topK?:

number
= 10
要返回的结果数量

filter?:

Record<string, any>
查询所用的元数据过滤条件

includeVector?:

boolean
= false
是否在结果中包含 Vector

listIndexes()
listindexes的直接链接

以字符串数组形式返回索引名称。

describeIndex()
describeindex的直接链接

indexName:

string
要描述的索引名称

返回:

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

deleteIndex()
deleteindex的直接链接

indexName:

string
要删除的索引名称

createMetadataIndex()
createmetadataindex的直接链接

为元数据字段创建索引,以启用过滤。

indexName:

string
包含该元数据字段的索引名称

propertyName:

string
要建立索引的元数据字段名称

indexType:

'string' | 'number' | 'boolean'
元数据字段的类型

deleteMetadataIndex()
deletemetadataindex的直接链接

移除元数据字段上的索引。

indexName:

string
包含该元数据字段的索引名称

propertyName:

string
要移除索引的元数据字段名称

listMetadataIndexes()
listmetadataindexes的直接链接

列出某个索引的所有元数据字段索引。

indexName:

string
要列出其元数据索引的索引名称

updateVector()
updatevector的直接链接

更新索引中特定 ID 对应的 Vector 或元数据。

indexName:

string
包含待更新 ID 的索引名称

id:

string
待更新 Vector 或元数据的唯一标识符

update:

{ vector?: number[]; metadata?: Record<string, any>; }
包含待更新 Vector 和/或元数据的对象

deleteVector()
deletevector的直接链接

删除索引中特定 ID 对应的 Vector 及其关联元数据。

indexName:

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

id:

string
待删除 Vector 和元数据的唯一标识符

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

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

interface QueryResult {
id: string
score: number
metadata: Record<string, any>
vector?: number[]
}

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

该存储会抛出可捕获的类型化错误:

try {
await store.query({
indexName: 'index_name',
queryVector: queryVector,
})
} catch (error) {
if (error instanceof VectorStoreError) {
console.log(error.code) // 'connection_failed' | 'invalid_dimension' | etc
console.log(error.details) // Additional error context
}
}

环境变量
环境变量的直接链接

必需的环境变量:

  • CLOUDFLARE_ACCOUNT_ID:你的 Cloudflare 账户 ID
  • CLOUDFLARE_API_TOKEN:具有 Vectorize 权限的 Cloudflare API token