pg-smart-search
Guides

Semantic Vector Search

Integrate OpenAI or Google Gemini embeddings with pgvector for AI-powered semantic search in PostgreSQL.

Semantic Vector Search

Traditional text search relies on keyword matching. Semantic search understands the meaning behind the query. pg-smart-search integrates seamlessly with OpenAI and Google Gemini to provide vector similarity search via the pgvector PostgreSQL extension.

Prerequisites

  1. Install the pgvector extension in your PostgreSQL database.
  2. Add a vector column to your table named exactly embedding (e.g., embedding vector(1536) for OpenAI's text-embedding-3-small, embedding vector(768) for Gemini's embedding-001) — VectorStrategy's SQL hardcodes the column name embedding; it isn't configurable.
  3. Ensure your data is embedded and stored in this column.

Configuration

Configure the engine with your preferred AI provider.

import { TrigramSearchEngine, OpenAIProvider, SearchTier } from "pg-smart-search";

const engine = new TrigramSearchEngine(adapter, {
  tableName: "articles",
  searchColumns: ["content"],
  tier: SearchTier.VECTOR,
  vectorProvider: new OpenAIProvider(
    process.env.OPENAI_API_KEY,
    "text-embedding-3-small"
  ),
});
import { TrigramSearchEngine, GeminiProvider, SearchTier } from "pg-smart-search";

const engine = new TrigramSearchEngine(adapter, {
  tableName: "articles",
  searchColumns: ["content"],
  tier: SearchTier.VECTOR,
  vectorProvider: new GeminiProvider(
    process.env.GEMINI_API_KEY,
    "embedding-001"
  ),
});

Querying

When tier: SearchTier.VECTOR is set, the engine generates an embedding for the query and performs a pure cosine-similarity search (ORDER BY embedding <=> $1::vector) against your embedding column. This tier is exclusive, not combined with FTS/trigram — a VECTOR-tier call doesn't also run a text search alongside it. To offer both, run the two searches yourself (e.g. a VECTOR-tier engine and a STANDARD-tier engine against the same table) and merge results in your application.

const results = await engine.search({
  query: "How to optimize database performance",
});

Rate Limiting

AI APIs have strict rate limits. The engine includes an intelligent rate-limiting queue (p-queue) built-in. If the API returns 429 Too Many Requests, the engine automatically pauses vector search requests and retries them, preventing cascade failures.