ExamplesRAGInsert Embedding in Astra

Insert Embedding in Astra DB

After generating embeddings, you need to store them in a vector database for similarity search. The AstraVector class provides methods to create collections and insert embeddings into DataStax Astra DB, a cloud-native vector database. This example shows how to store embeddings in Astra DB for later retrieval.

import { openai } from '@ai-sdk/openai';
import { AstraVector } from '@mastra/astra';
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({
  model: openai.embedding('text-embedding-3-small'),
  values: chunks.map(chunk => chunk.text),
});
 
const astra = new AstraVector({
  token: process.env.ASTRA_DB_TOKEN,
  endpoint: process.env.ASTRA_DB_ENDPOINT,
  keyspace: process.env.ASTRA_DB_KEYSPACE,
});
 
await astra.createIndex({
  indexName: 'test_collection',
  dimension: 1536,
});
 
await astra.upsert({
  indexName: 'test_collection',
  vectors: embeddings,
  metadata: chunks?.map(chunk => ({ text: chunk.text })),
});