Skip to content
AnswerWell geo Documentation

Research · 7 min read · Answerwell

Vector Index Embeddings, Query Bindings and RAG

How Cloudflare Vectorize stores embeddings, binds to Workers, queries with metadata filters, and powers retrieval-augmented generation pipelines.

This page summarizes Cloudflare Vectorize documentation for developers who need a managed vector index on the Workers platform: store embeddings from any model, run similarity search from a Worker or Pages Function, optionally filter by metadata or namespace, and wire results into retrieval-augmented generation (RAG) with Workers AI or other LLM APIs.

Build full-stack AI applications with Vectorize, Cloudflare’s powerful vector database.

— Cloudflare, Cloudflare Vectorize

Vectorize vs AI Search: when to manage vectors yourself

Section titled “Vectorize vs AI Search: when to manage vectors yourself”

Vectorize is the low-level vector database. AI Search is built on Vectorize and wraps chunking, embedding, indexing, hybrid retrieval, and optional answers.

Capability AI Search Vectorize
What you provide Files or a connected data source Vectors you generate
Chunking and embeddings Handled for you You generate and insert
Retrieval Vector, keyword (hybrid), reranking Vector similarity + metadata filtering
Generated answers Optional, built in Not included

Use Vectorize when you want to manage vectors yourself, and AI Search when you want managed search over your content.

— Cloudflare, How AI Search works

Choose Vectorize when you control embedding models, IDs, metadata schema, and how retrieved text is passed to an LLM. Choose AI Search when you want a faster path from documents to searchable, answer-ready context (AI Search vector search uses a built-in Vectorize index you do not manage separately).

Vector database basics: indexes, dimensions, and metrics

Section titled “Vector database basics: indexes, dimensions, and metrics”

In Vectorize, a database and an index are the same unit: each index is isolated and is re-optimized when you insert data (Vector databases). Indexes store embeddings (floating-point vectors), not the original text or images; you usually keep source records in D1, R2, or KV.

A vector database is designed to store vector embeddings, which are representations of data, but not the original data itself.

— Cloudflare, Introduction to Vectorize

Create indexes: fixed dimensions and distance metric

Section titled “Create indexes: fixed dimensions and distance metric”

Creating an index needs a kebab-case name, fixed dimension count (often 384–1536, matching your embedding model), and a distance metric that cannot change after creation (Create indexes).

Supported metrics (Create indexes — distance metrics):

Metric Behavior (summary)
cosine Similarity from −1 to 1; common for text
euclidean L2 distance; 0 means identical
dot-product Negative dot product; interpret scores per docs

Vectorize V2 requires Wrangler 3.71.0 or later (npx wrangler@latest vectorize). Example for Workers AI model @cf/baai/bge-base-en-v1.5 (768 dimensions, cosine):

npx wrangler vectorize create your-index-name --dimensions=768 --metric=cosine

You can also create indexes via the HTTP API or Wrangler commands.

Worker and Pages bindings: connect code to an index

Section titled “Worker and Pages bindings: connect code to an index”

Bindings expose the index on env.<BINDING_NAME> as insert, upsert, query, queryById, deleteByIds, and related APIs (Vectorize API).

In wrangler.toml / wrangler.jsonc (Wrangler configuration):

[[vectorize]]
binding = "VECTORIZE"
index_name = "tutorial-index"

For Pages Functions, configure the same binding in the dashboard (Bindings → Add → Vectorize index) or Wrangler, then redeploy. Access the binding via context.env.VECTORIZE_INDEX in your function code (Vectorize indexes — Pages bindings).

For local development there is no Vectorize simulator; point bindings at production indexes with remote = true (Local development).

Insert and upsert vectors: IDs, formats, and write throughput

Section titled “Insert and upsert vectors: IDs, formats, and write throughput”

Vectors need a unique string id, a values array whose length matches the index dimensions, and optional metadata (up to 10 KiB per vector) and namespace (Vectorize API — Vectors).

If the same vector id is inserted twice in a Vectorize index, the index would reflect the vector that was added first. If the same vector id is upserted twice in a Vectorize index, the index would reflect the vector that was added last.

— Cloudflare, Insert vectors

  • Use insert for new IDs only; duplicates are ignored.
  • Use upsert to replace an existing ID’s vector and metadata in full (no merge).

Values may be number[], Float32Array, or Float64Array; storage is Float32 (Insert vectors — supported formats). Bulk upload uses NDJSON via wrangler vectorize insert <index> --file=embeddings.ndjson (max 5000 vectors per file for API rate limits) (Insert vectors — wrangler CLI).

Inserts and upserts are asynchronous: the API returns a mutationId, and vectors typically become queryable after a short delay. Improved WAL throughput reduced median time-to-queryable from about 2 minutes to under 30 seconds (Reduced end-to-end latency for vector changes). Batch many vectors per request (up to 1000 updates per Workers batch job) instead of one-by-one inserts for large loads (Improve write throughput).

Check progress with:

npx wrangler vectorize info tutorial-index

Query vectors: topK, metadata return, and queryById

Section titled “Query vectors: topK, metadata return, and queryById”

Querying runs similarity search with an input vector (no id required) (Query vectors):

let matches = await env.YOUR_INDEX.query(queryVector, {
topK: 5,
returnValues: true,
returnMetadata: "all",
});
Option Role
topK Number of matches (default 5); up to 100 without values/metadata; up to 50 with returnValues: true or returnMetadata: "all" (Vectorize API — topK)
returnValues Exact scores via full vector values; increases latency
returnMetadata none, indexed, or all (returnMetadata)

Use queryById("some-vector-id") to search relative to a vector already in the index (Query by vector identifier).

env.AI.run() for embedding models returns { shape, data }. Pass only queryVector.data[0] to query(), not the whole response (Query vectors — Workers AI).

Metadata filtering, namespaces, and list-vectors

Section titled “Metadata filtering, namespaces, and list-vectors”

Namespaces segment vectors inside one index (optional on insert; pass namespace on query). Namespace filtering runs before metadata filters (Metadata filtering — namespace versus metadata).

Metadata filtering requires declaring metadata indexes before you rely on filters—ideally right after index creation (Introduction to Vectorize — metadata indexes):

npx wrangler vectorize create-metadata-index tutorial-index --property-name=url --type=string

Up to 10 metadata indexes per Vectorize index; string filters use the first 64 UTF-8 bytes of each indexed string (Metadata filtering). Example query:

let metadataMatches = await env.YOUR_INDEX.query(queryVector, {
topK: 3,
filter: { streaming_platform: "netflix" },
returnMetadata: "all",
});

V2 also supports range and set operators on indexed fields (for example $lt, $in; see Vectorize platform changelog).

The list-vectors operation paginates all vector IDs for audit, migration, or cleanup (List vectors). Pagination uses a snapshot: vectors added mid-iteration may not appear until you start a new sequence.

RAG pattern: Vectorize, D1, and LLM context

Section titled “RAG pattern: Vectorize, D1, and LLM context”

RAG augments an LLM prompt with retrieved context instead of sending the raw user question alone (Vector databases — RAG).

Combine vector search with Large Language Model (LLM) inference to ground responses in your own data: Vectorize stores embeddings of your knowledge base; Workers receives user queries and searches for relevant context; Workers AI or AI Gateway generates responses using retrieved context.

— Cloudflare, AI applications — RAG

A typical Worker flow from Build a Retrieval Augmented Generation (RAG) AI:

  1. Store source text in D1 (or elsewhere); on write, embed text and upsert into Vectorize with id aligned to the row ID.
  2. On question: embed the query → VECTOR_INDEX.query(vectors, { topK: 1 }) → load matching rows from D1.
  3. Put note text into the system or user messages for env.AI.run() on your chat model.
  4. On delete: remove the D1 row and deleteByIds([id]) on the index.

topK controls how many chunks feed the prompt; large documents benefit from chunking (for example with @langchain/textsplitters in the same tutorial) so each chunk gets its own vector.

Current Vectorize limits (Limits) include:

Feature Limit (high level)
Vectors per index 20,000,000
Dimensions per vector 1536 (float32)
Metadata per vector 10 KiB
topK with values/metadata 50
Upsert batch (Workers) 1000 vectors

Billing is by queried and stored vector dimensions, not per index count (Vectorize pricing). Workers Free includes capped Vectorize usage; paid plans add included quotas (Workers platform pricing — Vectorize).

Common mistakes:

  • Dimension mismatch between index config and embedding model output.
  • Using insert to update existing IDs instead of upsert.
  • Querying before mutations apply—wait for WAL processing or check wrangler vectorize info.
  • Filtering on metadata without a metadata index, or expecting full string match beyond the first 64 indexed bytes.
  • Passing the whole Workers AI embedding object into query() instead of data[0].
  • Leaving D1 (or KV) and Vectorize out of sync on deletes or edits.
  1. Create or confirm an index with matching --dimensions and --metric using Create indexes and npx wrangler vectorize create.

  2. Verify the Worker or Pages binding in Wrangler configuration or Pages bindings, deploy, and call your insert route once.

  3. Run npx wrangler vectorize info <index-name> and confirm vectorCount and processedUpToMutation match your last write (Introduction to Vectorize — query your index).

  4. Issue a test query (Worker route or query() in code) with known embeddings and confirm expected IDs, scores, and metadata per Query vectors.

  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact statement you are asking about.