A small, explainable proof-of-concept that answers one question:
How much Elasticsearch full-text search can you reproduce in PostgreSQL — and how close are the results?
Phase 1 focuses on the most important capability: BM25 full-text search. The exact same 1,000 documents and the exact same queries are run against three engines, and the results, ranking, BM25 scores and latency are compared side-by-side.
frontend.mov
| Engine | What it is | Runs on |
|---|---|---|
| Elasticsearch | The baseline we migrate away from | local Docker |
PostgreSQL + pg_search |
ParadeDB's BM25 extension (@@@, paradedb.score) |
local Docker |
PostgreSQL + pg_textsearch |
BM25 extension using the <@> operator + bm25 access method |
local Docker |
Headline result (1,000 docs, 8 queries, top-10, this machine):
| Engine | Top-5 overlap vs ES | Top-10 overlap vs ES | Rank corr (ρ) | Avg latency |
|---|---|---|---|---|
PostgreSQL + pg_search |
92% | 95% | 0.91 | ~1.7 ms |
PostgreSQL + pg_textsearch |
92% | 92% | 0.92 | ~6.7 ms |
Once the analyzer and field basis are aligned (see Why the results match), both PostgreSQL extensions reproduce Elasticsearch BM25 ranking at ~95% top-10 overlap — comfortably past the 80% PoC target — and often return nearly identical BM25 scores.
⚠️ 1,000 documents is a functional-equivalence PoC, not a performance benchmark. Latency numbers show orders of magnitude, nothing more.
flowchart TD
DS["Dataset generator<br/>1,000 documents (seeded)"] --> J["data/documents.json"]
J --> L["scripts/load_all.py"]
L --> ES["Elasticsearch :9210<br/>inverted index + BM25"]
L --> PS["PostgreSQL + pg_search :5442<br/>ParadeDB BM25 index"]
L --> PT["PostgreSQL + pg_textsearch :5443<br/>bm25 access method"]
subgraph APP["FastAPI :8810"]
REG["Engine registry<br/>(pluggable: bm25 today; vector/geo/fuzzy next)"]
CMP["Comparison layer<br/>top-K overlap · Spearman ρ · latency"]
end
ES --> REG
PS --> REG
PT --> REG
REG --> CMP
CMP --> UI["Web UI + CLI benchmark<br/>side-by-side results"]
Per-query request flow:
sequenceDiagram
participant U as User / CLI
participant API as FastAPI
participant ES as Elasticsearch
participant PS as pg_search
participant PT as pg_textsearch
participant C as Comparison layer
U->>API: GET /api/compare (q="distributed systems", k=10)
par same query, three engines
API->>ES: match(all_text) → hits + _score
API->>PS: WHERE search_text @@@ q → paradedb.score
API->>PT: ORDER BY search_text <@> to_bm25query(q) → BM25
end
API->>C: results (ids, scores, latency)
C-->>API: top-5/10 overlap + rank correlation
API-->>U: side-by-side comparison JSON
| Service | Host port | Container |
|---|---|---|
| Elasticsearch | 9210 |
es2pg-elasticsearch |
PostgreSQL + pg_search |
5442 |
es2pg-paradedb |
PostgreSQL + pg_textsearch |
5443 |
es2pg-pgtextsearch |
| FastAPI app | 8810 |
(host) |
Prerequisites: Docker, uv. No local psql needed.
make up # build + start Elasticsearch, ParadeDB, pg_textsearch
make setup # create the venv and install deps (uv sync)
make dataset # generate data/documents.json (1,000 docs)
make load # create schema + indexes and load all three engines
make bench # run the fixed query set → prints tables + writes REPORT.md
make serve # FastAPI + web UI at http://localhost:8810Open http://localhost:8810, type a query, and watch the three engines rank
the same documents. A green outline marks documents that also appear in the
Elasticsearch top-10. Click any result to expand it: you'll see the document
text with the matched terms highlighted by that engine's own analyzer (ES
highlight API, ParadeDB paradedb.snippet, ts_headline('english') for
pg_textsearch), plus a plain-language "why" — e.g. "matched 4 instances of
consistency in a 54-word document; BM25 rewards high term frequency in a short
document." This is what explains surprising rankings (like a doc titled
"partitions" topping a search for "consistency").
First-time note on
pg_textsearch: its prebuilt.soislinux/amd64only and links againstglibc 2.38, so the image is builtFROM postgres:17-trixieand pinned tolinux/amd64(runs under emulation on Apple Silicon — fine for 1,000 docs). Seedocker/pg_textsearch/Dockerfile.
Exactly 1,000 seeded documents spread evenly across 12 tech topics (Python, PostgreSQL, Elasticsearch, distributed systems, AWS, Kubernetes, Docker, ML, databases, backend, cloud, software engineering). Generation is deterministic, so every engine loads byte-for-byte identical data.
{
"id": 1,
"title": "A Practical Guide to Python",
"content": "A common mistake is ignoring asyncio until cluster and asyncio start to fail. ...",
"category": "python",
"author": "Liam Ahmed",
"tags": ["asyncio", "packaging", "pytest"],
"created_at": "2025-02-14"
}| Elasticsearch field type | PostgreSQL column type |
|---|---|
integer |
INTEGER PRIMARY KEY |
text (title, content) |
TEXT |
keyword (category, author) |
TEXT |
keyword[] (tags) |
TEXT[] |
date |
DATE |
| (combined searchable text) | `TEXT GENERATED ALWAYS AS (title |
All three are configured with the same BM25 parameters (k1 = 1.2,
b = 0.75) and the same English analyzer/stemmer, so the comparison is fair.
CREATE EXTENSION pg_search;
CREATE INDEX documents_bm25 ON documents
USING bm25 (id, (search_text::pdb.simple('stemmer=english')), title, category, author)
WITH (key_field = 'id');
SELECT id, title, paradedb.score(id) AS score
FROM documents
WHERE search_text @@@ 'distributed systems'
ORDER BY score DESC
LIMIT 10;CREATE EXTENSION pg_textsearch; -- needs shared_preload_libraries = 'pg_textsearch'
-- one text column per index → search a generated combined column
CREATE INDEX documents_bm25 ON documents USING bm25(search_text)
WITH (text_config = 'english', k1 = 1.2, b = 0.75);
SELECT id, title,
-(search_text <@> to_bm25query('distributed systems', 'documents_bm25')) AS score
FROM documents
ORDER BY search_text <@> to_bm25query('distributed systems', 'documents_bm25')
LIMIT 10;
-- the <@> operator returns the NEGATED BM25 score (so ascending ORDER BY = best first)Migration is not Elasticsearch → PostgreSQL; it is Elasticsearch query model
→ PostgreSQL query model:
| Concept | Elasticsearch | pg_search | pg_textsearch |
|---|---|---|---|
| Full-text match | match / multi_match |
@@@ operator |
<@> operator |
| Relevance score | _score |
paradedb.score(id) |
-(col <@> to_bm25query(...)) |
| Rank | sort: _score desc (default) |
ORDER BY score DESC |
ORDER BY col <@> ... (asc, negated) |
| Multi-field | fields: [title^2, content] |
multiple @@@ / boosts |
generated combined column |
| Analyzer | analyzer: english |
pdb.simple('stemmer=english') |
text_config = 'english' |
| Index | inverted index (Lucene) | USING bm25 ... WITH (key_field) |
USING bm25(col) access method |
| Elasticsearch | pg_search (ParadeDB) | pg_textsearch | |
|---|---|---|---|
| Index type | Lucene inverted index | Tantivy BM25 index | custom bm25 access method |
| Multi-column | native (per-field) | native (list columns) | single column → use a generated column |
Custom k1/b |
per-similarity | Tantivy defaults (1.2 / 0.75) | WITH (k1=…, b=…) |
| Stemming | analyzers | per-column tokenizer cast | text_config |
| Updates | near-real-time refresh | transactional (index maintained on write) | transactional |
| Extra infra | separate JVM cluster | none — it's Postgres | none — it's Postgres |
A naïve migration (ES standard analyzer + multi_match best_fields) lands
around ~50% top-10 overlap — the engines disagree because:
- ES's default
standardanalyzer does not stem (systems≠system), while both PG extensions stem via their English config. - ES
multi_match best_fieldsscores each field separately and takes the max, whereas the PG engines score one combined text field.
Aligning two things — a decision a real migration makes deliberately — pushes overlap to ~95%:
- Same analyzer:
english(stemming + stopwords) everywhere. - Same basis: score one combined field. ES uses
copy_to: all_text; both PG engines use the generatedsearch_textcolumn.
This is the core migration lesson: BM25 math is portable; the tokenizer and field strategy are what you actually have to port.
- Identify the ES index — mapping, analyzers, similarity, queries.
- Export documents to JSON.
- Map ES field types → PostgreSQL columns (table above).
- Load the same documents into PostgreSQL.
- Install a search extension (
pg_searchand/orpg_textsearch). - Create the BM25 index (mind single- vs multi-column).
- Translate the Query DSL into SQL (translation table above).
- Validate with top-K overlap, rank correlation, latency (
make bench). - Document what is equivalent, partial, or unsupported.
- Can PostgreSQL do Elasticsearch-style BM25? — Yes, via
pg_searchorpg_textsearch. - Are results identical? — Not by default (~50% overlap); with aligned analyzer + field basis, ~95% and near-identical scores.
- Can the Query DSL be dropped in as-is? — No. The app's search layer must translate the ES query model into SQL.
- Can Elasticsearch be removed entirely? — Depends on the workload. BM25 search migrates cleanly; other ES features are future phases below.
The engine layer is the extensibility seam. Every backend implements
SearchEngine and declares its Capability set
(bm25, and later vector, geo, fuzzy, filter). Adding a capability =
register one new engine; the comparison layer, API and UI are untouched.
| Future phase | Elasticsearch feature | PostgreSQL answer |
|---|---|---|
| Fuzzy / autocomplete | fuzziness, prefix | pg_trgm |
| Vector / semantic | dense_vector, kNN |
pgvector (HNSW / IVFFlat) |
| Hybrid | BM25 + vectors | pg_search/pg_textsearch + pgvector |
| Geospatial | geo_point, geo queries |
PostGIS |
| Nested / JSON | object / nested | JSONB |
| Aggregations | terms/range/metrics | GROUP BY, FILTER, window functions |
.
├── compose.yaml # ES + ParadeDB + pg_textsearch (non-clashing ports)
├── docker/pg_textsearch/ # builds pg_textsearch into postgres:17-trixie (amd64)
├── app/
│ ├── config.py # pydantic-settings (.env)
│ ├── models.py # Document / SearchHit / metrics schemas
│ ├── dataset.py # deterministic 1,000-doc generator
│ ├── queries.py # the fixed query set
│ ├── compare.py # top-K overlap + Spearman rank correlation
│ ├── main.py # FastAPI + web UI
│ └── engines/ # the extensibility seam
│ ├── base.py # SearchEngine ABC + Capability + registry
│ ├── elasticsearch_engine.py
│ ├── pg_search_engine.py
│ ├── pg_textsearch_engine.py
│ └── pg_common.py # shared table + pooled connections
├── scripts/ # generate_dataset · load_all · benchmark
├── web/index.html # self-contained side-by-side comparison UI
└── Makefile
pg_textsearchneedsshared_preload_librariesand PostgreSQL 17/18; its release.soisamd64+glibc 2.38→ build onpostgres:17-trixie.pg_textsearchindexes one text column and has no expression indexes → the generatedsearch_textcolumn is the documented workaround.<@>returns the negated BM25 score — order ascending, negate for display.- Connection pooling matters for latency: a fresh connection per query added ~30 ms; pooling drops PG query latency to low single-digit ms.
- Fair comparison = same analyzer + same field basis. Change either and overlap drops — that's the point, not a bug.
- Everything runs in local Docker containers — no external/cloud database is required or used.