关于 cloudflare-vectorize
cloudflare-vectorize 是面向使用 Cloudflare Workers 构建向量搜索和 RAG 应用的开发者指南,涵盖索引、向量操作、元数据筛选、嵌入流程及 V2 迁移。
主要功能
- 01索引与向量操作
- 02语义搜索和元数据筛选
- 03RAG 与文档导入模式
- 04Workers AI 和 OpenAI 嵌入示例
- 05Vectorize V2 配置与迁移指南
适用场景
- 01在 Worker 中构建语义搜索
- 02为 RAG 创建检索流程
- 03导入并分块处理文档
- 04将 Vectorize 索引从 V1 迁移至 V2
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ ovachiever/ droid-tings --skill cloudflare-vectorize安装后在 Claude Code 中输入/cloudflare-vectorize确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
README.md.claude-plugin/plugin.jsonreferences/embedding-models.mdindex-operations.mdintegration-openai-embeddings.mdintegration-workers-ai-bge-base.mdmetadata-guide.mdvector-operations.mdwrangler-commands.mdtemplates/basic-search.tsdocument-ingestion.tsmetadata-filtering.tsrag-chat.ts详细介绍
Cloudflare Vectorize
Cloudflare Vectorize 完整实现指南——借助 Cloudflare Workers 构建语义搜索、RAG(检索增强生成)和 AI 驱动应用的全球分布式向量数据库。
状态:已可用于生产环境 ✅ 最近更新:2025-10-21 依赖项:cloudflare-worker-base(用于 Worker 设置)、cloudflare-workers-ai(用于生成嵌入) 最新版本:[email protected]、@cloudflare/[email protected] 节省 Token:约 65% 避免的错误:8 节省的开发时间:约 3 小时
此技能提供的功能
核心能力
- ✅ 索引管理:创建、配置和管理向量索引
- ✅ 向量操作:插入、更新、查询、删除和列出向量
- ✅ 元数据过滤:高级过滤,每个索引支持 10 个元数据索引
- ✅ 语义搜索:使用余弦、欧几里得或点积指标查找相似向量
- ✅ RAG 模式:完整的检索增强生成工作流
- ✅ Workers AI 集成:使用 @cf/baai/bge-base-en-v1.5 原生生成嵌入
- ✅ OpenAI 集成:支持 text-embedding-3-small/large 模型
- ✅ 文档处理:文本分块和批量导入流水线
包含的模板
- basic-search.ts - 使用 Workers AI 的简单向量搜索
- rag-chat.ts - 支持上下文检索的完整 RAG 聊天机器人
- document-ingestion.ts - 文档分块和嵌入流水线
- metadata-filtering.ts - 高级过滤模式
⚠️ Vectorize V2 重大变更(2024 年 9 月)
重要:Vectorize V2 于 2024 年 9 月正式发布,并带来了重大不兼容变更。
V2 的变更内容
性能提升:
- 索引容量:每个索引 200,000 → 500 万个向量
- 查询延迟:中位数 549ms → 31ms(快 18 倍)
- TopK 限制:每次查询 20 → 100 个结果
- 规模限制:每个账户 100 → 50,000 个索引
- 命名空间限制:每个索引 100 → 50,000 个命名空间
不兼容的 API 变更:
-
异步变更操作 - 现在所有变更操作都是异步的:
// V2: Returns mutationId const result = await env.VECTORIZE_INDEX.insert(vectors); console.log(result.mutationId); // "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" // Vector inserts/deletes may take a few seconds to be reflected -
returnMetadata 参数 - 从布尔值改为字符串枚举:
// ❌ V1 (deprecated) { returnMetadata: true } // ✅ V2 (required) { returnMetadata: 'all' | 'indexed' | 'none' } -
插入前必须创建元数据索引:
- V2 要求在插入向量之前创建元数据索引
- 在元数据索引创建前添加的向量不会被索引
- 创建元数据索引后,必须重新 upsert 向量
V1 弃用时间表:
- 2024 年 12 月:无法再创建 V1 索引
- 现有 V1 索引:继续正常工作(其他操作不受影响)
- 迁移:对 V1 操作使用
wrangler vectorize --deprecated-v1标志
所需的 Wrangler 版本:
- 最低版本:V2 命令需使用 [email protected]
- 推荐版本:[email protected]+(最新版本)
检查变更操作状态
// Get index info to check last mutation processed
const info = await env.VECTORIZE_INDEX.describe();
console.log(info.mutationId); // Last mutation ID
console.log(info.processedUpToMutation); // Last processed timestamp
关键设置规则
⚠️ 插入向量前必须完成
# 1. Create the index with FIXED dimensions and metric
npx wrangler vectorize create my-index \
--dimensions=768 \
--metric=cosine
# 2. Create metadata indexes IMMEDIATELY (before inserting vectors!)
npx wrangler vectorize create-metadata-index my-index \
--property-name=category \
--type=string
npx wrangler vectorize create-metadata-index my-index \
--property-name=timestamp \
--type=number
原因:插入向量前必须创建元数据索引。在元数据索引创建前添加的向量,无法按该属性进行过滤。
索引配置(之后无法更改)
# Dimensions MUST match your embedding model output:
# - Workers AI @cf/baai/bge-base-en-v1.5: 768 dimensions
# - OpenAI text-embedding-3-small: 1536 dimensions
# - OpenAI text-embedding-3-large: 3072 dimensions
# Metrics determine similarity calculation:
# - cosine: Best for normalized embeddings (most common)
# - euclidean: Absolute distance between vectors
# - dot-product: For non-normalized vectors
Wrangler 配置
wrangler.jsonc:
{
"name": "my-vectorize-worker",
"main": "src/index.ts",
"compatibility_date": "2025-10-21",
"vectorize": [
{
"binding": "VECTORIZE_INDEX",
"index_name": "my-index"
}
],
"ai": {
"binding": "AI"
}
}
TypeScript 类型
export interface Env {
VECTORIZE_INDEX: VectorizeIndex;
AI: Ai;
}
interface VectorizeVector {
id: string;
values: number[] | Float32Array | Float64Array;
namespace?: string;
metadata?: Record<string, string | number | boolean | string[]>;
}
interface VectorizeMatches {
matches: Array<{
id: string;
score: number;
values?: number[];
metadata?: Record<string, any>;
namespace?: string;
}>;
count: number;
}
元数据过滤运算符(V2)
Vectorize V2 支持使用范围查询进行高级元数据过滤:
// Equality (implicit $eq)
{ category: "docs" }
// Not equals
{ status: { $ne: "archived" } }
// In/Not in arrays
{ category: { $in: ["docs", "tutorials"] } }
{ category: { $nin: ["deprecated", "draft"] } }
// Range queries (numbers) - NEW in V2
{ timestamp: { $gte: 1704067200, $lt: 1735689600 } }
// Range queries (strings) - prefix searching
{ url: { $gte: "/docs/workers", $lt: "/docs/workersz" } }
// Nested metadata with dot notation
{ "author.id": "user123" }
// Multiple conditions (implicit AND)
{ category: "docs", language: "en", "metadata.published": true }
元数据最佳实践
1. 基数注意事项
低基数(适合 $eq 过滤):
// Few unique values - efficient filtering
metadata: {
category: "docs", // ~10 categories
language: "en", // ~5 languages
published: true // 2 values (boolean)
}
高基数(避免用于范围查询):
// Many unique values - avoid large range scans
metadata: {
user_id: "uuid-v4...", // Millions of unique values
timestamp_ms: 1704067200123 // Use seconds instead
}
2. 元数据限制
- 最多 10 个元数据索引:每个 Vectorize 索引
- 每个向量的元数据最多 10 KiB
- 字符串索引:前 64 字节(UTF-8)
- 数字索引:Float64 精度
- 过滤器大小:最多 2048 字节(紧凑 JSON)
3. 键限制
// ❌ INVALID metadata keys
metadata: {
"": "value", // Empty key
"user.name": "John", // Contains dot (reserved for nesting)
"$admin": true, // Starts with $
"key\"with\"quotes": 1 // Contains quotes
}
// ✅ VALID metadata keys
metadata: {
"user_name": "John",
"isAdmin": true,
"nested": { "allowed": true } // Access as "nested.allowed" in filters
}
常见错误和解决方案
错误 1:插入向量后才创建元数据索引
Problem: Filtering doesn't work on existing vectors
Solution: Delete and re-insert vectors OR create metadata indexes BEFORE inserting
错误 2:维度不匹配
Problem: "Vector dimensions do not match index configuration"
Solution: Ensure embedding model output matches index dimensions:
- Workers AI bge-base: 768
- OpenAI small: 1536
- OpenAI large: 3072
错误 3:无效的元数据键
Problem: "Invalid metadata key"
Solution: Keys cannot:
- Be empty
- Contain . (dot)
- Contain " (quote)
- Start with $ (dollar sign)
错误 4:过滤器过大
Problem: "Filter exceeds 2048 bytes"
Solution: Simplify filter or split into multiple queries
错误 5:对高基数执行范围查询
Problem: Slow queries or reduced accuracy
Solution: Use lower cardinality fields for range queries, or use seconds instead of milliseconds for timestamps
错误 6:混淆插入和 Upsert
Problem: Updates not reflecting in index
Solution: Use upsert() to overwrite existing vectors, not insert()
错误 7:缺少绑定
Problem: "VECTORIZE_INDEX is not defined"
Solution: Add [[vectorize]] binding to wrangler.jsonc
错误 8:混淆命名空间和元数据
Problem: Unclear when to use namespace vs metadata filtering
Solution:
- Namespace: Partition key, applied BEFORE metadata filters
- Metadata: Flexible key-value filtering within namespace
错误 9:V2 异步变更时序(V2 新增)
Problem: Inserted vectors not immediately queryable
Solution: V2 mutations are asynchronous - vectors may take a few seconds to be reflected
- Use mutationId to track mutation status
- Check env.VECTORIZE_INDEX.describe() for processedUpToMutation timestamp
错误 10:V1 的 returnMetadata 布尔值(V2 中存在破坏性变更)
Problem: "returnMetadata must be 'all', 'indexed', or 'none'"
Solution: V2 changed returnMetadata from boolean to string enum:
- ❌ V1: { returnMetadata: true }
- ✅ V2: { returnMetadata: 'all' }
V2 迁移检查清单
如果从 V1 迁移到 V2:
- ✅ 将 wrangler 更新到 3.71.0+(
npm install -g wrangler@latest) - ✅ 创建新的 V2 索引(无法将 V1 升级为 V2)
- ✅ 在插入向量之前创建元数据索引
- ✅ 将
returnMetadata布尔值改为字符串枚举('all'、'indexed'、'none') - ✅ 处理异步变更(预期响应中包含
mutationId) - ✅ 使用 V2 限制进行测试(topK 最高为 100,每个索引最多 5M 个向量)
- ✅ 更新异步行为的错误处理
V1 弃用:
- 2024 年 12 月之后:无法创建新的 V1 索引
- 现有 V1 索引:继续正常工作
- 使用
wrangler vectorize --deprecated-v1执行 V1 操作
官方文档
- Vectorize V2 文档:https://developers.cloudflare.com/vectorize/
- V2 更新日志:https://developers.cloudflare.com/vectorize/platform/changelog/
- 从 V1 迁移到 V2:https://developers.cloudflare.com/vectorize/reference/transition-vectorize-legacy/
- 元数据筛选:https://developers.cloudflare.com/vectorize/reference/metadata-filtering/
- Workers AI 模型:https://developers.cloudflare.com/workers-ai/models/
状态:可用于生产环境 ✅(Vectorize V2 正式发布 — 2024 年 9 月) 最后更新:2025-11-22 节省的 Token:约 70% 避免的错误:10 个(包括 V2 破坏性变更)