Skip to content

Vectorize

A Vectorize index finds the stored vectors nearest to a query vector. With Workers AI making the embeddings, a search route is two calls: embed the query with env.AI.run, then env.VECTORIZE.query. Declare both bindings:

jsonc
{
  "name": "my-app",
  "ai": { "binding": "AI" },
  "vectorize": [{ "binding": "VECTORIZE", "index_name": "docs" }],
  "browser": { "binding": "BROWSER" },
}

The index (index_name) must exist in your account and match the dimensions and metric of the embedding model; create it with Wrangler before you deploy. The typed env gives env.VECTORIZE the interface HamurVectorize (query, queryById, insert, upsert, deleteByIds, getByIds, describe) with loose options and results. The handler states the parts it reads:

ts
import { createError, defineHandler, getQuery } from "hamur/server"
import type { HamurEvent } from "hamur/server"

interface Env {
  AI: { run(model: string, inputs: { text: string[] }): Promise<{ data: number[][] }> }
  VECTORIZE: {
    query(
      vector: number[],
      options?: { topK?: number; returnMetadata?: "none" | "indexed" | "all" },
    ): Promise<{ matches: Array<{ id: string; score: number; metadata?: Record<string, unknown> }>; count: number }>
  }
}

const bindings = (event: HamurEvent): Env => {
  const env = event.runtime.env as unknown as Partial<Env> | undefined
  if (!env?.AI || !env.VECTORIZE)
    throw createError({ status: 501, message: "The AI and VECTORIZE bindings are not configured" })
  return env as Env
}

export const search = defineHandler({
  route: "/api/search",
  method: "GET",
  async handler(_, { event }) {
    const { AI, VECTORIZE } = bindings(event)
    const q = String(getQuery(event).q ?? "")
    const { data } = await AI.run("@cf/baai/bge-base-en-v1.5", { text: [q] })
    const { matches } = await VECTORIZE.query(data[0]!, { topK: 3, returnMetadata: "all" })
    return matches.map((match) => ({ id: match.id, score: match.score, title: String(match.metadata?.title ?? "") }))
  },
})
  • query(vector, { topK, returnMetadata }) answers { matches, count }, each match with its id, score and, with returnMetadata: "all", its metadata.
  • The embedding model of the query must be the one that embedded the stored vectors. The sample uses @cf/baai/bge-base-en-v1.5, whose { text: string[] } input answers { data: number[][] }, one vector per text.
  • As with Workers AI, the bindings are local-only under hamur dev; the handler answers 501 when they are missing.