Skip to content

Create a simple search engine

Use the search() method to implement a simple search engine. This example uses the Workers binding, but can be adapted to use the REST API instead.

To replicate this example:

  • Disable query rewriting so that the original user query is matched directly
  • Configure your AI Search instance to have small chunk sizes (256 tokens is usually enough)
JavaScript
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),
});
},
};