/blogs/postgresql-vs-elasticsearch-understanding-search-at-scale

← Back to blogs
Blog

PostgreSQL vs Elasticsearch: Understanding Search at Scale

Learn why traditional SQL searches slow down at scale, how inverted indexes work, why relevance scoring matters, and when to use PostgreSQL Full-Text Search v/s Elasticsearch for production search workloads.

·6 min read·

Relational Databases Are Bad at Text Search

You start with a simple product search. Your catalog has a few thousand rows. You write a quick query:

>_ text
SELECT * FROM products 
WHERE name ILIKE '%laptop%' OR description ILIKE '%laptop%';

It returns results in 50 milliseconds. Everything works fine.

A year later, your catalog grows to 10 million products. That exact same query now takes 30 seconds. Your database CPU spikes, users bounce, and you have to figure out why your search is broken.

To make it worse, the product team wants new features. They want typo tolerance. They want type-ahead search. They want a "MacBook Pro" to rank higher than a "laptop bag".

A standard relational database cannot handle these requirements efficiently. Here is why, and how search engines actually solve the problem.

#The Problem with LIKE

Think of a relational database executing a LIKE '%term%' query as a librarian who has to read every single book in the library from cover to cover just to find a specific word.

The database performs a full table scan. It reads every single row, examines the text fields, and performs character-by-character pattern matching.

This approach has two major problems:

  1. It is incredibly slow at scale. Scanning millions of rows character by character destroys performance.
  2. It has no concept of relevance. The database returns every match in whatever order it finds them. A textbook titled Introduction to Machine Learning ranks exactly the same as a cookbook that mentions the phrase once on page 400.

#The Inverted Index

During the early 2000s, companies processing billions of web pages needed millisecond search latency. They could not rely on full table scans.

The solution was to invert the problem. Instead of mapping documents to the words inside them, search engines map words to the documents that contain them. This data structure is an inverted index.

When a document is ingested, the search engine extracts every word and records which document IDs contain it, and exactly where it appears.

Rendering diagram...

When a user searches for "laptop", the engine looks up the term in the index and instantly retrieves the list of document IDs. No full table scan is required.

#Relevance and BM25

Finding the documents is only half the battle. You need to sort them. If someone searches for "laptop", a product named "Laptop Stand" should beat a product where "laptop" is buried in the description.

Tools like Elasticsearch use the BM25 algorithm for this. You do not need to memorize the math, but you need to know the levers it pulls:

  • Term Frequency: How often the term appears in the specific document. More occurrences usually mean higher relevance.
  • Inverse Document Frequency: How common the term is across all documents. Rare words carry more weight than common words.
  • Document Length: Shorter documents are weighted more heavily. If a short product title contains the search term, it is likely more relevant than a massive manual that happens to contain the word once.
  • Field Boosting: You can assign higher weights to specific fields. A match in the title field can be configured to score higher than a match in the description field.

#Handling Typos

SQL is strict. If a user types "laptap", an ILIKE query returns zero results.

Search engines handle this using fuzzy matching. They analyze the context of the query, identify probable typos, and return results for the intended term. This is what powers type-ahead search bars, allowing them to return relevant suggestions while the user is still typing, even if they make spelling mistakes.

#PostgreSQL vs. Elasticsearch: A Real Benchmark

To see the performance difference in practice, I built a test comparing a standard relational database search against an Elasticsearch cluster.

The setup:

  • Database: Neon Serverless PostgreSQL
  • Search Engine: Elastic Cloud
  • Dataset: 50,000 product reviews (text and sentiment)
  • Location: Both hosted in us-west to eliminate network latency variables.

The Queries

For PostgreSQL, I used a standard case-insensitive pattern match:

>_ text
SELECT id, review, sentiment 
FROM reviews 
WHERE review ILIKE '%search_term%';

For Elasticsearch, I used a query string search:

>_ text
{
  "query": {
    "query_string": {
      "query": "*search_term*",
      "fields": ["review"]
    }
  }
}

The Results

I ran queries for different terms and measured the response times.

Search TermTotal ResultsPostgreSQL TimeElasticsearch Time
laptop~12,0003.1 seconds1.0 second
something~8,0007.5 seconds0.5 seconds

The relational database took seconds to return a few thousand rows. Elasticsearch returned the same results in milliseconds. The gap widens significantly as the dataset grows and the queries become more complex.

#Choosing the Right Tool

You do not always need to abandon your relational database to add search capabilities. PostgreSQL includes built-in Full Text Search using tsvector and tsquery. It is highly capable and keeps your architecture simple. If your search needs are basic, keep it in Postgres. Do not add infrastructure you do not need.

However, if your search requirements include complex fuzzy matching, deep relevance tuning, or massive scale, you need a dedicated search engine.

Elasticsearch is the standard choice for these heavy workloads. It is also the core of the ELK stack (Elasticsearch, Logstash, Kibana). If your company already runs Elasticsearch for log management, using it for application search avoids introducing a new technology to your stack.


Your primary focus should be mastering your relational database. Understanding B-trees, query execution plans, and indexing will solve 99% of your daily backend problems.

You do not need to read the academic papers behind the BM25 algorithm or understand the internal memory management of Apache Lucene. When you encounter a search problem, understand the underlying concepts of the inverted index and relevance scoring. Then, read the documentation for your chosen tool, implement the query, and build the feature.

Relational databases require deep mastery. Search engines require functional understanding. Know the difference, and use the right tool for the job.

965 words left