← All posts

Adding semantic search to your SaaS with embeddings (PostgreSQL, pgvector, PHP): setup and pitfalls

Users search for "cancel my subscription" while your docs say "end your plan"? Embeddings let search match meaning instead of words. Storage with pgvector, generation in PHP, per-tenant filtering, hybrid search and production pitfalls.

Adding semantic search to your SaaS with embeddings (PostgreSQL, pgvector, PHP): setup and pitfalls

Key points

  • An embedding turns text into a vector: texts with similar meaning get nearby vectors, even with no words in common.
  • With pgvector, vectors live in PostgreSQL next to your data, with the usual tenant filtering and transactions.
  • Semantic search alone misses exact references, so pair it with classic keyword search.

Search in most applications runs on words: LIKE, the database’s full-text search, or a dedicated engine. It breaks down as soon as users phrase things differently from the content. They type “cancel my subscription” and the help article is called “Ending your plan”; they look for “charged twice” and the ticket says “duplicate payment”. Embeddings, numerical representations of a text’s meaning produced by an AI model, fix exactly this. We’ve shipped them on knowledge bases, support tickets and product catalogues. Here’s how to build it properly in a PHP and PostgreSQL application, and what production taught us.

What embeddings give you, and what they don’t

An embedding model turns text into a list of numbers, a vector, and it’s trained so that texts with similar meaning produce vectors that sit close together. Searching then means turning the query into a vector and finding the nearest stored vectors, usually by cosine distance.

What you gain: synonyms, rephrasing, minor typos, and often queries in a different language from the content. What it handles badly: exact references. An invoice number, a SKU or a function name has no “meaning”, so semantic search returns documents about invoices in general, not the one the user wants. That’s why on our projects it complements existing search rather than replacing it.

It’s also the foundation of assistants that answer from your documentation: you first retrieve relevant passages with embeddings, then hand them to a language model. Reliable retrieval is a prerequisite, not a detail.

Storing vectors in PostgreSQL with pgvector

You don’t need a separate vector database to start. The pgvector extension gives PostgreSQL a vector type, distance operators and suitable indexes. Vectors stay next to your data, covered by the same backups, transactions and tenant filtering, and most managed PostgreSQL hosts offer the extension.

CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE doc_chunks (
  id            bigserial    PRIMARY KEY,
  tenant_id     bigint       NOT NULL,
  document_id   bigint       NOT NULL REFERENCES documents (id) ON DELETE CASCADE,
  content       text         NOT NULL,
  content_hash  char(64)     NOT NULL,  -- sha256 of the text: skip recomputing
  model         text         NOT NULL,  -- model that produced the vector
  embedding     vector(1536) NOT NULL
);

-- Approximate (HNSW) index for cosine distance, plus a regular per-tenant index
CREATE INDEX ON doc_chunks USING hnsw (embedding vector_cosine_ops);
CREATE INDEX ON doc_chunks (tenant_id, document_id);

We don’t store one vector per document but one per chunk. A multi-page help article produces a blurry vector that matches no specific question well. We split along the content’s structure, by section or group of paragraphs, and keep the section heading inside each chunk so it retains its context.

The content_hash and model columns are there for maintenance. The first saves you paying the API again when a document is re-saved unchanged; the second tells you which vectors to recompute when you switch models.

Generating embeddings in PHP

Embeddings come from an HTTP call to the provider’s API. This example uses OpenAI’s; other providers work the same way with a different URL and payload. Sending several chunks per call cuts the number of requests sharply during the initial indexing:

<?php
function embed(array $texts): array
{
    $ch = curl_init('https://api.openai.com/v1/embeddings');
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_HTTPHEADER     => [
            'Authorization: Bearer ' . getenv('OPENAI_API_KEY'),
            'Content-Type: application/json',
        ],
        CURLOPT_POSTFIELDS => json_encode([
            'model' => 'text-embedding-3-small',   // 1536 dimensions
            'input' => array_values($texts),       // several chunks in one call
        ], JSON_THROW_ON_ERROR),
    ]);
    $body   = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if ($body === false || $status !== 200) {
        throw new RuntimeException("Embeddings API: HTTP $status");
    }
    $data = json_decode($body, true, 512, JSON_THROW_ON_ERROR)['data'];
    usort($data, fn ($a, $b) => $a['index'] <=> $b['index']);

    return array_column($data, 'embedding');
}

// pgvector accepts a vector as text: '[0.12,-0.03,...]'
function to_pgvector(array $vector): string
{
    return '[' . implode(',', $vector) . ']';
}

Never make this call while the user is saving a document. We push a job onto the queue: it chunks the document, compares hashes with the existing chunks, calls the API only for new or changed ones, then swaps the rows in a single transaction. If the API is slow or down, the user never notices and the job simply retries. A full, resumable indexing command handles the first backfill and model changes.

Searching: tenant filtering and hybrid ranking

The search embeds the user’s question, then asks for the nearest chunks, always restricted to the current tenant:

<?php
$vector = to_pgvector(embed([$userQuery])[0]);

// Two separate placeholders: with PDO's native prepared statements,
// the same named placeholder can't be used twice.
$stmt = $pdo->prepare(
    "SELECT document_id, content,
            1 - (embedding <=> CAST(:v1 AS vector)) AS similarity
       FROM doc_chunks
      WHERE tenant_id = :tenant
      ORDER BY embedding <=> CAST(:v2 AS vector)
      LIMIT 8"
);
$stmt->execute(['v1' => $vector, 'v2' => $vector, 'tenant' => $tenantId]);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

<=> returns cosine distance, and the ORDER BY must use that expression directly for the HNSW index to kick in. Watch the tenant filter: because the index is approximate, it picks nearby candidates first and applies the WHERE afterwards. With many tenants you can end up with fewer than 8 rows. Recent pgvector versions offer iterative scans (SET hnsw.iterative_scan = relaxed_order), which keep searching until enough rows qualify. Check your version, and test with your smallest customer.

To cover exact references, we run a classic full-text search alongside and merge the two lists. A simple, robust approach is to give each document a score that shrinks with its rank in each list and add them up. Documents ranked well in both rise to the top, and an invoice number found by keyword search doesn’t get buried.

Pitfalls we hit in production

  • Switching models means re-embedding everything. Vectors from two different models aren’t comparable. Plan a full reindex into a new column or table, then switch over in one go.
  • Privacy. Your customers’ text is sent to the API provider. Check its terms on retention and training use, sign the data processing agreement, and list the provider as a sub-processor in your privacy policy. For highly sensitive data, a self-hosted embedding model is a realistic option.
  • Cost. Usually modest next to text generation, but it scales with how much you index and re-index. Measure it during your first backfill instead of guessing, and keep the hash-based cache.
  • Deletions. A deleted document, or one the user lost access to, must vanish from results. The foreign key with ON DELETE CASCADE handles deletion; finer-grained permissions have to be enforced in the query.
  • Measuring quality. Build a list of real user questions, taken from tickets or searches that returned nothing, each with the document you expect. Re-run it whenever you change chunking or models; it’s the only way to know whether a change actually helps.

FAQ

Do I need a dedicated vector database?

Not to start. pgvector handles the volumes of most SaaS products comfortably and saves you another system to keep in sync. A dedicated option makes sense at very large scale, or if you’re not on PostgreSQL.

Can I use embeddings with MySQL?

Recent MySQL and MariaDB releases add vector types and functions, with maturity varying by version. Check exactly what yours supports; otherwise an external vector index kept in sync through a job queue still works.

Does this replace a chatbot?

It’s the first step towards one. Semantic search finds the right passages; a conversational assistant then uses them to write an answer. Without good retrieval, the assistant misses the point.

Want your users to finally find what they’re looking for in your application? We add AI to existing SaaS products with care: semantic search and assistants grounded in your content, with real tracking of quality and cost.

Share LinkedIn Facebook X WhatsApp
</>

webtestudio

Web agency: custom WordPress sites, premium themes and SaaS software.

Discuss your project →