ExamplesRAGInsert Embedding in PgVector

Insert Embedding in PgVector

After generating embeddings, you need to store them in a database that supports vector similarity search. The PgVector class provides methods to create indexes and insert embeddings into PostgreSQL with the pgvector extension. This example shows how to store embeddings in a PostgreSQL database for later retrieval.

import { MDocument, embed, PgVector } from "@mastra/rag";
 
const doc = MDocument.fromText("Your text content...");
 
const chunks = await doc.chunk();
 
const { embeddings } = await embed(chunks, {
  provider: "OPEN_AI",
  model: "text-embedding-ada-002",
  maxRetries: 3,
});
 
const pgVector = new PgVector("postgresql://localhost:5432/mydb");
 
await pgVector.createIndex("test_index", 1536);
 
await pgVector.upsert(
  "test_index",
  embeddings,
  chunks?.map((chunk: any) => ({ text: chunk.text })),
);





View Example on GitHub

MIT 2025 © Nextra.