你可以将 Cloudflare R2 bucket 连接为 AI Search 实例的数据源。AI Search 会自动为存储在 bucket 中的文件建立索引。
你可以在通过仪表板、REST API 或 Wrangler 创建新实例时连接 R2 bucket。R2 是可选数据源,可与内置存储一起添加。
如果此前从未创建过基于 R2 的实例,建议使用仪表板或 Wrangler CLI,它们会自动为你创建并注册服务 API 令牌。如果使用 REST API 或 Workers 绑定,则需要创建服务 API 令牌,并在创建请求中传入 token_id。设置说明请参阅 Service API token。
开始前,请配置一个包含数据的 R2 bucket。不受支持或超出大小限制的文件将在索引期间被跳过,并记录为错误。
你可以通过为对象路径定义包含和排除规则,控制哪些文件被索引。使用此功能可将索引限制为特定文件夹,或排除你不希望可搜索的文件。
例如,仅索引文档同时排除草稿:
- Include:
/docs/** - Exclude:
/docs/drafts/**
有关模式语法、过滤行为及更多示例,请参阅 Path filtering。
有关支持的文件类型和大小限制,请参阅 Data source。
你可以为 R2 对象附加自定义元数据,用于过滤搜索结果。AI Search 从 S3 兼容的自定义标头(x-amz-meta-*)读取元数据。
在提取元数据之前,必须在 AI Search 配置中定义架构。
使用 R2 Workers 绑定 上传对象时,使用 customMetadata 选项:
await env.MY_BUCKET.put("docs/document.pdf", fileContent, {
customMetadata: {
category: "documentation",
version: "2.5",
is_public: "true",
},
});使用 AWS SDK for JavaScript 的 Metadata 选项:
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
const client = new S3Client({
region: "auto",
endpoint: `https://${accountId}.r2.cloudflarestorage.com`,
credentials: {
accessKeyId: R2_ACCESS_KEY_ID,
secretAccessKey: R2_SECRET_ACCESS_KEY,
},
});
await client.send(
new PutObjectCommand({
Bucket: "your-bucket",
Key: "docs/document.pdf",
Body: fileContent,
Metadata: {
category: "documentation",
version: "2.5",
is_public: "true",
},
}),
);使用 Wrangler 的 --header 标志设置 x-amz-meta-* 标头:
wrangler r2 object put your-bucket/docs/document.pdf \
--file=./document.pdf \
--header="x-amz-meta-category:documentation" \
--header="x-amz-meta-version:2.5" \
--header="x-amz-meta-is_public:true"在索引期间从 R2 获取文件时:
- 从对象读取所有
x-amz-meta-*标头。 - 剥离
x-amz-meta-前缀(例如,x-amz-meta-category变为category)。 - 将字段名与你的架构匹配(不区分大小写)。
- 将值转换为配置的数据类型。
- 无效值(例如,对
number类型使用非数字字符串)会被静默忽略。
元数据值通过 MIME-Word 编码(RFC 2047)支持 Unicode 字符。大多数 S3 兼容工具会自动处理此编码。