ExamplesRAGUpsertUpsert Embeddings

Upsert Embeddings

After generating embeddings, you need to store them in a database that supports vector similarity search. This example shows how to store embeddings in various vector databases for later retrieval.

The PgVector class provides methods to create indexes and insert embeddings into PostgreSQL with the pgvector extension.

import { openai } from "@ai-sdk/openai";
import { PgVector } from "@mastra/pg";
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 pgVector = new PgVector(process.env.POSTGRES_CONNECTION_STRING!);
 
await pgVector.createIndex({
  indexName: "test_index",
  dimension: 1536,
});
 
await pgVector.upsert({
  indexName: "test_index",
  vectors: embeddings,
  metadata: chunks?.map((chunk: any) => ({ text: chunk.text })),
});



View Example on GitHub
Last updated on