Site search without Algolia: Postgres full-text and Laravel Scout

Core45 ·

PostgreSQL can power good site search on its own: weighted full-text for relevance, trigrams for typos and optional vectors for meaning, with Laravel Scout keeping the engine swappable. Here is how the pieces fit, and when a hosted service is still the better choice.

A site search box looks like a small feature until you build it. The first version is a LIKE '%term%' query, it works on ten rows, and then the catalogue grows, someone types a word with a typo, and the results come back empty or in a random order. The usual next step is to sign up for a hosted search service, and for many projects that is a fair choice. For many others it adds a second system, a second bill and a second copy of your data for a problem the database could have solved.

We build custom web applications on Laravel, and for a large share of them the database is already PostgreSQL. This article explains what PostgreSQL can do for search on its own, where it falls short, and how a hybrid approach with Laravel Scout closes most of the gap, so you can decide whether you need Algolia at all.

Site search without Algolia: the short answer

For a catalogue, a content site or an internal tool of modest size that already runs on PostgreSQL, you can usually build good search inside the database: weighted full-text search for relevance, trigram matching for typos, and optionally vector embeddings for meaning. Laravel Scout keeps your application code independent of the engine. Choose a dedicated search service when you need facet counts, result highlighting, geographic search or a search tier that scales apart from your main database.

Why LIKE is not enough

A pattern with a leading wildcard cannot use an ordinary B-tree index, so the database scans every row. It also has no idea of relevance: a word in a product name and a word buried in a long description look the same. And it matches strings, not language, so a search for one word form does not find another.

PostgreSQL has had an answer for a long time. Its built-in full-text search converts text into a tsvector of normalised words, converts the query into a tsquery, and matches the two. A GIN index makes the match fast, and ranking functions order the results.

Search box on a laptop screen with a list of ranked results below it
Good site search is mostly about ranking: the right result first, even when the query is imperfect.

What PostgreSQL full-text search gives you

  • Stemming per language. With the english configuration, a search for "running" can match "run", because words are reduced to a base form.
  • Weights. You can mark the title as weight A and the body as weight D, so a hit in a title ranks above a hit in a long description.
  • A readable query syntax. websearch_to_tsquery accepts the kind of input people type into a search box, including quoted phrases, or and a minus sign to exclude a word, without throwing a syntax error at a stray character.
  • Ranking. ts_rank_cd orders the matches by how well they fit.

A minimal version looks like this:

CREATE EXTENSION IF NOT EXISTS pg_trgm;

ALTER TABLE articles ADD COLUMN search_vector tsvector
  GENERATED ALWAYS AS (
    setweight(to_tsvector('english', coalesce(title, '')), 'A') ||
    setweight(to_tsvector('english', coalesce(body, '')), 'D')
  ) STORED;

CREATE INDEX articles_search_idx ON articles USING gin (search_vector);

SELECT id, title
FROM articles
WHERE search_vector @@ websearch_to_tsquery('english', 'yoga mat')
ORDER BY ts_rank_cd(search_vector, websearch_to_tsquery('english', 'yoga mat')) DESC
LIMIT 20;

That is already a real improvement over LIKE, and it needs no extra service. It does not fix everything, which is where the other two techniques come in.

Typos and missing accents: trigram matching

Full-text search matches words that are spelled right. A visitor who types a word with a typo, or without the diacritics your content uses, finds nothing. The pg_trgm extension compares strings by the three-letter fragments they share, so near-misses still score. Its word_similarity function suits a short query compared against a multi-word title.

Trigrams also help where stemming does not exist. PostgreSQL ships no Polish stemmer, so a Polish site falls back to the simple configuration, which does no stemming at all. Trigrams relate joga and jogi because they share letters, not because they understand Polish grammar, and for finding inflected words that is often enough. If you run a site in several languages, our notes on multilingual website SEO cover the content side of the same problem.

The third technique is optional. With the pgvector extension, each document can carry an embedding, a list of numbers produced by an embedding model, and a query is matched by cosine distance. This finds "waterproof jacket" when the page says "rain coat". It needs an embedding provider, which is a paid and rate-limited network call, so it should never sit on the path where a record is saved. Treat it as an extra that you add once the first two are working, not as the foundation.

Combining the rankings without guessing

Once you have two or three result lists, the temptation is to add their scores. That does not work: ts_rank_cd, word_similarity and cosine similarity live on different scales, so the sum means nothing. A sturdier method is reciprocal rank fusion. Each list is numbered by position, a document scores weight / (k + rank) in every list where it appears, and the scores are summed. Positions are comparable even when raw scores are not, and a document that ranks reasonably in all lists beats one that tops a single list.

TechniqueGood atWeak at
Full-text (tsvector)Relevance, stemming, weighted fields, phrasesTypos; languages without a stemmer
Trigrams (pg_trgm)Typos, missing accents, inflected formsLong queries; knowing what matters most
Vectors (pgvector)Synonyms and meaningExact codes and names; needs an embedding provider
Fusion of all threeRobust results across query typesMore moving parts to tune

Where Laravel Scout fits

Laravel Scout is the framework's search layer. A model gets a trait, and your code says Product::search('yoga mat'). The engine behind that call is a configuration value, so you can start with search in your own database and move to a hosted engine later by changing the driver, not by rewriting every query. That is the main argument for using Scout even when you do not use a separate server today.

We needed exactly this setup often enough that we packaged it: an open-source Scout engine that keeps the whole index in one PostgreSQL table, with weighted full-text, trigram matching and optional semantic search fused by reciprocal rank fusion. Its design, limits and installation guide are on the Laravel Scout Postgres Hybrid project page. The decisions that matter in a build like this are worth copying even if you write your own:

  • Keep embeddings off the save path, so an outage at the provider never blocks an edit.
  • Apply filters inside each search branch, not after the limit, or narrow queries come back short.
  • In a multi-tenant application, make the tenant a real column with a real predicate, and refuse to search when it cannot be resolved instead of widening the query.

When a dedicated search service is the better choice

Keeping search in the database is a trade, not a rule. A dedicated engine such as Meilisearch, Typesense, Algolia or Elasticsearch is worth the extra infrastructure when:

  • you need facet counts, result highlighting or geographic search;
  • search traffic is heavy enough that it should not share resources with your main database;
  • the corpus is very large and you need an approximate vector index;
  • your application does not run on PostgreSQL, or you cannot install the extensions you need.

The approach above has its own limits. The semantic branch in our package is an exact scan, so its cost grows with the number of embedded rows you query, and the extensions pg_trgm, unaccent and vector need a role that is allowed to create them, which on managed PostgreSQL often means asking the provider or an administrator.

A practical order of work

  1. Measure first. Collect the real queries your visitors type, and the ones that return nothing.
  2. Start with full-text. Add a weighted tsvector column and a GIN index, and use the right language configuration for each locale.
  3. Add trigrams if your logs show typos, missing diacritics or a language without a stemmer.
  4. Add semantic search last, and only if people search by meaning rather than by name.
  5. Test on real PostgreSQL. SQLite has no equivalent of these features, so a test that passes there proves nothing about search.
  6. Review the results by hand with a list of typical queries, before and after each change.

Search also supports the rest of the site. Good internal search keeps visitors on pages and shows you what they cannot find, and the rules for crawlable pages in our technical SEO checklist apply to result pages too. Why we choose this framework for such work is covered in why Laravel for business applications.

What to do next

List what you want people to find, in which languages, and how many records there are. That short list usually shows whether PostgreSQL can carry the search or whether a hosted engine is justified, before any money is spent.

If you want search built into your application, see our web application development service, or contact us and describe the problem. We will tell you plainly whether the database you already have is enough.

Common questions

Do I need Algolia for site search in a Laravel application?

Not always. If your application already runs on PostgreSQL and the content is of modest size, full-text search with trigram matching inside the database is often enough. A hosted engine is worth it when you need facet counts, highlighting, geographic search or a search tier that scales apart from your main database.

Can Laravel Scout use PostgreSQL?

Yes. Scout lets you choose the engine through configuration, and an engine can store its index in PostgreSQL. Your code keeps calling Model::search(), so moving to another engine later is a driver change rather than a rewrite. Our open-source package does this; see its project page.

How does PostgreSQL search handle typos?

Plain full-text search does not, because it matches correctly spelled words. The pg_trgm extension compares the three-letter fragments strings share, so near-misses and missing accents still match. Combining it with full-text search covers both relevance and typos.

Is semantic search with pgvector required?

No. It is an optional third branch that needs an embedding provider, which is a paid and rate-limited call. Start with weighted full-text and trigrams, and add vectors only if people search by meaning rather than by name. If you want search built into your application, see our web application development service.

Got a project that needs to move?

Tell us what you want to build or improve. We will reply with specifics: what we suggest, in what order, and what we will need from you.