Insert Embedding in Cloudflare Vectorize
After generating embeddings, you need to store them in a vector database for similarity search. The CloudflareVector
class provides methods to create collections and insert embeddings into Cloudflare Vectorize, a serverless vector database service. This example shows how to store embeddings in Vectorize for later retrieval.
import { openai } from '@ai-sdk/openai';
import { CloudflareVector } from '@mastra/vectorize';
import { MDocument } from '@mastra/rag';
import { embedMany } from 'ai';
const doc = MDocument.fromText('Your text content...');
const chunks = await doc.chunk();
const { embeddings } = await embedMany({
values: chunks.map(chunk => chunk.text),
model: openai.embedding('text-embedding-3-small'),
});
const vectorize = new CloudflareVector({
accountId: process.env.CF_ACCOUNT_ID,
apiToken: process.env.CF_API_TOKEN,
});
await vectorize.createIndex('test_collection', 1536);
await vectorize.upsert(
'test_collection',
embeddings,
chunks?.map(chunk => ({ text: chunk.text })),
);