Skip to main content
AI & Machine Learning 12 min readPublished: Oct 12, 20261,137 views

Implementing Production Semantic Search with OpenAI Embeddings and PostgreSQL pgvector (2026)

Shivam Swami — Founder & CEO at Betadrix
Shivam Swami

Founder & CEO

Implementing Production Semantic Search with OpenAI Embeddings and PostgreSQL pgvector (2026)
12 min read

Production guide to semantic search with OpenAI text-embedding-3 and PostgreSQL pgvector. Learn HNSW index tuning, hybrid search with RRF, and SQL optimizations.

The Modern Retrieval Paradigm: Relational Data Meets Vector Embeddings

In early generative AI architectures, engineering teams frequently adopted dedicated, standalone vector databases (such as Pinecone, Qdrant, or Milvus) alongside their existing relational stores. However, in production, this dual-database topology introduces severe operational liabilities: distributed transaction desynchronization, eventual consistency lag, duplicate authorization checks, and spiraling SaaS infrastructure costs.

With the maturation of PostgreSQL 16+ and the pgvector 0.7+ extension, modern software architectures can store relational business entities, transactional ledgers, user access control lists (ACLs), and high-dimensional vector embeddings within a single unified, ACID-compliant database cluster.

// Hybrid Search Architecture with PostgreSQL & OpenAI
User Query ──> (OpenAI text-embedding-3-small) ──> Vector Embedding [1536 float32]
│
├──> [Branch 1: pgvector HNSW Query] ──> Cosine Similarity Top-50
└──> [Branch 2: PostgreSQL tsvector Search] ──> BM25 Full-Text Rank Top-50
│
▼ (Reciprocal Rank Fusion - RRF)
Final Blended & Deduplicated Results (Sub-15ms Latency)
Figure 1: Hybrid retrieval blending semantic vector proximity with lexical keyword accuracy.

1. Database Schema & HNSW Indexing Strategy in pgvector

To implement high-throughput search, we install the vector extension and define table schemas equipped with both vector embeddings and traditional PostgreSQL full-text search columns.

Production PostgreSQL SQL DDL

-- Enable the pgvector extension
CREATE EXTENSION IF NOT EXISTS vector;

-- Table storing documents, lexical search vectors, and semantic embeddings
CREATE TABLE enterprise_knowledge_base (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL,
    title TEXT NOT NULL,
    content TEXT NOT NULL,
    category VARCHAR(64) NOT NULL,
    metadata JSONB DEFAULT '{}'::jsonb,
    
    -- Lexical search tsvector column
    tsv_content TSVECTOR GENERATED ALWAYS AS (
        setweight(to_tsvector('english', coalesce(title, '')), 'A') ||
        setweight(to_tsvector('english', coalesce(content, '')), 'B')
    ) STORED,

    -- Vector embedding (1536 dimensions for text-embedding-3-small)
    embedding VECTOR(1536),

    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- 1. Create Generalized Inverted Index (GIN) for lexical text search
CREATE INDEX idx_knowledge_tsv ON enterprise_knowledge_base USING GIN(tsv_content);

-- 2. Create Hierarchical Navigable Small World (HNSW) index for vector cosine distance
-- m = 16 (bidirectional links per node), ef_construction = 128 (construction search depth)
SET maintenance_work_mem = '2GB';
CREATE INDEX idx_knowledge_hnsw_cosine ON enterprise_knowledge_base 
USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 128);

2. Vector Distance Metrics: Choosing the Right Operator

pgvector supports three primary distance calculation operators:

  • <=> Cosine Distance: Measures the angular difference between vectors, ignoring magnitude. This is the correct metric for normalized embeddings such as OpenAI's models (distance = 1 - cosine_similarity).
  • <-> L2 / Euclidean Distance: Measures direct straight-line geometric distance. Ideal for spatial coordinates and computer vision feature spaces.
  • <#> Negative Inner Product: Maximizes dot-product multiplication. Fastest computational operator when embeddings are pre-normalized to unit length.

3. End-to-End TypeScript Implementation: Ingestion & Hybrid RRF Search

The following production TypeScript service generates embeddings via the OpenAI API, executes parallel semantic and lexical searches in PostgreSQL, and merges rankings using Reciprocal Rank Fusion (RRF).

import OpenAI from "openai";
import { Pool } from "pg";

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
const pool = new Pool({ connectionString: process.env.DATABASE_URL });

export interface SearchResult {
  id: string;
  title: string;
  content: string;
  score: number;
}

/**
 * Generates normalized 1536-dimensional embedding using text-embedding-3-small
 */
export async function generateEmbedding(text: string): Promise {
  const cleanInput = text.replace(/\n/g, " ").trim();
  const response = await openai.embeddings.create({
    model: "text-embedding-3-small",
    input: cleanInput,
    encoding_format: "float",
  });
  return response.data[0].embedding;
}

/**
 * Executes hybrid search merging BM25 and Vector Cosine similarity via Reciprocal Rank Fusion
 */
export async function hybridSearch(query: string, tenantId: string, limit: number = 10): Promise {
  const queryEmbedding = await generateEmbedding(query);
  const vectorString = `[${queryEmbedding.join(",")}]`;

  // SQL query executing Reciprocal Rank Fusion (k = 60)
  const sql = `
    WITH semantic_search AS (
        SELECT id, title, content,
               ROW_NUMBER() OVER (ORDER BY embedding <=> $1::vector) as rank
        FROM enterprise_knowledge_base
        WHERE tenant_id = $2
        ORDER BY embedding <=> $1::vector
        LIMIT 40
    ),
    lexical_search AS (
        SELECT id, title, content,
               ROW_NUMBER() OVER (ORDER BY ts_rank_cd(tsv_content, plainto_tsquery('english', $3)) DESC) as rank
        FROM enterprise_knowledge_base
        WHERE tenant_id = $2 AND tsv_content @@ plainto_tsquery('english', $3)
        ORDER BY ts_rank_cd(tsv_content, plainto_tsquery('english', $3)) DESC
        LIMIT 40
    )
    SELECT
        COALESCE(s.id, l.id) as id,
        COALESCE(s.title, l.title) as title,
        COALESCE(s.content, l.content) as content,
        (
            COALESCE(1.0 / (60.0 + s.rank), 0.0) +
            COALESCE(1.0 / (60.0 + l.rank), 0.0)
        ) as rrf_score
    FROM semantic_search s
    FULL OUTER JOIN lexical_search l ON s.id = l.id
    ORDER BY rrf_score DESC
    LIMIT $4;
  `;

  const client = await pool.connect();
  try {
    // Tune HNSW search depth for this transaction (higher ef_search = higher recall)
    await client.query("SET LOCAL hnsw.ef_search = 64;");
    const result = await client.query(sql, [vectorString, tenantId, query, limit]);
    return result.rows.map(r => ({
      id: r.id,
      title: r.title,
      content: r.content,
      score: parseFloat(r.rrf_score),
    }));
  } finally {
    client.release();
  }
}

Benchmark Comparison: IVFFlat vs HNSW in Production

Performance Metric IVFFlat Index HNSW Index (pgvector 0.7+)
Query Latency (p95) 25ms – 80ms 3ms – 12ms
Query Throughput (QPS) 150 – 400 QPS 1,500 – 4,000+ QPS
Search Recall Accuracy 85% – 92% 97% – 99.5%
Index Memory Footprint Low (approx. 1.2x vector data) Higher (approx. 1.5x–2x vector data)
Index Build Time Fast (Minutes for 1M vectors) Moderate (Requires sufficient RAM)
Training Step Requirement Mandatory (Requires pre-populated data) None (Builds incrementally on live writes)

Performance Tuning & Memory Sizing Rules

  1. Set maintenance_work_mem High During Index Creation: HNSW graph construction requires substantial memory. Set SET maintenance_work_mem = '4GB'; before executing CREATE INDEX to prevent temporary disk spills.
  2. Tune hnsw.ef_search Dynamically: The default ef_search is 40. For higher recall in deep knowledge bases, increase to 64 or 100 at the session level.
  3. Keep HNSW Graphs in Buffer Cache: For sub-10ms search responses, ensure the total size of your HNSW indexes fits entirely within PostgreSQL's shared_buffers and the operating system file system cache.

Enterprise Search Engineering with Betadrix

Modernizing search infrastructure from brittle keyword engines to high-performance semantic retrieval transforms customer conversion and internal employee productivity. At Betadrix, our AI and database architects design low-latency vector search architectures, hybrid RAG retrieval pipelines, and enterprise PostgreSQL databases. Discover our AI development services, consult our PostgreSQL development services, or custom software development offerings to scale your retrieval systems.

Deploying high-concurrency semantic vector search with pgvector eliminates distributed transaction lag by unifying relational entities with vector embeddings. Betadrix's AI development services include hybrid search engineering, OpenAI model fine-tuning, and RAG retrieval pipelines. For organizations scaling complex data platforms, our custom software development services deliver resilient backend APIs and sub-millisecond database architectures.

Series Guide

AI & Intelligent Systems

19/19

?Frequently Asked Questions

Why use PostgreSQL pgvector instead of dedicated vector databases like Pinecone, Weaviate, or Qdrant?
PostgreSQL with pgvector allows you to keep relational data (users, permissions, products, prices) and vector embeddings in a single ACID-compliant database. This eliminates complex dual-write distributed transactions, prevents data synchronization lag, avoids extra SaaS subscription costs, and allows combining relational SQL filtering (e.g. WHERE user_id = $1 AND in_stock = true) with vector similarity in a single query.
What is the difference between HNSW and IVFFlat index types in pgvector?
IVFFlat partitions vectors into clusters (lists). It has fast build times and low memory usage, but lower recall (accuracy) and requires training on representative data. HNSW (Hierarchical Navigable Small World) builds multi-layer proximity graphs. It delivers significantly higher queries-per-second (QPS), sub-10ms query latency, and superior recall (>98%) at the expense of higher memory usage and longer build times. HNSW is recommended for virtually all production workloads.
What OpenAI embedding model should be used in 2026?
OpenAI's 'text-embedding-3-small' (1536 dimensions) is the standard recommendation for cost-sensitive, high-throughput search, offering high semantic recall at $0.02 per 1M tokens. For legal, medical, or complex multi-lingual domain search, 'text-embedding-3-large' (3072 dimensions) provides state-of-the-art retrieval accuracy.
What is Hybrid Search and why is pure vector search often insufficient?
Pure vector search excels at conceptual matching (e.g. 'how to fix a leaking tap' matching plumbing guides), but often fails on exact keyword lookups, part numbers, SKUs, and proper nouns (e.g. 'Sony WH-1000XM5'). Hybrid search combines Full-Text Search (BM25 / tsvector) with Vector Similarity, blending rankings using Reciprocal Rank Fusion (RRF) for the highest possible precision.
How do you scale pgvector beyond millions of vectors?
Scaling pgvector to tens of millions of records requires: (1) tuning maintenance_work_mem and max_parallel_maintenance_workers during HNSW index construction, (2) adjusting the hnsw.ef_search parameter at runtime, (3) using PostgreSQL declarative table partitioning by tenant, category, or date, and (4) utilizing read-replicas for read-heavy search workloads.
How does Betadrix assist organizations deploying production AI search and RAG systems?
Betadrix designs and implements production AI retrieval systems, including custom pgvector architectures, hybrid search pipelines, semantic caching layers, and end-to-end RAG workflows for enterprise applications.
Shivam Swami — Founder & CEO at Betadrix

Shivam Swami

Founder & CEO

Shivam Swami is the Founder & CEO of Betadrix, driving technical vision, distributed systems engineering, high-throughput iGaming platforms, and enterprise AI architecture.

iGaming & Casino SystemsEnterprise AIDistributed SystemsCloud Architecture
Quick Inquiry

Build Your Custom Project

Connect with technical architects for scope and estimation.

Related Insights & Deep-Dives

More Articles in AI & Machine Learning

Page 1 of 2

Watch.
Learn.
Grow.

Discover how our engineered solutions transform industries and propel client operations forward.

Owning the Game, Not Renting It: Custom Crash Game Development for a Lahore-Based iGaming Operator
iGaming — Online Casino & Sportsbook

Owning the Game, Not Renting It: Custom Crash Game Development for a Lahore-Based iGaming Operator

READ CASE STUDY
Casino Software Development in Germany — Case Study
iGaming / Online Casino

Casino Software Development in Germany — Case Study

READ CASE STUDY
NikahNet Ethiopia Mobile App | Betadrix
Technology

NikahNet Ethiopia Mobile App | Betadrix

READ CASE STUDY
STACK ARCHITECTURE & ENGINEERING PROCESS

Technologies & Frameworks Powering This Service

01
Model Context Protocol (MCP) Development | Enterprise AI Agent Infrastructure | Betadrix

Model Context Protocol (MCP) Development | Enterprise AI Agent Infrastructure | Betadrix

ai

Explore Tech →
02
AI Agent Development Development

AI Agent Development Development

ai

Explore Tech →
03
Enterprise RAG Systems Development | Hybrid Retrieval & Vector Search | Betadrix

Enterprise RAG Systems Development | Hybrid Retrieval & Vector Search | Betadrix

ai

Explore Tech →
04
Node.js Development Services | High-Concurrency Event-Driven Architecture | Betadrix

Node.js Development Services | High-Concurrency Event-Driven Architecture | Betadrix

backend

Explore Tech →
05
.NET Development Services | Enterprise C# & ASP.NET Core Engineering | Betadrix

.NET Development Services | Enterprise C# & ASP.NET Core Engineering | Betadrix

backend

Explore Tech →
ON-DEMAND TALENT & DEDICATED TEAMS

Hire Specialized Developers For Your Service Project

01 EXPERT TALENT
React Developers

React Developers

Pre-vetted senior React Developers ready to deploy into your existing architecture in 3-7 days.

Hire React
02 EXPERT TALENT
Flutter Developers

Flutter Developers

Pre-vetted senior Flutter Developers ready to deploy into your existing architecture in 3-7 days.

Hire Flutter
03 EXPERT TALENT
Python Developers

Python Developers

Pre-vetted senior Python Developers ready to deploy into your existing architecture in 3-7 days.

Hire Python
04 EXPERT TALENT
Nodejs Developers

Nodejs Developers

Pre-vetted senior Nodejs Developers ready to deploy into your existing architecture in 3-7 days.

Hire Nodejs
Client Reviews

What Our Clients Say

“Mobile app development and cloud migration were handled smoothly. Strong technical skills, clear communication, and dependable post-launch support stood out throughout the engagement.”

Sarah Mitchell

Sarah Mitchell

Director of Operations, HealthFirst Clinics

Instant Architecture Consultation

Have a Project in Mind?
Let's Build It Together.

Connect directly with our senior software architects and technical leads. We evaluate your requirements and deliver an actionable technical proposal within 24 hours.

Strict NDA Protection

Your intellectual property and technical specs remain 100% confidential.

24-Hour Response Guarantee

Guaranteed evaluation and scoping reply from an engineering manager.

Zero Obligation Estimate

Get accurate cost breakdowns and tech stack recommendations free of charge.

Start Your Project

Request Free Technical Consultation

+ Add File
No file chosen

We respond within 24 hours. NDA available on request.

Lead Diagnostic

Let's build something serious.

Diagnose your system architecture, budget ranges, and roadmap parameters with an expert.

AI Fit Finder

Scoping Diagnostic

Analyze your workflows in 60 seconds. A senior AI architect reviews every parameter personally.

Real Client Outcomes
+22%
Revenue Growth
$5.12M from $4.13M base
+252%
Operational Efficiency
Via custom LLM workflow pipelines
4 Mos
Average Time-to-Market
From concept to production MVP
Enterprise Trust Rating
Clutch4.9/5.0 Partner
GoodFirms4.8/5.0 Leader
Google4.9/5.0 Rated
Trustpilot4.8/5.0 Excellent

Not sure where AI actually moves the needle for you?

Answer a few brief questions. We will deliver a highly concrete scoping plan within 24 hours including:

  • Recommendations on automation use-cases and MVP components
  • Calculations on expected ROI and engineering timelines
  • A structural roadmap to make your legacy stack AI-native