Pular para o conteúdo

Create a simple search engine

Atualizado em Ver como Markdown

This guide builds a search engine that returns the file names matching a query, using the search() method on the Workers binding. You can adapt it to use the REST API instead.

For the best results with this pattern:

  • Disable query rewriting so the original user query is matched directly.
  • Configure your AI Search instance with small chunk sizes (256 tokens is usually enough).

Prerequisites

  1. Sign up for a Cloudflare account.
  2. Install Node.js.

Node.js version manager

Use a Node version manager like Volta or nvm to avoid permission issues and change Node.js versions. Wrangler, discussed later in this guide, requires a Node version of 16.17.0 or later.

You also need an AI Search instance that already contains indexed content. To create one and add content, refer to Get started.

1. Create a Worker project

Create a new Worker project using the create-cloudflare CLI (C3). C3 is a command-line tool designed to help you set up and deploy new applications to Cloudflare.

Create a new project named search-engine by running:


								
									
									npm
									 create cloudflare@latest -- search-engine
								
							

For setup, select the following options:

  • For What would you like to start with?, choose Hello World example.
  • For Which template would you like to use?, choose Worker only.
  • For Which language do you want to use?, choose TypeScript.
  • For Do you want to use git for version control?, choose Yes.
  • For Do you want to deploy your application?, choose No (we will be making some changes before deploying).

Go to your application directory:

cd search-engine

Add the following to your Wrangler configuration file:

{
  "$schema": "./node_modules/wrangler/config-schema.json",
  "ai_search_namespaces": [
    {
      "binding": "AI_SEARCH",
      "namespace": "default",
      "remote": true
    }
  ]
}
[[ai_search_namespaces]]
binding = "AI_SEARCH"
namespace = "default"
remote = true

This binds the default namespace to env.AI_SEARCH. The remote option lets wrangler dev proxy requests to your deployed instance, since AI Search does not run locally.

3. Add the search code

Update src/index.ts. This Worker reads a query from the URL, searches your instance, and returns the file name of each matching chunk. Replace my-instance with the name of your instance.

src/index.jsjs
export default {
	async fetch(request, env) {
		const url = new URL(request.url);
		const userQuery = url.searchParams.get("query") ?? "What is Cloudflare?";

		const searchResult = await env.AI_SEARCH.get("my-instance").search({
			messages: [{ role: "user", content: userQuery }],
		});

		return Response.json({
			files: searchResult.chunks.map((chunk) => chunk.item.key),
		});
	},
};
src/index.tsts
export interface Env {
	AI_SEARCH: AiSearchNamespace;
}

export default {
	async fetch(request, env): Promise<Response> {
		const url = new URL(request.url);
		const userQuery = url.searchParams.get("query") ?? "What is Cloudflare?";

		const searchResult = await env.AI_SEARCH.get("my-instance").search({
			messages: [{ role: "user", content: userQuery }],
		});

		return Response.json({
			files: searchResult.chunks.map((chunk) => chunk.item.key),
		});
	},
} satisfies ExportedHandler<Env>;

4. Run and deploy

Start a local development server, then query it at /?query=your+search+terms:

npx wrangler dev

Log in with your Cloudflare account, then deploy your Worker to make it accessible on the Internet:

npx wrangler login
npx wrangler deploy

Next steps