PostgreSQL Hybrid Search Course – Keyword (BM25) + Vector Retrieval

freeCodeCamp.org

Summary

Beau Carnes walks through building Wiki Search, an end-to-end hybrid search engine over 241,787 Simple English Wikipedia articles stored entirely inside PostgreSQL. Starting from native GIN indexes and TS_RANK, the course introduces pg_textsearch 1.5.1 for corpus-aware BM25 ranking with block-max WAND optimization, then adds 384-dimensional semantic vectors for 25,002 articles indexed with pgvectorscale. Because BM25 scores and vector distances cannot be added directly, Carnes combines the top 20 candidates from each method in SQL using Reciprocal Rank Fusion (RRF) and serves the results with safe TS_HEADLINE previews through a pooled FastAPI backend.

Keeping articles, keyword indexes, and vector embeddings in a single PostgreSQL database eliminates external synchronization pipelines and makes newly inserted articles immediately searchable across all three modes within one ACID transaction. Viewers can extend the project by embedding the full collection, chunking long articles past their first 1,500 characters, or adding a reranker.

How time-sensitive the topic is: Evergreen

By the numbers

  • 241,787 articles: Total Simple English Wikipedia articles in the 2023-11-01.simple Hugging Face snapshot loaded into PostgreSQL. (Mentioned at 15:55)
  • 157 megabytes: Compressed download size of the Simple English Wikipedia parquet file before database expansion and indexing. (Mentioned at 16:00)
  • 1.2 parameter value: Default k1 term frequency saturation parameter in pg_textsearch for BM25 scoring. (Mentioned at 9:57)
  • 0.75 parameter value: Default b document length normalization parameter in pg_textsearch for BM25 scoring. (Mentioned at 10:17)
  • 9 milliseconds: Execution time reported by EXPLAIN ANALYZE for the BM25 index scan returning 10 ranked articles. (Mentioned at 32:06)
  • 384 dimensions: Number of vector dimensions produced per input by the local embedding model and stored in the database. (Mentioned at 39:06)
  • 1,500 characters: Number of leading article body characters passed with the title to the embedding model. (Mentioned at 38:44)
  • 25,002 articles: Maximum number of articles embedded for semantic search (the 25,000 longest plus volcano and bioluminescence). (Mentioned at 40:11)
  • 71 milliseconds: Database execution time for the Reciprocal Rank Fusion hybrid search query combining 20 keyword and 20 vector candidates. (Mentioned at 48:40)
  • 138 million passages: Dataset size in a vendor-run benchmark comparing pg_textsearch 1.0 against ParadeDB 0.21.6. (Mentioned at 57:30)

Questions this video answers

Why should you keep keyword and vector search inside PostgreSQL instead of using a separate search service?

Copying data from PostgreSQL to an external search engine introduces synchronization delays, failed events, and stale search results right after a user edits an article. Keeping articles, BM25 indexes, and vector embeddings in PostgreSQL provides a single ACID transaction boundary and lets developers combine search with standard relational SQL.

Beau Carnes, 4:06 to 6:34

From this keypoint: Beau Carnes Outlines In-Database Hybrid Search

How does Reciprocal Rank Fusion (RRF) combine BM25 scores and vector distances in SQL?

Raw BM25 scores and vector distances sit on incompatible scales and cannot be added directly. RRF retrieves the top 20 candidates from each index and assigns points based on rank position using the formula 1 / (60 + position), allowing articles that appear in both lists to rise to the top.

Beau Carnes, 43:28 to 49:12

From this keypoint: Carnes Combines Rankings with Reciprocal Rank Fusion

Why does pg_textsearch return negative numbers for BM25 scores and require ASC sorting?

The <@> operator in pg_textsearch returns the negative of the BM25 score so that stronger matches are represented by more negative numbers (for example, -20 is stronger than -5). Because PostgreSQL index scans sort ascending by default, negative scores allow an ORDER BY ASC LIMIT query to read top matches directly off the index without a separate sort step.

Beau Carnes, 27:40 to 32:32

From this keypoint: Implementing BM25 Indexes and Negative Score Sorts

How does BM25 improve on PostgreSQL's built-in TS_RANK function?

Built-in TS_RANK evaluates matching terms within an individual document without knowing how rare a term is across the entire table, and a GIN index cannot return rows in BM25 score order. BM25 incorporates collection-wide inverse document frequency, saturating term frequency (k1), and average document length normalization (b) while using block-max WAND to skip low-scoring blocks.

Beau Carnes, 6:34 to 11:39

From this keypoint: How BM25 Balances Rarity, Frequency, and Length

Why did PostgreSQL's plainto_tsquery return zero results for a multi-word volcano query?

By default, plainto_tsquery joins all surviving search words with ampersand (AND) operators, requiring every single term to appear in the article body. Switching the tsquery to use vertical bar (OR) operators or moving to BM25 ranked retrieval allows articles containing a subset of the query terms to qualify and be ranked.

Beau Carnes, 20:30 to 27:40

From this keypoint: Testing Native PostgreSQL GIN and TS_RANK Limits

Why should you load bulk data into PostgreSQL before creating BM25 and vector indexes?

Importing 241,787 articles via PostgreSQL COPY into an unindexed table and building the indexes afterward avoids updating the index structures one row at a time during ingestion. Once bulk loading completes, running ANALYZE refreshes planner statistics before index creation begins.

Beau Carnes, 15:43 to 20:30

From this keypoint: Carnes Bulk-Loads 241,787 Wikipedia Articles

How did pg_textsearch compare to ParadeDB in TigerData's 138-million-passage benchmark?

In a vendor-run benchmark over 138 million cached passages comparing pg_textsearch 1.0 with ParadeDB 0.21.6, pg_textsearch answered short queries faster and handled higher query concurrency. However, ParadeDB built its index roughly twice as fast, underscoring the need to benchmark against your own data and update patterns.

Beau Carnes, 54:06 to 1:00:16

From this keypoint: Transactional Article Writes and Scale Benchmarks

Credible AI™ signals

Confidence: Hands-On Technical Course. Beau Carnes walks through executable SQL and Python code against a pinned Hugging Face dataset of 241,787 Wikipedia articles, inspecting actual EXPLAIN ANALYZE plans and openly disclosing the TigerData grant and the trade-offs of vendor benchmarks.

Bias: Sponsor-Supported Postgres. While funded by a grant from TigerData and using Tiger Cloud for the demo, the course emphasizes that pg_textsearch is open-source, notes local setup options, and candidly presents where ParadeDB beat pg_textsearch on index build times.

Originality (78%): Complete End-to-End Build. Rather than teaching keyword and vector search in isolation, the course builds a unified Wikipedia search engine inside a single PostgreSQL database, comparing native GIN, BM25, pgvectorscale, and Reciprocal Rank Fusion side by side.

Depth (86%): Plan-Level SQL Inspection. The tutorial goes beyond surface API calls to dissect BM25 parameters (k1 and b), block-max WAND skipping, negative score sorting, CTE-based RRF math, and EXPLAIN ANALYZE BUFFERS output across search modes.

Key points (11)

  • Short (19 min): key points 1, 6, 8 and 9
  • Medium (30 min): key points 1, 2, 6, 8, 9 and 11
  • Relaxed (56 min): all 11 key points

1. Beau Carnes Outlines In-Database Hybrid Search

Timestamp: 00:04:06 to 00:06:34 (2 min)

Speaker: Beau Carnes

Beau Carnes explains that offloading search to an external service creates synchronization delays and stale reads when articles change in PostgreSQL. Keeping articles, BM25 indexes, and vectors inside PostgreSQL preserves a single transaction boundary and separates boolean matching from corpus-aware relevance ranking. Native TS_RANK lacks collection-wide document frequencies, motivating the addition of pg_textsearch.

Impact: High. Why it matters: Consolidating relational data, keyword indexes, and vectors into one database eliminates change-stream pipelines and sync lag for application teams.

“For this project, we'll keep the search indexes alongside the articles. That gives us one transaction boundary for the data and its index, and lets us combine search with the relational queries we already understand.”

In the video: Beau Carnes, at 4:46

2. How BM25 Balances Rarity, Frequency, and Length

Timestamp: 00:06:34 to 00:11:39 (5 min)

Speaker: Beau Carnes

BM25 scores documents by combining inverse document frequency for rare terms, saturating term frequency controlled by k1 (default 1.2), and document length normalization controlled by b (default 0.75). In pg_textsearch, an inverted index with block-max WAND optimization skips posting blocks that cannot beat the top results. This architecture lets ordered queries with a LIMIT clause return top matches without scoring every document.

Impact: High. Why it matters: Understanding k1, b, and block-max WAND helps engineers know when default BM25 parameters suffice and why LIMIT queries execute quickly.

“BM25 gives us a tunable model that combines term frequency with average document length and collection-wide document frequencies.”

In the video: Beau Carnes, at 6:34

3. Configuring Tiger Cloud and Required Extensions

Timestamp: 00:11:39 to 00:15:43 (4 min)

Speaker: Beau Carnes

Setting up the environment involves provisioning a PostgreSQL instance, configuring the .env connection string, and enabling pg_textsearch, vector, and vectorscale with CASCADE. Carnes stresses verifying that pg_textsearch is at version 1.5.1 before proceeding so phrase and boolean queries behave as expected. Failing the version check early prevents confusing debugging later in the build.

Impact: Low. Why it matters: Enforcing strict extension version checks during database initialization prevents subtle query syntax failures across cloud and local environments.

“This enables PG text search and vector scale. The cascade option also installs the vector dependency if it isn't already enabled.”

In the video: Beau Carnes, at 14:46

4. Carnes Bulk-Loads 241,787 Wikipedia Articles

Timestamp: 00:15:43 to 00:20:30 (5 min)

Speaker: Beau Carnes

Beau Carnes loads a pinned Simple English Wikipedia parquet snapshot of 241,787 articles from Hugging Face using PostgreSQL COPY via a staging table. The script loads all rows and runs ANALYZE before any search indexes are created, avoiding per-row index maintenance overhead during bulk import. Sanity checks confirm row counts, word counts, and demo titles are intact.

Impact: Medium. Why it matters: Loading bulk data via COPY before building search indexes dramatically reduces initial ingestion time and resource contention.

“So, for the initial import, loading the data first and building the indexes afterward avoids maintaining those indexes one insertion at a time.”

In the video: Beau Carnes, at 18:34

5. Testing Native PostgreSQL GIN and TS_RANK Limits

Timestamp: 00:20:30 to 00:27:40 (7 min)

Speaker: Beau Carnes

Using native to_tsvector with a GIN index and plainto_tsquery requires every query word to appear in the document body, returning zero matches for a five-word volcano query. Switching the tsquery operator from ampersands (AND) to vertical bars (OR) admits candidate matches that TS_RANK can order. Inspecting EXPLAIN ANALYZE BUFFERS shows how native search separates bitmap index matching from sorting.

Impact: Medium. Why it matters: Demonstrates why strict AND matching in plainto_tsquery often yields zero results on multi-word user queries and requires explicit OR handling or ranked retrieval.

“Post equal may examine and rank many matching articles before returning 10. Limit 10 controls the output size. It doesn't automatically limit all the work to 10 articles.”

In the video: Beau Carnes, at 25:38

6. Implementing BM25 Indexes and Negative Score Sorts

Timestamp: 00:27:40 to 00:32:32 (5 min)

Speaker: Beau Carnes

Creating a BM25 index with pg_textsearch uses the <@> operator to score articles against a bm25query object. Because pg_textsearch returns negative BM25 scores where more negative numbers indicate stronger matches, queries must sort in ascending order rather than descending. Comparing EXPLAIN plans confirms the BM25 index scan returns the top 10 ranked rows directly without a separate sort step.

Impact: High. Why it matters: Eliminating the separate sort node via an ordered BM25 index scan is the key architectural win of pg_textsearch over native GIN plus TS_RANK.

“PG text search returns a negative of the BM25 score, so a more negative number represents a stronger match. A score of -20 sorts before -5. That's why the query uses ascending order.”

In the video: Beau Carnes, at 29:07

7. Combined Search Columns and Safe Excerpt Previews

Timestamp: 00:32:32 to 00:37:32 (5 min)

Speaker: Beau Carnes

Carnes alters the table to add a generated search_text column combining title and body, builds the app's primary BM25 index on it, and binds user input safely via psycopg2 parameters. To explain matches to users, TS_HEADLINE generates highlighted excerpts only for the top 10 returned rows, and Python strips unsafe HTML before rendering. He also shows optional boolean NOT and phrase filters using @@ alongside BM25 ordering.

Impact: Medium. Why it matters: Generating TS_HEADLINE previews only after limiting to 10 rows prevents expensive text processing across thousands of candidate documents.

“We chose the top articles first, then prepare previews only for those results. There's no reason to prepare thousands of previews when we're showing 10.”

In the video: Beau Carnes, at 35:18

8. Generating 384-Dimensional Vectors and Indexing

Timestamp: 00:37:32 to 00:43:28 (6 min)

Speaker: Beau Carnes

For queries that describe concepts without knowing exact terms like bioluminescence, semantic search converts text into 384-dimensional vectors using a local embedding model. To keep runtime manageable, embed.py embeds the title and first 1,500 body characters for the 25,000 longest articles plus specific demo pages. After verifying zero missing embeddings in that subset, Carnes builds an approximate nearest-neighbor index using pgvectorscale.

Impact: High. Why it matters: Truncating inputs to 1,500 characters and embedding a 25,000-article subset shows practical trade-offs between compute cost and recall.

“The code takes the first 1,500 body characters and the model can shorten that further to fit its input limit. So, this search represents article introductions.”

In the video: Beau Carnes, at 38:44

9. Carnes Combines Rankings with Reciprocal Rank Fusion

Timestamp: 00:43:28 to 00:49:12 (6 min)

Speaker: Beau Carnes

Because raw BM25 scores and vector distances are not directly comparable, Beau Carnes uses Reciprocal Rank Fusion (RRF) with the formula 1 / (60 + position) to score the top 20 keyword candidates and top 20 semantic candidates. An article appearing near the top of both lists accumulates weighted points from each, outranking an article that ranks first in only one list.

Impact: High. Why it matters: Reciprocal Rank Fusion in SQL CTEs merges lexical precision and semantic recall in a single database round-trip without normalizing raw scores.

“Well, a BM25 score and a vector distance aren't directly comparable, so adding their raw numbers wouldn't give us a useful ranking. Instead, we'll use where each article appears in each list, first, second, third, and so on.”

In the video: Beau Carnes, at 43:32

10. Comparing Modes, Tuning Weights, and Pooling in FastAPI

Timestamp: 00:49:12 to 00:54:06 (5 min)

Speaker: Beau Carnes

Comparing keyword, semantic, and hybrid outputs on Apollo 13 shows hybrid search surfaces the exact mission while retaining related concepts, though Carnes notes semantic search only covers the 25,002 embedded articles. The FastAPI backend exposes a semantic_weight parameter from 0 to 1, reuses the in-memory embedding model, and maintains a connection pool of up to four prepared PostgreSQL connections. End-to-end API timings include Python query encoding alongside database execution.

Impact: Medium. Why it matters: Reusing the loaded embedding model and pooling database connections in FastAPI prevents per-request initialization bottlenecks in production.

“Keyword search covers the whole collection, but semantic search covers the articles we embedded. An article without a vector can't earn semantic points.”

In the video: Beau Carnes, at 51:31

11. Transactional Article Writes and Scale Benchmarks

Timestamp: 00:54:06 to 01:00:16 (6 min)

Speaker: Beau Carnes

Carnes tests weight tuning via curl and demonstrates inserting a new article where Python computes the embedding first and commits the text, vector, and index updates in a single PostgreSQL transaction. The new article is immediately searchable across keyword, semantic, and hybrid modes without external sync jobs. He concludes by reviewing a vendor-run 138-million-passage benchmark comparing pg_textsearch 1.0 and ParadeDB 0.21.6 and recommending chunking or rerankers as next steps.

Impact: High. Why it matters: Writing text and vectors in a single ACID transaction proves the core architectural benefit: zero lag between write commit and hybrid search visibility.

“First, the app creates its vector. Then it saves the text and vector together in a database transaction. A transaction lets us save the the change as a unit or undo it if it fails.”

In the video: Beau Carnes, at 55:56

Conflicts of interest (1)

TigerData Grant and Cloud Promotion

Commercial conflict, Medium severity

TigerData, the company behind TimescaleDB and pg_textsearch, funded this course with a grant to freeCodeCamp and provides a promotional link offering $1,000 in Tiger Cloud credits.

Sources: Beau Carnes, TigerData, freeCodeCamp

Significance: The sponsorship centers the curriculum on TigerData's pg_textsearch extension and Tiger Cloud workflow rather than competing PostgreSQL search extensions such as ParadeDB.

Key sources

  • Beau Carnes: Course creator and instructor at freeCodeCamp

Who's in this

  • TigerData
  • freeCodeCamp
  • PostgreSQL
  • pg_textsearch
  • pgvectorscale
  • FastAPI
  • ParadeDB

Also mentioned

  • Wikipedia (First mentioned at 0:01)
  • pgvector (First mentioned at 0:44)
  • Wiki Search (First mentioned at 1:09)
  • Python (First mentioned at 1:32)
  • Tiger Cloud (First mentioned at 1:38)
  • Wikimedia (First mentioned at 15:45)
  • Hugging Face (First mentioned at 15:47)
  • New Orleans (First mentioned at 26:23)
  • psycopg2 (First mentioned at 33:28)
  • TimescaleDB (First mentioned at 3:08)
  • Lucene (First mentioned at 7:55)
  • Elasticsearch (First mentioned at 7:57)
  • Creative Commons Attribution-ShareAlike 3.0 (First mentioned at 16:27)
  • GNU Free Documentation License (First mentioned at 16:29)

This analysis was generated by skim (skim.plus), an AI-powered content analysis platform by Credible AI. Scores and classifications represent the platform's AI-generated assessment and should be considered alongside other sources.