mcpField
C
cloudflare-vectorize

cloudflare-vectorize

github.com/jackspace数据与数据库1638 次安装12 周前更新
代码仓库

关于 cloudflare-vectorize

面向 Cloudflare Workers 开发者的 Cloudflare Vectorize 实现指南,涵盖向量索引、检索和 RAG 工作流,并提供 TypeScript 模板及配置参考。

主要功能

  1. 01管理向量索引与向量
  2. 02相似度搜索和元数据筛选
  3. 03Workers AI 与 OpenAI 嵌入
  4. 04文档分块与批量导入
  5. 05提供搜索和 RAG 模板

适用场景

  1. 01为文档或内容构建语义搜索
  2. 02实现带上下文检索的 RAG 聊天
  3. 03按元数据筛选相似向量

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/jackspace/claudeskillz --skill cloudflare-vectorize

安装后在 Claude Code 中输入/cloudflare-vectorize确认已加载。

附带文件README.mdSKILL.json

详细介绍

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 模型
  • ✅ 文档处理:文本分块和批量摄取管道
包含的模板
  1. basic-search.ts - 使用 Workers AI 的简单向量搜索
  2. rag-chat.ts - 支持上下文检索的完整 RAG 聊天机器人
  3. document-ingestion.ts - 文档分块和嵌入管道
  4. metadata-filtering.ts - 高级过滤示例

关键设置规则

⚠️ 插入向量前必须执行
# 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;
}

常见操作

1. 插入与更新或插入
// INSERT: Keeps first insertion if ID exists
await env.VECTORIZE_INDEX.insert([
  {
    id: "doc-1",
    values: [0.1, 0.2, 0.3, ...],
    metadata: { title: "First version" }
  }
]);

// UPSERT: Overwrites with latest if ID exists (use this for updates)
await env.VECTORIZE_INDEX.upsert([
  {
    id: "doc-1",
    values: [0.1, 0.2, 0.3, ...],
    metadata: { title: "Updated version" }
  }
]);
2. 使用过滤器查询
// Generate embedding for query
const queryEmbedding = await env.AI.run('@cf/baai/bge-base-en-v1.5', {
  text: "What is Cloudflare Workers?"
});

// Search with metadata filtering
const results = await env.VECTORIZE_INDEX.query(
  queryEmbedding.data[0],
  {
    topK: 5,
    filter: {
      category: "documentation",
      timestamp: { $gte: 1704067200 }  // After Jan 1, 2024
    },
    returnMetadata: 'all',
    returnValues: false,
    namespace: 'prod'
  }
);
3. 元数据过滤运算符
// Equality (implicit $eq)
{ category: "docs" }

// Explicit operators
{ status: { $ne: "archived" } }

// In array
{ category: { $in: ["docs", "tutorials", "guides"] } }

// Not in array
{ category: { $nin: ["deprecated", "draft"] } }

// Range queries (numbers)
{
  timestamp: {
    $gte: 1704067200,  // >= Jan 1, 2024
    $lt: 1735689600    // < Jan 1, 2025
  }
}

// Range queries (strings) - prefix searching
{
  url: {
    $gte: "/docs/workers",
    $lt: "/docs/workersz"  // Matches all /docs/workers/*
  }
}

// Nested metadata with dot notation
{ "author.id": "user123" }

// Multiple conditions (implicit AND)
{
  category: "docs",
  language: "en",
  "metadata.published": true
}
4. 命名空间过滤
// Insert with namespace (partition key)
await env.VECTORIZE_INDEX.upsert([
  {
    id: "1",
    values: embedding,
    namespace: "customer-123",
    metadata: { type: "support_ticket" }
  }
]);

// Query only within namespace
const results = await env.VECTORIZE_INDEX.query(queryVector, {
  topK: 5,
  namespace: "customer-123"  // Only search this customer's data
});
5. 列出和删除向量
// List vector IDs (paginated)
const vectors = await env.VECTORIZE_INDEX.listVectors({
  cursor: null,
  limit: 100
});

// Get specific vectors by ID
const retrieved = await env.VECTORIZE_INDEX.getByIds([
  "doc-1", "doc-2", "doc-3"
]);

// Delete vectors
await env.VECTORIZE_INDEX.deleteByIds([
  "doc-1", "doc-2"
]);

嵌入生成

Workers AI(推荐——免费)
const embeddings = await env.AI.run('@cf/baai/bge-base-en-v1.5', {
  text: ["Document 1 content", "Document 2 content"]
});

// embeddings.data is number[][] (array of 768-dim vectors)
const vectors = embeddings.data.map((values, i) => ({
  id: `doc-${i}`,
  values,
  metadata: { source: 'batch-import' }
}));

await env.VECTORIZE_INDEX.upsert(vectors);
OpenAI 嵌入
import OpenAI from 'openai';

const openai = new OpenAI({ apiKey: env.OPENAI_API_KEY });

const response = await openai.embeddings.create({
  model: "text-embedding-3-small",  // 1536 dimensions
  input: "Text to embed"
});

await env.VECTORIZE_INDEX.upsert([{
  id: "doc-1",
  values: response.data[0].embedding,
  metadata: { model: "openai-3-small" }
}]);

元数据最佳实践

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
}

RAG 模式(完整示例)

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const { question } = await request.json();

    // 1. Generate embedding for user question
    const questionEmbedding = await env.AI.run('@cf/baai/bge-base-en-v1.5', {
      text: question
    });

    // 2. Search vector database for similar content
    const results = await env.VECTORIZE_INDEX.query(
      questionEmbedding.data[0],
      {
        topK: 3,
        returnMetadata: 'all',
        filter: { type: "documentation" }
      }
    );

    // 3. Build context from retrieved documents
    const context = results.matches
      .map(m => m.metadata.content)
      .join('\n\n---\n\n');

    // 4. Generate answer with LLM using context
    const answer = await env.AI.run('@cf/meta/llama-3-8b-instruct', {
      messages: [
        {
          role: "system",
          content: `Answer based on this context:\n\n${context}`
        },
        {
          role: "user",
          content: question
        }
      ]
    });

    return Response.json({
      answer: answer.response,
      sources: results.matches.map(m => m.metadata.title)
    });
  }
};

文档分块策略

function chunkText(text: string, maxChunkSize = 500): string[] {
  const sentences = text.match(/[^.!?]+[.!?]+/g) || [text];
  const chunks: string[] = [];
  let currentChunk = '';

  for (const sentence of sentences) {
    if ((currentChunk + sentence).length > maxChunkSize && currentChunk) {
      chunks.push(currentChunk.trim());
      currentChunk = sentence;
    } else {
      currentChunk += sentence;
    }
  }

  if (currentChunk) chunks.push(currentChunk.trim());
  return chunks;
}

// Usage
const chunks = chunkText(longDocument, 500);
const embeddings = await env.AI.run('@cf/baai/bge-base-en-v1.5', {
  text: chunks
});

const vectors = embeddings.data.map((values, i) => ({
  id: `doc-${docId}-chunk-${i}`,
  values,
  metadata: {
    doc_id: docId,
    chunk_index: i,
    total_chunks: chunks.length,
    content: chunks[i]
  }
}));

await env.VECTORIZE_INDEX.upsert(vectors);

常见错误与解决方案

错误 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:混淆插入与更新或插入
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

Wrangler CLI 参考

# Create index (dimensions and metric cannot be changed later!)
npx wrangler vectorize create <name> \
  --dimensions=768 \
  --metric=cosine

# List indexes
npx wrangler vectorize list

# Get index details
npx wrangler vectorize get <name>

# Get index info (vector count, mutations)
npx wrangler vectorize info <name>

# Delete index
npx wrangler vectorize delete <name>

# Create metadata index (BEFORE inserting vectors!)
npx wrangler vectorize create-metadata-index <name> \
  --property-name=category \
  --type=string

# List metadata indexes
npx wrangler vectorize list-metadata-index <name>

# Delete metadata index
npx wrangler vectorize delete-metadata-index <name> \
  --property-name=category

# Insert vectors from file
npx wrangler vectorize insert <name> \
  --file=vectors.ndjson

# Query vectors
npx wrangler vectorize query <name> \
  --vector="[0.1, 0.2, ...]" \
  --top-k=5 \
  --return-metadata=all

# List vector IDs
npx wrangler vectorize list-vectors <name> \
  --count=100

# Get vectors by IDs
npx wrangler vectorize get-vectors <name> \
  --ids="id1,id2,id3"

# Delete vectors by IDs
npx wrangler vectorize delete-vectors <name> \
  --ids="id1,id2,id3"

性能提示

  1. 批量操作:每批插入或更新或插入 100-1000 个向量
  2. 选择性返回:仅在需要时使用 returnValues: true(可节省带宽)
  3. 元数据基数:范围查询所用的已索引元数据字段应保持低基数
  4. 命名空间过滤:先应用命名空间过滤器,再应用元数据过滤器(优先处理)
  5. 查询优化:使用 topK=3-10 可获得最佳延迟(较大的值会增加搜索时间)

适用场景

✅ 适合使用 Vectorize 的场景:

  • 为文档、产品或内容构建语义搜索
  • 实现可检索上下文的 RAG 聊天机器人
  • 根据相似度创建推荐引擎
  • 构建多租户应用(使用命名空间)
  • 需要全球分发和低延迟

❌ 不适合使用 Vectorize 的场景:

  • 传统关系型数据(使用 D1)
  • 键值查找(使用 KV)
  • 大型文件存储(使用 R2)
  • 实时协作状态(使用 Durable Objects)

模板位置

所有可用的代码示例都在 ./templates/ 中:

  • basic-search.ts - 简单的向量搜索实现
  • rag-chat.ts - 完整的 RAG 聊天机器人
  • document-ingestion.ts - 文档处理流水线
  • metadata-filtering.ts - 高级筛选模式

参考文档

详细指南位于 ./references/:

  • wrangler-commands.md - 完整的 CLI 参考
  • index-operations.md - 索引创建和管理
  • vector-operations.md - 插入、查询和删除操作
  • metadata-guide.md - 元数据索引和筛选
  • embedding-models.md - 模型配置

集成示例

完整的集成指南位于 ./references/:

  • integration-workers-ai-bge-base.md - Workers AI 集成(@cf/baai/bge-base-en-v1.5)
  • integration-openai-embeddings.md - OpenAI 嵌入集成

官方文档


版本:1.0.0 状态:可用于生产环境 ✅ 节省的 Token:约 65% 避免的错误:8 个主要类别 节省的开发时间:每次实现约 2.5 小时

评论

支持 Markdown