跳转到内容
本站为社区维护的非官方中文翻译,与 Cloudflare, Inc. 无关联。本站不提供账户登录,请勿在任何非官方站点输入您的 Cloudflare 账户信息。官方文档:developers.cloudflare.com

跨多个实例搜索

最后更新 查看 MarkdownAgent 设置

AI Search 可以在一次请求中查询多个实例、合并结果,并标记每条结果来自哪个实例。本指南利用这一能力同时搜索两个知识库:所有用户都可搜索的共享 通用 知识库,以及存放某个客户私有内容的 租户专属 知识库。一次查询即可返回两个知识库中的相关内容。

将每个租户的内容保持在其自身的实例中是隔离租户的推荐方式(请参阅多租户搜索隔离)。跨实例搜索允许你在查询时将租户的实例与共享内容结合起来,因此你无需将共享内容复制到每个租户的实例中。

你将构建的内容: 一个一同搜索共享的 general-knowledge 实例和按租户实例的 Worker,然后按来源对结果进行分组。

先决条件

  1. 注册 Cloudflare 账户 ↗。
  2. 安装 Node.js ↗。

Node.js 版本管理器

使用 Vite+ (vp env) ↗ 安装和管理 Node.js 版本。

有关支持的 Node.js 版本,请参阅 Wrangler 系统要求。

你跨其搜索的实例必须属于同一个命名空间 (namespace)。本指南将为你创建它们。

1. 创建 Worker 项目

使用 create-cloudflare CLI (C3) 创建新的 Worker 项目。C3 ↗ 是一种命令行工具,旨在帮助你设置并部署新的应用程序到 Cloudflare。

通过运行以下命令创建一个名为 multi-source-search 的新项目:

npm create cloudflare@latest -- multi-source-search

设置时,选择以下选项:

  • 对于 What would you like to start with?(希望从什么开始?),选择 Hello World example。
  • 对于 Which template would you like to use?(希望使用哪个模板?),选择 Worker only。
  • 对于 Which language do you want to use?(希望使用哪种语言?),选择 TypeScript。
  • 对于 Do you want to use git for version control?(是否使用 Git 进行版本控制?),选择 Yes。
  • 对于 Do you want to add an AGENTS.md file to help AI coding tools understand Cloudflare APIs?(是否添加 AGENTS.md 文件以帮助 AI 编程工具理解 Cloudflare API?),选择 Yes。
  • 对于 Do you want to deploy your application?(是否部署应用?),选择 No(部署前还需要进行一些修改)。

进入你的应用程序目录:

cd multi-source-search

2. 配置 Wrangler

将 AI Search 命名空间绑定 添加到你的 Wrangler 配置文件。跨实例搜索是命名空间绑定上的一个方法,因此单个绑定就能访问命名空间中的每个实例。

{
  "$schema": "./node_modules/wrangler/config-schema.json",
  "name": "multi-source-search",
  "main": "src/index.ts",
  "upload_source_maps": true,
  // Set this to today's date
  "compatibility_date": "2026-11-14",
  "ai_search_namespaces": [
    {
      "binding": "AI_SEARCH",
      "namespace": "default",
      "remote": true
    }
  ]
}
name = "multi-source-search"
main = "src/index.ts"
upload_source_maps = true
# Set this to today's date
compatibility_date = "2026-11-14"

[[ai_search_namespaces]]
binding = "AI_SEARCH"
namespace = "default"
remote = true

remote 选项允许 wrangler dev 将请求代理到已部署的实例,因为 AI Search 不在本地运行。

3. 添加 Worker 代码

更新 src/index.ts。此 Worker 从请求标头中识别租户,然后在一次调用中搜索共享实例和该租户的实例。每个返回的块 (chunk) 都带有 instance_id,因此 Worker 可以按来源对结果进行分组。

src/index.jsjs
// The shared instance that every tenant can search.
const GENERAL_INSTANCE = "general-knowledge";
// Each tenant also has its own instance, holding only that tenant's content.
const tenantInstance = (tenantId) => `tenant-${tenantId}`;

// Seed content, so each instance returns something on the first query. In a
// real app you would provision instances and their content ahead of time.
const GENERAL_DOC = `# Support hours
Support is available Monday to Friday, 9am to 5pm UTC for all customers.`;
const TENANT_DOC = `# Your plan
This account is on the Enterprise plan with a dedicated success manager.`;

export default {
	async fetch(request, env) {
		// Identify the tenant and read the query.
		const tenantId = request.headers.get("x-tenant-id");
		if (!tenantId) {
			return new Response("Missing x-tenant-id header", { status: 400 });
		}
		const query = new URL(request.url).searchParams.get("q");
		if (!query) {
			return new Response("Add a ?q= query parameter", { status: 400 });
		}

		// One-time setup for this demo: create both instances and seed each.
		await ensureInstance(
			env,
			GENERAL_INSTANCE,
			"support-hours.md",
			GENERAL_DOC,
		);
		await ensureInstance(env, tenantInstance(tenantId), "plan.md", TENANT_DOC);

		// Search the shared instance and this tenant's instance in one call.
		// AI Search fans out to both, merges the results, and tags each chunk
		// with the instance_id it came from. You can pass 1 to 10 instance IDs.
		const results = await env.AI_SEARCH.search({
			query,
			ai_search_options: {
				instance_ids: [GENERAL_INSTANCE, tenantInstance(tenantId)],
			},
		});

		// Use the instance_id tag to separate shared results from tenant results.
		const fromGeneral = results.chunks.filter(
			(chunk) => chunk.instance_id === GENERAL_INSTANCE,
		);
		const fromTenant = results.chunks.filter(
			(chunk) => chunk.instance_id === tenantInstance(tenantId),
		);

		return Response.json({
			query: results.search_query,
			general: fromGeneral.map((chunk) => ({
				key: chunk.item.key,
				text: chunk.text,
			})),
			tenant: fromTenant.map((chunk) => ({
				key: chunk.item.key,
				text: chunk.text,
			})),
			// If one instance fails, the other still returns. Failures land here.
			errors: results.errors,
		});
	},
};

// Create an instance with built-in storage and seed one document. Safe to call
// on every request: create() throws if the instance already exists, so the
// try/catch skips setup once it is in place.
async function ensureInstance(env, id, key, content) {
	try {
		await env.AI_SEARCH.create({ id });
		await env.AI_SEARCH.get(id).items.uploadAndPoll(key, content, {
			timeoutMs: 60_000,
		});
	} catch {
		// The instance already exists and has been seeded.
	}
}
src/index.tsts
export interface Env {
	AI_SEARCH: AiSearchNamespace;
}

// The shared instance that every tenant can search.
const GENERAL_INSTANCE = "general-knowledge";
// Each tenant also has its own instance, holding only that tenant's content.
const tenantInstance = (tenantId: string) => `tenant-${tenantId}`;

// Seed content, so each instance returns something on the first query. In a
// real app you would provision instances and their content ahead of time.
const GENERAL_DOC = `# Support hours
Support is available Monday to Friday, 9am to 5pm UTC for all customers.`;
const TENANT_DOC = `# Your plan
This account is on the Enterprise plan with a dedicated success manager.`;

export default {
	async fetch(request, env): Promise<Response> {
		// Identify the tenant and read the query.
		const tenantId = request.headers.get("x-tenant-id");
		if (!tenantId) {
			return new Response("Missing x-tenant-id header", { status: 400 });
		}
		const query = new URL(request.url).searchParams.get("q");
		if (!query) {
			return new Response("Add a ?q= query parameter", { status: 400 });
		}

		// One-time setup for this demo: create both instances and seed each.
		await ensureInstance(
			env,
			GENERAL_INSTANCE,
			"support-hours.md",
			GENERAL_DOC,
		);
		await ensureInstance(env, tenantInstance(tenantId), "plan.md", TENANT_DOC);

		// Search the shared instance and this tenant's instance in one call.
		// AI Search fans out to both, merges the results, and tags each chunk
		// with the instance_id it came from. You can pass 1 to 10 instance IDs.
		const results = await env.AI_SEARCH.search({
			query,
			ai_search_options: {
				instance_ids: [GENERAL_INSTANCE, tenantInstance(tenantId)],
			},
		});

		// Use the instance_id tag to separate shared results from tenant results.
		const fromGeneral = results.chunks.filter(
			(chunk) => chunk.instance_id === GENERAL_INSTANCE,
		);
		const fromTenant = results.chunks.filter(
			(chunk) => chunk.instance_id === tenantInstance(tenantId),
		);

		return Response.json({
			query: results.search_query,
			general: fromGeneral.map((chunk) => ({
				key: chunk.item.key,
				text: chunk.text,
			})),
			tenant: fromTenant.map((chunk) => ({
				key: chunk.item.key,
				text: chunk.text,
			})),
			// If one instance fails, the other still returns. Failures land here.
			errors: results.errors,
		});
	},
} satisfies ExportedHandler<Env>;

// Create an instance with built-in storage and seed one document. Safe to call
// on every request: create() throws if the instance already exists, so the
// try/catch skips setup once it is in place.
async function ensureInstance(
	env: Env,
	id: string,
	key: string,
	content: string,
) {
	try {
		await env.AI_SEARCH.create({ id });
		await env.AI_SEARCH.get(id).items.uploadAndPoll(key, content, {
			timeoutMs: 60_000,
		});
	} catch {
		// The instance already exists and has been seeded.
	}
}

env.AI_SEARCH.search() 是命名空间级别的搜索。它不同于 env.AI_SEARCH.get(id).search(),后者仅搜索单个实例。传递 instance_ids 会将查询扇出到这些实例上,并返回一个合并且排序的块列表。因为每个块都包含 instance_id,你始终知道结果来自共享实例还是租户实例。

如果某个实例失败(例如因为 ID 不存在),其他实例仍然会返回,并且失败会在 errors 中报告而不是抛出异常。这使得缺失的租户实例表现为部分结果而非硬性错误。

4. 运行它

启动本地开发服务器:

npx wrangler dev

发送带有租户标头和查询的请求。第一个请求需要一点时间,因为要创建并填充实例:

curl "http://localhost:8787/?q=support+hours+and+my+plan" -H "x-tenant-id: acme"

响应会将来自共享实例和租户实例的结果分离开来:

{
	"query": "support hours and my plan",
	"general": [
		{
			"key": "support-hours.md",
			"text": "# Support hours\nSupport is available..."
		}
	],
	"tenant": [
		{
			"key": "plan.md",
			"text": "# Your plan\nThis account is on the Enterprise plan..."
		}
	]
}

当每个实例都成功时,响应没有 errors 字段。如果某个实例失败,errors 数组会列出失败原因,同时其他实例的结果仍然返回。

5. 基于两个实例生成回答

要返回一个基于两个实例的单篇撰写的回答而不是原始 chunks,请使用带有相同 instance_ids 的 chatCompletions。它会从列出的每个实例中进行检索,然后从组合的上下文生成一个响应:

const completion = await env.AI_SEARCH.chatCompletions({
	query,
	ai_search_options: {
		instance_ids: [GENERAL_INSTANCE, tenantInstance(tenantId)],
	},
});

// The generated answer, grounded in both the shared and tenant content.
const answer = completion.choices[0]?.message.content;

响应还包含检索到的 chunks(每个都用其 instance_id 进行标记),以便你可以引用来源,以及针对任何失败实例的 errors 数组。

6. 部署

登录你的 Cloudflare 账户,然后部署你的 Worker:

npx wrangler login
npx wrangler deploy

后续步骤

这篇文档对您有帮助吗?