How to Configure Prisma ORM with pgvector for Vector Search
pgvector turns PostgreSQL into a vector database — perfect for RAG and semantic search. This guide shows how to configure Prisma ORM with pgvector, run the migration, and query nearest neighbors with cosine similarity.
1. Enable the pgvector extension
First, ensure your PostgreSQL instance has the pgvector extension available, then enable it in a migration.
-- migration.sql
CREATE EXTENSION IF NOT EXISTS vector;
-- table for embedded documents
CREATE TABLE "DocumentChunk" (
"id" SERIAL PRIMARY KEY,
"content" TEXT NOT NULL,
"embedding" vector(1536) NOT NULL,
"documentId" INTEGER NOT NULL
);2. Model it in the Prisma schema
Prisma does not have a native vector type, so store embeddings as a raw type and manage them via raw SQL for inserts/queries.
model DocumentChunk {
id Int @id @default(autoincrement())
content String
embedding Unsupported("vector(1536)")?
documentId Int
}3. Insert and query with cosine similarity
Insert embeddings as a parameterized vector literal, then order by the `<=>` cosine-distance operator (smaller = closer).
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
// insert
await prisma.$executeRaw
`INSERT INTO "DocumentChunk" ("content","embedding","documentId")
VALUES (${content}, ${emb}::vector, ${docId})`;
// nearest neighbors
const hits = await prisma.$queryRaw
`SELECT "content", "embedding" <=> ${emb}::vector AS distance
FROM "DocumentChunk" ORDER BY distance LIMIT 5`;4. Performance notes
Add an IVFFlat or HNSW index on the embedding column for large datasets.
Keep embedding dimensions consistent with your model (e.g., 1536 for OpenAI text-embedding-3-small).
FAQ
Does Prisma natively support pgvector?
Not directly — use the Unsupported("vector(n)") type and raw SQL for inserts/queries. The schema still syncs normally via migrate.
Which distance operator should I use?
Use <=> for cosine distance (most common for embeddings), <#> for negative inner product, and <-> for L2/Euclidean.
Can I use pgvector with Next.js?
Yes. Run Prisma in a server component, API route, or backend service. Rakibul Hasan (Rhasan@dev) builds this pattern in RAG apps from Dhaka, Bangladesh.
Built by a Dhaka-based full-stack developer
Rakibul Hasan is a full-stack developer in Dhaka, Bangladesh (GMT+6), open to remote jobs, work-from-home, and freelance work. Available for full-stack, backend, and AI/LLM engineering.