Full-Text Search: PostgreSQL FTS vs Elasticsearch
"Full text indexing allows documents to be preprocessed and an index saved for later rapid searching." — PostgreSQL documentation, 12.1. Introduction (Full Text Search)
Summary: Full-text search finds documents by the words they contain, ranks them, and tolerates inflection and (in some engines) typos, by looking words up in an inverted index instead of scanning text. Focus: The inverted index and analysis chain, ranking (TF-IDF, BM25, ts_rank), PostgreSQL FTS with pg_trgm, pg_bigm and ParadeDB, Elasticsearch and OpenSearch internals, Meilisearch and Typesense, MySQL FULLTEXT and SQLite FTS5, Persian text, autocomplete, hybrid search, keeping an index in sync, and Laravel Scout and Go clients. Learning goal: Choose between database-native search and a dedicated engine, configure analysis correctly for your languages, and keep a derived index trustworthy.
This page is the complete reference for searching text in a database-backed system. It covers the building blocks every engine shares (inverted index, postings, tokenization, normalization, stop words, stemming and lemmatization, n-grams), the ranking functions (TF-IDF, BM25 with k1 and b, ts_rank and ts_rank_cd, field weights), what PostgreSQL really gives you (tsvector, tsquery, dictionaries, configurations, GIN versus GiST, generated columns, websearch_to_tsquery, phrase search, ts_headline, and the limits), the extensions that fill its gaps (pg_trgm, pg_bigm, ParadeDB pg_search), Elasticsearch and OpenSearch (shards, segments, refresh, analyzers, mappings, relevance tuning, aggregations), Meilisearch and Typesense, MySQL FULLTEXT with the ngram parser, SQLite FTS5, Persian and Arabic problems (ZWNJ, diacritics, the two spellings of ی and ک), autocomplete, hybrid search with Reciprocal Rank Fusion, how to keep an index in sync with the database (dual write, CDC, the outbox), and Laravel Scout and the Go clients. How a B-tree or GIN index is laid out is in Indexing; embeddings and nearest-neighbour search are in Vector Search & pgvector; scoring at the scale of a search product (personalization, learning to rank) is in Search Systems. SQLite as an engine is in SQLite in Depth and the MySQL engines in MySQL Storage Engines.
Page map
| If you are looking for | Go to |
|---|---|
| A table you can memorise in one minute | Everything in one minute |
| Why LIKE is not search and what the trade-off is | Why full-text search exists |
| Where inverted indexes and BM25 come from | Where it comes from |
| Inverted index, postings, analysis, stemming, n-grams | The concepts, one by one |
| ZWNJ, diacritics, ی and ک variants | Persian and Arabic text |
TF-IDF, BM25, ts_rank, weights | Ranking |
| Autocomplete, edge n-grams, completion suggester | Autocomplete and typeahead |
| Vectors plus keywords, RRF | Hybrid search |
| Feature matrix and what each product really does | Per-engine behaviour |
| tsvector, tsquery, dictionaries, GIN, GiST, pg_trgm, limits | Mechanics |
| Elasticsearch shards, segments, refresh, Lucene | Elasticsearch internals |
| Code for PostgreSQL, Persian, sync, Scout, MySQL, SQLite, Go clients | Solving the classic problems |
| Which engine for which workload | Choosing |
| Sync, replicas, scale | In architecture |
| Timed comparison you can reproduce | Lab |
| Wrong beliefs, cheat sheet, terms | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The building blocks. Each row is unpacked in the concepts section.
| Term | In plain words | Tiny example | Who provides it |
|---|---|---|---|
| Inverted index | A word-to-documents lookup instead of document-to-words | fox points to documents 1 and 2 | Lucene segments, PostgreSQL GIN, FTS5, InnoDB FULLTEXT |
| Postings (posting list) | The sorted list of documents (and positions) for one term | fox: [1@4, 2@1] | All of the above |
| Tokenization | Split text into tokens | The quick fox becomes The, quick, fox | Parser (PostgreSQL), tokenizer (Lucene) |
| Normalization | Make spellings comparable: case, accents, letter variants | Café becomes cafe | Token filters, dictionaries |
| Stop words | Very common words dropped from the index | the, of, و | Dictionaries, stop filters |
| Stemming | Cut a word to a crude root by rules | foxes becomes fox | Snowball (PostgreSQL), Porter (FTS5), language analyzers |
| Lemmatization | Map a word to its dictionary form using a lexicon | better becomes good | Hunspell/ispell, external NLP; rare in engines |
| N-grams, trigrams | Overlapping fixed-size character pieces | fox has trigrams __f, _fo, fox, ox_ | pg_trgm, pg_bigm, ngram filters, FTS5 trigram |
| Ranking | Order matches by relevance | BM25 score | BM25 (Lucene, ParadeDB, FTS5), ts_rank, Meilisearch ranking rules |
The engines.
| Engine | Kind | Ranking | Typo tolerance | Needs sync? | Typical sweet spot |
|---|---|---|---|---|---|
PostgreSQL FTS (tsvector and GIN) | Built into the database | ts_rank, ts_rank_cd (no BM25) | No (add pg_trgm) | No, same transaction | Up to millions of documents, one or two languages |
pg_trgm / pg_bigm | Extensions | Similarity score | Yes (trigram similarity) | No | Substring, fuzzy names, CJK (pg_bigm) |
ParadeDB pg_search | Postgres extension | BM25 | Fuzzy query types | No (in the database) | BM25 without a second datastore |
| MySQL FULLTEXT (InnoDB) | Built in | Natural language relevance | No | No | Simple search on MySQL, CJK with ngram parser |
| SQLite FTS5 | Virtual table | bm25() | No (trigram tokenizer for substrings) | No | Embedded and local search |
| Elasticsearch / OpenSearch | Distributed engine on Lucene | BM25 (default) | Yes (fuzziness) | Yes | Large corpora, analyzers, aggregations |
| Meilisearch / Typesense | Single-purpose engines | Ranking rules / text match score | Yes, on by default | Yes | Product search, instant search, small operations |
The three things to do.
| Situation | Do this |
|---|---|
| Search over data already in PostgreSQL, thousands to a few million rows | A stored generated tsvector column with weights, a GIN index and websearch_to_tsquery; add pg_trgm for typos and substring |
| Users mistype, or you need as-you-type results with facets | Meilisearch, Typesense, or Elasticsearch; sync with an outbox or CDC, never with a bare dual write |
| Persian or Arabic content | Normalize ZWNJ, ی/ک variants and diacritics yourself (PostgreSQL has no Persian configuration) or use Elasticsearch's persian analyzer |
Why full-text search exists
Searching text with LIKE '%word%' asks the database to read every document for every query, knows nothing about grammar, and returns matches in no useful order. A full-text engine does the work once, at write time: it analyzes each document into terms and stores a term-to-documents map, so a query becomes a few lookups and a merge. What you pay for that is write-time work, extra storage, language configuration, and (outside the database) a second system that must be kept in sync.
| Database-native (PostgreSQL, MySQL, SQLite) | Dedicated engine (Elasticsearch, Meilisearch, Typesense) |
|---|---|
| Same transaction as your data: no lag, no sync | Separate datastore: eventual consistency, sync pipeline |
| One system to run, back up and secure | Cluster or service to run, secure and upgrade |
| Few languages out of the box, little relevance tuning | Analyzers per language, synonyms, boosts, learning to rank |
Ranking is basic (ts_rank, relevance) | BM25 with tunable parameters, function scores |
| Faceting is hand-written SQL | Aggregations and facets are first-class |
| Search load competes with OLTP traffic | Search scales and fails independently |
The analogy we reuse on this page: the index at the back of a reference book. A librarian can walk every shelf reading spines (LIKE '%fox%'), or open the index in the back of a reference book, find the word, and jump to the pages. The index only works if the indexer decided that "foxes" and "Fox" are one entry and in which language to file them (analysis). Add a new chapter and the index must be updated (write cost). Print a second copy of the index for the branch library and the two copies can disagree (sync).
Three common misunderstandings, up front
- "An index on the column makes
LIKE '%x%'fast." A B-tree cannot seek on a leading wildcard. Only a trigram index (pg_trgm,pg_bigm) can, because it indexes character fragments. - "Full-text search is typo tolerant." It matches normalized words.
invertdis a different term frominverted. Typo tolerance needs trigrams or an engine with edit-distance matching (Elasticsearchfuzziness, Meilisearch, Typesense). - "Search needs Elasticsearch." For many products a generated column and a GIN index in the database you already run is enough, and it comes with no sync problem. A dedicated engine is for needs the database cannot meet, not a default.
Where it comes from
Databases have had text operators for a long time, and the PostgreSQL manual is blunt about why they are not enough. ~, ~*, LIKE and ILIKE "lack many essential properties required by modern information systems":
"There is no linguistic support, even for English. [...] They provide no ordering (ranking) of search results [...] They tend to be slow because there is no index support, so they must process all documents for every search."
The answer is the inverted index: instead of storing "document → words", store "word → list of documents". Lucene, the Java library under Elasticsearch and OpenSearch, is built on it, and so is PostgreSQL's GIN index, which the manual describes as containing "an index entry for each word (lexeme), with a compressed list of matching locations."
The second ingredient is ranking. Robertson and Zaragoza's monograph describes the Probabilistic Relevance Framework as the basis of "one of the most successful text-retrieval algorithms, BM25", a function that ranks documents "in descending order of probability of relevance". Elasticsearch uses BM25 by default; PostgreSQL's built-in ts_rank is a simpler frequency-based function. TF-IDF (term frequency times inverse document frequency) is the older, simpler ancestor: a term counts for more when it is frequent in the document and rare in the corpus. BM25 keeps that idea and adds two corrections, saturation of term frequency and document-length normalization.
The concepts, one by one
Each block follows the same order: plain words, the usual wrong belief, the precise definition, a sequence or timeline, real scenarios, what provides it in each product, and the fix or usage with SQL, Go and Laravel where code helps.
Inverted index and postings Must-know
In plain words: instead of "this document contains these words", you store "this word appears in these documents". Looking up a word is then one lookup, not a scan.
Common misunderstanding: "The index stores the text, so the database just searches the index text." No. The index stores terms (after analysis) and, per term, a list of document ids and usually positions. The original text lives elsewhere (the heap row, Lucene's stored fields, Elasticsearch _source), and the index cannot reproduce it exactly.
Definition: an inverted index is a sorted dictionary of terms; each term points to a posting list (postings): the document ids that contain it, optionally with term frequency, positions and offsets. A query reads the posting lists for its terms and combines them: intersection for AND, union for OR, position comparison for phrases.
Query: quick AND fox (postings are sorted by document id)
1 dictionary lookup "quick" -> postings [D1@2, D3@1]
2 dictionary lookup "fox" -> postings [D1@4, D2@1]
3 merge-intersect both lists -> [D1]
4 (ranking) read term frequency and field length for D1, compute score
5 fetch the stored row / _source for D1 onlyReal scenario: a 100,000-row table where ILIKE '%tokenizer%' read every row and took 430 ms, while the GIN-backed query took 26 ms on the same machine (see the lab). A support portal with 40 million tickets where only the posting-list intersection touches the disk before the top 20 rows are fetched.
| Product | What the index structure is |
|---|---|
| PostgreSQL GIN | B-tree of terms (lexemes); each entry holds a posting list or, for popular terms, a posting tree; new rows go to a pending list first (fastupdate) |
| Lucene (Elasticsearch, OpenSearch, Solr) | Immutable segments, each with a term dictionary (an FST), postings with skip data, and doc values for sorting and aggregations |
| MySQL InnoDB FULLTEXT | Auxiliary index tables (6 per index) with a cache that is merged on flush |
| SQLite FTS5 | Shadow tables in the database file, segment B-trees, merged by merge and optimize commands |
| Meilisearch | LMDB-based, word-to-documents bitmaps (roaring bitmaps) plus prefix and proximity databases |
| Typesense | In-memory adaptive radix tree of tokens per field with on-disk RocksDB for documents |
Fix / how to use it: you do not build it by hand. In PostgreSQL:
-- One document, analyzed with the 'english' configuration
SELECT to_tsvector('english', 'The quick brown foxes jumped');
-- 'brown':3 'fox':4 'jump':5 'quick':2Tokenization Must-know
In plain words: cutting a string into the pieces (tokens) that will become index terms.
Common misunderstanding: "Tokenizing means splitting on spaces." Real tokenizers handle punctuation (state-of-the-art), apostrophes, e-mail addresses and URLs, digits, scripts without spaces (Chinese, Japanese, Thai), and zero-width characters (the ZWNJ in Persian).
Definition: tokenization is the first step of analysis proper: a parser or tokenizer turns the character stream into typed tokens. PostgreSQL's default parser classifies tokens (asciiword, word, email, url, numword, hword, ...) and a configuration maps each type to dictionaries. Lucene tokenizers (standard, whitespace, keyword, pattern, path_hierarchy, icu_tokenizer, edge_ngram) emit plain tokens with positions and offsets.
Text: "Mail bob@example.com state-of-the-art"
1 standard tokenizer (Lucene): Mail | bob | example.com | state | of | the | art
2 uax_url_email tokenizer: Mail | bob@example.com | state | of | the | art
3 PostgreSQL default parser: Mail | bob@example.com (email) | state-of-the-art (asciihword) + state, of, the, art (hword_asciipart)
-- same text, three different term sets: query and index must use the same tokenizerReal scenario: a product code like AK-1243XY that the standard tokenizer splits into two tokens, so the exact code no longer matches; an e-mail search that needs uax_url_email; a Japanese catalogue that returns nothing because no spaces exist to split on.
| Product | Tokenizer you control |
|---|---|
| PostgreSQL | Parser (default, or CREATE TEXT SEARCH PARSER in C); ts_debug() shows token types |
| Elasticsearch / OpenSearch | tokenizer in an analyzer definition; _analyze API |
| Meilisearch | Built in (charabia: script-aware, with CJK segmentation); separator and dictionary settings |
| Typesense | Built in; token_separators, symbols_to_index per field |
| SQLite FTS5 | tokenize = 'unicode61' (default), ascii, porter, trigram |
| MySQL | Word parser, or WITH PARSER ngram / MeCab plugin for CJK |
Fix / how to use it: inspect before you trust.
SELECT alias, token, dictionaries, lexemes FROM ts_debug('english', 'Mail bob@example.com state-of-the-art');Normalization, stop words, stemming and lemmatization Must-know
In plain words: make different spellings of the same idea become the same term: lowercase, drop accents, drop filler words, cut endings.
Common misunderstanding: "Stemming understands the language." It is a set of suffix rules. Snowball turns tokenizer into token and university into univers; that is fine for recall and wrong when you need exact words. Lemmatization uses a dictionary to return real base forms (better to good, mice to mouse) and is slower, language specific and rarely built into search engines.
Definition: analysis is the chain that turns raw text into index terms. Normalization covers case folding, accent folding (unaccent, ASCII folding), Unicode normalization (NFC, NFKC) and language-specific letter mapping. Stop words are removed because they are frequent and carry little ranking signal; removing them shrinks the index and breaks phrases like "to be or not to be" unless positions are preserved. Stemming is rule-based (Snowball, Porter); lemmatization is lexicon-based (Hunspell, ispell, external NLP).
"Café FOXES jumped over the lazy dogs" configuration = english
1 parser Café | FOXES | jumped | over | the | lazy | dogs
2 lowercase café | foxes | jumped | over | the | lazy | dogs
3 stop words café | foxes | jumped | - | - | lazy | dogs (positions 1,2,3,6,7 kept)
4 english_stem café | fox | jump | | lazi | dog
5 index terms 'café':1 'dog':7 'fox':2 'jump':3 'lazi':6 (lab output)Note step 4: english_stem does not remove the accent, so Café is stored as café and a search for cafe finds nothing until an accent-folding dictionary (unaccent) runs first; the recipe is in Mechanics.
Real scenario: a shop where searching "running shoes" must also find "run shoe" (stemming); a legal archive where stop-word removal broke the exact phrase "to be or not to be"; a recipe site where Crème brûlée must match creme brulee (accent folding).
| Product | Normalization and stemming you get |
|---|---|
| PostgreSQL | Dictionaries per token type: simple (lowercase only), *_stem (Snowball, 28 languages in the PostgreSQL 17 lab), unaccent, ispell/hunspell, synonym, thesaurus |
| Elasticsearch / OpenSearch | Token filters: lowercase, asciifolding, icu_folding, stop, stemmer, snowball, hunspell, synonym; prebuilt language analyzers |
| Meilisearch | Built-in normalization (case, diacritics); no stemming; stopWords, synonyms settings |
| Typesense | locale per field; stemming optional (stem: true); synonyms API |
| SQLite FTS5 | unicode61 remove_diacritics 2, porter wrapper tokenizer for English stemming |
| MySQL InnoDB | Stop-word list (innodb_ft_enable_stopword), minimum token size 3; no stemming |
Fix / how to use it: choose per field and per language, and test with the debug functions (ts_debug, _analyze).
N-grams, trigrams and edge n-grams Important
In plain words: instead of words, index every overlapping run of 2 or 3 characters. Substrings and misspellings then share most of their pieces.
Common misunderstanding: "Trigram search is just a faster LIKE." It is also a similarity measure: inverted and invertd share most trigrams, so they score close even though no word-based index would connect them.
Definition: an n-gram is a contiguous run of n characters. pg_trgm pads each word with two leading spaces and one trailing space, so word has the trigrams " w", " wo", wor, ord, "rd ". An edge n-gram is anchored to the start of a word (q, qu, qui, quic, quick) and powers prefix and autocomplete matching. pg_bigm uses 2-grams. A query is split into the same grams and matched by overlap.
similarity('invertd', 'inverted') with pg_trgm
1 trigrams('invertd') = {" i"," in",inv,nve,ver,ert,"td ",rtd} -- 8
2 trigrams('inverted') = {" i"," in",inv,nve,ver,ert,rte,ted,"ed "} -- 9
3 shared = 6 union = 11 similarity = 6/11 = 0.545 (lab output: 0.54545456)
4 threshold pg_trgm.similarity_threshold = 0.3 -> 'invertd' % 'inverted' is trueReal scenario: searching customer names with typos (Mohamad versus Muhammad); finding a code fragment in the middle of a long identifier (%XY12%); Japanese or Chinese text with no spaces; autocomplete on product names.
| Product | N-gram support |
|---|---|
| PostgreSQL | pg_trgm (trigrams, GIN or GiST), pg_bigm (2-grams, GIN only, CJK friendly) |
| Elasticsearch / OpenSearch | ngram and edge_ngram tokenizers and filters; search_as_you_type field type |
| Meilisearch | Prefix search by default (last word as prefix); typo tolerance by edit distance, not n-grams |
| Typesense | infix option for substring search; prefix on the last word |
| SQLite FTS5 | tokenize = 'trigram' for substring and LIKE/GLOB acceleration |
| MySQL InnoDB | WITH PARSER ngram, size set by ngram_token_size (default 2) |
Cost: an index of n-grams is much larger than a word index (every word produces many grams) and slower to update; plan for it on large columns.
Persian and Arabic text Must-know
In plain words: the same Persian word can be typed several ways, and unless you make them identical before indexing, the search misses obvious matches.
Common misunderstanding: "The engine supports Unicode, so Persian works." Unicode storage works; search quality needs language rules. PostgreSQL ships an arabic configuration but no persian one, and its Snowball dictionary is for Arabic morphology.
Definition: six independent issues, all verified in the lab:
| Issue | Example | Code points | What to do |
|---|---|---|---|
| ZWNJ (zero-width non-joiner) | میشود versus می شود | U+200C versus U+0020 | Map ZWNJ to a space before tokenizing, or index both forms |
| Letter variants: yeh | Arabic ي versus Persian ی | U+064A versus U+06CC | Map to the Persian letter |
| Letter variants: kaf | Arabic ك versus Persian ک | U+0643 versus U+06A9 | Map to the Persian letter |
| Diacritics (harakat) and tatweel | مُحَمَّد, کـتاب | U+064B to U+065F, U+0670, U+0640 | Strip |
| Digits | ۱۲۳ versus ١٢٣ versus 123 | U+06F0 to U+06F9, U+0660 to U+0669 | Fold to ASCII |
| Plurals and suffixes | کتاب, کتابها, کتابها | ها suffix with or without ZWNJ | Stemmer (persian_stem) or a prefix/trigram fallback |
Lab: PostgreSQL 17, 'simple' configuration
1 SELECT to_tsvector('simple', 'میشود'); -> 'میشود':1 (ZWNJ is a word character: one token)
2 SELECT to_tsvector('simple', 'می شود'); -> 'شود':2 'می':1 (two tokens)
3 -- the same word, two spellings, no match between them
4 to_hex(ascii('ی')) = 6cc to_hex(ascii('ي')) = 64a to_hex(ascii('ک')) = 6a9 to_hex(ascii('ك')) = 643
5 to_hex(ascii(E'\u200c')) = 200cReal scenario: a Persian news site where editors type with an Arabic keyboard layout (ي and ك) and readers with a Persian one; a bookshop where کتابها never matches کتابها; a hospital system with Arabic-script names containing harakat.
| Product | Persian and Arabic support |
|---|---|
| PostgreSQL | arabic configuration (Snowball Arabic stemmer); no persian; use simple plus your own normalization (an immutable expression or generated column) |
| Elasticsearch / OpenSearch | persian and arabic analyzers; persian = zero_width_spaces char filter ("\u200C=>\u0020") then lowercase, decimal_digit, arabic_normalization, persian_normalization, persian_stop, persian_stem |
| Meilisearch | Built-in script-aware normalization (charabia); no stemmer; test your exact Persian spellings, including ZWNJ, before relying on it |
| Typesense | locale setting for specific scripts; normalize in your application for Persian |
| SQLite FTS5 | unicode61 handles case and (with remove_diacritics) marks; map ي/ك yourself |
| MySQL InnoDB | Depends on the collation (utf8mb4 collations fold some variants and not others); test yours; no Persian stemmer |
Fix / how to use it: one normalization function, applied on write and on query, in every layer that touches the text. Go and Laravel versions are in Persian search in PostgreSQL.
Ranking: TF-IDF, BM25, ts_rank and weights Must-know
In plain words: among all documents that match, the ones where the query words are frequent, rare in the corpus, and in short fields should come first.
Common misunderstanding: "A higher score means a better answer." Scores are only comparable within one query on one index. PostgreSQL says so itself: the ranking functions "do not use any global information, so it is impossible to produce a fair normalization to 1% or 100%".
Definition:
| Model | Idea | Knobs |
|---|---|---|
| TF-IDF | score = term frequency times log(N / document frequency); raw counts grow without bound | None in the classic form |
| BM25 | TF-IDF with saturation of term frequency and document-length normalization | k1 (default 1.2, saturation) and b (default 0.75, length normalization) in Elasticsearch; discount_overlaps |
ts_rank (PostgreSQL) | Frequency of matching lexemes, with weights per label D, C, B, A | Weights array, default {0.1, 0.2, 0.4, 1.0}; normalization bit mask |
ts_rank_cd (PostgreSQL) | Cover density: also rewards matching words that sit close together | Same weights and normalization; needs positions |
| Meilisearch ranking rules | Not a score: an ordered list of rules (words, typo, proximity, attributeRank, sort, wordPosition, exactness) applied as tie-breakers | Reorder, add custom rules |
| Typesense | Text match score plus optional sort_by and field weights (query_by_weights) | query_by_weights, num_typos, prioritize_exact_match |
| MySQL natural language | Relevance from term frequency and inverse document frequency | None |
SQLite FTS5 bm25() | BM25 with per-column weights; returns negative numbers, lower is better | Column weights arguments |
ParadeDB pdb.score() | BM25 | BM25 parameters per field (k1, b) in the index definition |
Higher k1 lets repeated words count for more before saturating; b = 0 ignores document length and b = 1 normalizes fully. PostgreSQL's normalization is a bit mask (combine with a bitwise OR such as 2 and 4): 0 ignore length (default), 1 divide by 1 + log(length), 2 divide by length, 4 divide by mean harmonic distance between extents (ts_rank_cd only), 8 divide by unique words, 16 divide by 1 + log(unique words), 32 rank/(rank+1).
-- Weights here: A for the title, D for the body (the schema in Solutions uses A and C); array order is {D, C, B, A}
SELECT id, ts_rank('{0.1,0.2,0.4,1.0}', search_vector, q) AS rank
FROM articles, websearch_to_tsquery('english', 'inverted index') AS q
WHERE search_vector @@ q
ORDER BY rank DESC LIMIT 20;
-- A title hit scored 0.608; the same word in the body only scored 0.061 (lab output)Cost to know: PostgreSQL ranks every row that matches, because ts_rank needs the tsvector of each one. A query that matches 5,067 rows in the lab had to compute 5,067 ranks and sort them (top-N heapsort) before returning 20. Narrow queries are cheap; broad ones are not, and no index helps the ranking step.
Phrase, proximity, prefix, fuzzy and boolean queries Important
In plain words: users do not only type loose words. They quote phrases, exclude words, type half a word, and misspell.
Common misunderstanding: "plainto_tsquery('fat cat') finds the phrase." It ANDs the words: any document with both, anywhere. Use phraseto_tsquery or websearch_to_tsquery with quotes for adjacency.
Definition:
| Need | PostgreSQL | Elasticsearch | Meilisearch / Typesense |
|---|---|---|---|
| All words, any order | plainto_tsquery, & | match with operator: and | default |
| Any word | | in to_tsquery, or in websearch_to_tsquery | match (operator or) | default |
| Exact phrase | phraseto_tsquery, "..." in websearch_to_tsquery, <-> | match_phrase (with slop) | "..." quotes |
| Within N words | <N> operator, for example fat <2> sat | match_phrase with slop | proximity ranking rule |
| Exclusion | !, -word in websearch_to_tsquery | bool.must_not | -word |
| Prefix | postgr:* | match_bool_prefix, prefix query | last word is a prefix by default |
| Typo tolerance | pg_trgm % | fuzziness: "AUTO" | on by default |
| Wildcard / regex | trigram LIKE, ~ | wildcard, regexp queries (slow) | not supported |
SELECT websearch_to_tsquery('english', '"fat rats" -cat or dog');
-- 'fat' <-> 'rat' & !'cat' | 'dog'
SELECT to_tsvector('english', 'a fat cat sat on a mat') @@ to_tsquery('english', 'fat <2> sat'); -- true
SELECT to_tsquery('english', 'postgres:*'); -- 'postgr':*websearch_to_tsquery "will never raise syntax errors", which makes it the right function for raw user input; to_tsquery raises ERROR: syntax error in tsquery on stray operators. The <N> (FOLLOWED BY) distance cannot exceed 16,384.
Highlighting and snippets Good to know
In plain words: showing the user the part of the document that matched, with the words marked.
Common misunderstanding: "Highlighting is free once you have the index." In PostgreSQL ts_headline re-parses the original text of every row it is applied to, so run it only on the final 20 rows, never in the WHERE clause or on the whole result set.
Definition: ts_headline(config, document, query, options) returns fragments with StartSel/StopSel markers. Elasticsearch has the highlight request section (unified highlighter); Meilisearch returns _formatted with attributesToHighlight and attributesToCrop; Typesense returns highlight; SQLite FTS5 has highlight() and snippet().
-- Pattern: rank and limit first, highlight only the surviving 20 rows
SELECT id, ts_headline('english', body, q, 'StartSel=<mark>,StopSel=</mark>,MaxFragments=2,MaxWords=20,MinWords=5')
FROM (SELECT id, body, q FROM articles, websearch_to_tsquery('english', 'quick fox') q
WHERE search_vector @@ q ORDER BY ts_rank(search_vector, q) DESC LIMIT 20) top;
-- Literal example (lab output)
SELECT ts_headline('english', 'The quick brown fox jumps over the lazy dog', 'fox & jump'::tsquery,
'StartSel=<mark>,StopSel=</mark>,MaxFragments=2');
-- quick brown <mark>fox</mark> <mark>jumps</mark> over the lazyAlways escape the stored text if you render the marked output as HTML, because the markers are plain strings and the body is user content.
Facets, aggregations and filters Important
In plain words: the "filter by brand, price range, category" sidebar, with a count next to each choice.
Common misunderstanding: "Facets are just a GROUP BY." They are, in PostgreSQL, and that is the problem: the counts must be computed over every matching row, so a broad query pays for them. Engines keep column-oriented structures (doc values, bitmaps) to make this cheap.
Definition: a filter narrows the result set without affecting relevance; a facet (aggregation) counts the distinct values of a field inside the current result set. Elasticsearch has terms, range, date_histogram, filters and nested aggregations, and post_filter to keep facet counts independent of the selected facet. Meilisearch takes facets and returns facetDistribution; Typesense takes facet_by.
-- PostgreSQL: facets by hand; cost grows with the number of matches
SELECT category, count(*)
FROM articles, websearch_to_tsquery('english', 'index') q
WHERE search_vector @@ q
GROUP BY category ORDER BY count(*) DESC;Real scenario: an e-commerce listing with brand, size and price facets that must update on every keystroke; a log search where the histogram over time is the main output.
| Product | Facets |
|---|---|
| PostgreSQL | GROUP BY; ParadeDB adds fast aggregates over its index |
| Elasticsearch / OpenSearch | Aggregations framework (the main reason to move to it) |
| Meilisearch | facets plus filterableAttributes; returns facetDistribution |
| Typesense | facet_by, max_facet_values |
| SQLite FTS5, MySQL | Hand-written GROUP BY |
Relevance tuning Important
In plain words: the first result should be what the user meant. Tuning is the work of making that true for your data.
Common misunderstanding: "Pick BM25 and you are done." Defaults are a starting point. Field weights, synonyms, exact-match boosts, popularity and recency usually matter more than k1 and b.
Definition and knobs:
| Lever | Elasticsearch / OpenSearch | PostgreSQL | Meilisearch / Typesense |
|---|---|---|---|
| Field weight | multi_match with title^3 boosts | setweight labels A to D plus the weights array | searchableAttributes order / query_by_weights |
| Exact beats stemmed | Index the field twice (a stemmed text field and a .exact sub-field) and boost the exact one | A second simple-config vector, or ts_rank on both | exactness rule / prioritize_exact_match |
| Synonyms | synonym_graph filter at search time | synonym or thesaurus dictionary (files on the server) | synonyms setting / API |
| Popularity, recency | function_score, rank_feature | ts_rank(...) * log(1 + views) in ORDER BY | sort rules, custom ranking rule |
| Second pass | rescore on the top N | A CTE: filter cheap, rank the top N | n/a |
| Explain a score | explain: true, _explain API | Compute ts_rank per component | showRankingScore, showRankingScoreDetails |
| Similarity parameters | index.similarity.default with k1, b | Normalization mask | n/a |
| Per-shard statistics | search_type=dfs_query_then_fetch | n/a | n/a |
Evaluate with a judged set of queries (the 50 searches your users actually run, with the expected top results), not by feel: change one lever, re-run, compare nDCG or simply "expected result in the top 3".
Autocomplete and typeahead Important
In plain words: show suggestions while the user is still typing, in under 100 milliseconds.
Common misunderstanding: "Autocomplete is a search for the typed prefix." It is a different query shape: the last word is a prefix, the earlier words are whole words, results should be few, and latency matters more than recall. Using the normal search with LIKE 'abc%' on every keystroke works only on small tables.
Definition: three techniques.
| Technique | How | Strengths | Cost |
|---|---|---|---|
| Prefix query on an ordinary index | PostgreSQL to_tsquery('simple', 'pos:*'), a B-tree with text_pattern_ops for LIKE 'pos%' | No extra structure | Slow on huge vocabularies, no typo help |
| Edge n-grams at index time | Elasticsearch edge_ngram tokenizer or filter (min_gram, max_gram), or the search_as_you_type field type | Words in any order, fuzzy-friendly | Bigger index; max_gram caps the length that matches |
| Completion suggester | Elasticsearch completion field type: an in-memory FST of whole inputs with weights | Fastest, ordered by weight, supports fuzzy | Prefix of the whole string only; separate field; memory |
| Engine default | Meilisearch and Typesense treat the last word as a prefix by default (prefix=true in Typesense) | Zero setup | Per-engine limits (Meilisearch matches the prefix only on the last word) |
Elasticsearch's own guidance: for text "which has a widely known order, such as movie or song titles, the completion suggester is a much more efficient choice than edge N-grams. Edge N-grams have the advantage when trying to autocomplete words that can appear in any order." Its edge n-gram tokenizer defaults are min_gram 1 and max_gram 2, and the documentation calls them "almost entirely useless", so always configure them.
Search-as-you-type with edge n-grams (index analyzer) and a plain search analyzer
1 index time: "Quick Fox" -> q, qu, qui, quic, quick, f, fo, fox (edge_ngram, min 1, max 10)
2 user types: "qui" -> search analyzer (standard, NO ngrams) -> term "qui"
3 lookup: term "qui" is in the dictionary (it was written at index time) -> doc matches
4 user types: a 12-letter word -> longer than max_gram, so the full word is never indexed
-- if the search analyzer also made n-grams, "xyz" would match everything containing "x"Hybrid search and Reciprocal Rank Fusion (RRF) Important
In plain words: keyword search finds exact words; vector search finds similar meaning. Hybrid runs both and merges the two ranked lists.
Common misunderstanding: "Add the BM25 score and the cosine similarity." The two scores live on different scales (BM25 is unbounded; cosine is -1 to 1), so adding or averaging them gives one side all the weight. Fuse by rank, not by score, or normalize carefully.
Definition: Reciprocal Rank Fusion scores each document by summing, over the result lists it appears in, 1 / (k + rank). Elasticsearch describes RRF as combining "multiple result sets with different relevance indicators into a single result set" and says it "requires no tuning"; rank_constant (our k) defaults to 60 and rank_window_size is how many top documents each list contributes. Embeddings, indexes (HNSW, IVFFlat) and distance operators are in Vector Search & pgvector; this page covers only the fusion with keyword search.
-- PostgreSQL + pgvector: RRF with k = 60 over a keyword list and a vector list
WITH fts AS (
SELECT id, row_number() OVER (ORDER BY ts_rank(search_vector, q) DESC) AS rnk
FROM articles, websearch_to_tsquery('english', $1) AS q
WHERE search_vector @@ q
ORDER BY ts_rank(search_vector, q) DESC LIMIT 50),
vec AS (
SELECT id, row_number() OVER (ORDER BY embedding <=> $2::vector) AS rnk
FROM articles ORDER BY embedding <=> $2::vector LIMIT 50)
SELECT id, sum(1.0 / (60 + rnk)) AS score
FROM (SELECT * FROM fts UNION ALL SELECT * FROM vec) u
GROUP BY id ORDER BY score DESC LIMIT 20;{
"retriever": {
"rrf": {
"retrievers": [
{ "standard": { "query": { "match": { "body": "inverted index" } } } },
{ "knn": { "field": "vector", "query_vector": [0.1, 0.2, 0.3], "k": 50, "num_candidates": 200 } }
],
"rank_window_size": 50,
"rank_constant": 60
}
}
}| Product | Hybrid approach |
|---|---|
| PostgreSQL + pgvector | You write the RRF query above (or a weighted blend); ParadeDB documents hybrid fusion over its BM25 index |
| Elasticsearch | rrf retriever; knn plus query in one search |
| OpenSearch | hybrid query with a search pipeline normalization-processor (min-max or L2 normalization, then arithmetic, geometric or harmonic mean); check your version for an RRF processor |
| Meilisearch | hybrid search parameter with an embedder and a semanticRatio between 0 and 1 (a weighted blend, not RRF) |
| Typesense | Vector query combined with keyword query; alpha blends the two |
| Laravel Scout | Database engine with pgvector supports semantic and hybrid search; Meilisearch hybrid through embedders in index-settings |
Per-engine behaviour
Matrix: feature by product
| Feature | PostgreSQL FTS | pg_trgm / pg_bigm | ParadeDB | MySQL InnoDB | SQLite FTS5 | Elasticsearch / OpenSearch | Meilisearch | Typesense |
|---|---|---|---|---|---|---|---|---|
| Inverted index | GIN / GiST | GIN / GiST (trigram) | Custom index (Tantivy-based) | FULLTEXT | Shadow tables | Lucene segments | LMDB bitmaps | In-memory radix tree |
| BM25 | No (ts_rank) | No (similarity) | Yes | No | Yes (bm25()) | Yes (default) | No (rules) | No (text match score) |
| Stemming | Snowball, 28 languages | No | Configurable | No | porter | Per language | No | Optional |
| Typo tolerance | No | Yes | Fuzzy queries | No | No | fuzziness | Default on | Default on |
Substring (%x%) | No (needs trigram) | Yes | Regex / ngram | No (ngram parser) | trigram tokenizer | wildcard, ngram | No | infix |
| Phrase / proximity | <->, <N> | No | Phrase queries | Boolean mode quotes | Phrase, NEAR | match_phrase | Rule-based | Quoted phrase |
| Facets | GROUP BY | GROUP BY | Aggregates | GROUP BY | GROUP BY | Aggregations | facets | facet_by |
| Highlighting | ts_headline | No | Snippet functions | No | highlight(), snippet() | highlight | _formatted | highlight |
| Same transaction as data | Yes | Yes | Yes | Yes | Yes | No (sync) | No (sync) | No (sync) |
| Horizontal scale | Read replicas, partitions | Same | Replicas | Replicas | Single file | Shards | Single node (replication in cloud) | Clustering (Raft) |
What each product really does
| Product | What you must know |
|---|---|
| PostgreSQL FTS | tsvector/tsquery; 28 Snowball stemming dictionaries and 31 configurations in the PostgreSQL 17 lab; no persian configuration; GIN is the preferred index; ts_rank has no corpus statistics; hard limits (1 MB per tsvector, 2 KB per lexeme) |
pg_trgm | Contrib module; %, <%, <<%, <-> operators; similarity, word_similarity, strict_word_similarity; GIN or GiST; accelerates LIKE, ILIKE, ~, ~*; needs at least one extractable trigram |
pg_bigm | Third-party; 2-gram GIN index (gin_bigm_ops); accelerates LIKE only; supports 1 to 2 character keywords fast and non-alphabetic languages (Japanese); pg_bigm.similarity_limit; coexists with pg_trgm from 1.1 |
ParadeDB pg_search | Postgres extension (Rust, Tantivy engine) that gives you BM25 in Postgres by adding a BM25 index; index access method paradedb (alias bm25, renamed in 0.25.0); match operators ||| (any term), &&& (all terms); pdb.score() returns BM25; self-hosted extension, check your hosting provider supports it |
| MySQL InnoDB FULLTEXT | MATCH(col) AGAINST('...' IN NATURAL LANGUAGE MODE | BOOLEAN MODE); default innodb_ft_min_token_size 3 and stop words on; ngram_token_size default 2 for the ngram parser; error 1191 if no FULLTEXT index matches the column list; ft_* variables are MyISAM only |
| SQLite FTS5 | CREATE VIRTUAL TABLE ... USING fts5(...); MATCH; bm25() returns negative numbers (lower is better); highlight(), snippet(); tokenizers unicode61 (default), ascii, porter, trigram; external-content and contentless tables |
| Elasticsearch | Lucene; shards and replicas; mapping per index; analyzers; BM25 default (k1 1.2, b 0.75); near-real-time (1 s refresh); max_result_window 10,000 |
| OpenSearch | Fork of Elasticsearch 7.10; same Lucene core and similar APIs; own hybrid search, neural plugin, security plugin; client libraries are separate |
| Meilisearch | Rust, single binary; typo tolerance on (one typo from 5 characters, two from 9 by default); seven ranking rules; asynchronous indexing through tasks; filterableAttributes must be declared |
| Typesense | C++, in-memory index; typo tolerance (num_typos 0 to 2, min_len_1typo 4, min_len_2typo 7 by default); schema-first collections; drop_tokens_threshold, typo_tokens_threshold |
| Lucene | The library underneath Elasticsearch, OpenSearch and Solr; segments, FST term dictionary, BKD trees, HNSW vectors |
| SQL Server | Full-Text Search with full-text catalogs and indexes; CONTAINS, FREETEXT, CONTAINSTABLE, FREETEXTTABLE; stoplists, thesaurus files and per-language word breakers; population is asynchronous (change tracking) |
| Oracle | Oracle Text: a CONTEXT index and the CONTAINS operator with SCORE; lexers, stoplists and index sync (CTX_DDL.SYNC_INDEX, SYNC (ON COMMIT)) |
| MongoDB | One text index per collection with the $text operator and textScore; MongoDB Atlas Search ($search) is a separate Lucene-based service with analyzers and facets |
| CockroachDB | PostgreSQL-compatible tsvector/tsquery types, text search functions and inverted (GIN) indexes; check the version notes for gaps against PostgreSQL |
| Redis | The Redis Query Engine (RediSearch): FT.CREATE, FT.SEARCH, in-memory full-text index with scorers such as TF-IDF and BM25; see Redis |
Mechanics
PostgreSQL FTS: tsvector, tsquery, dictionaries and configurations Must-know
A tsvector is a sorted list of distinct lexemes with positions and optional weight labels; a tsquery is a Boolean expression over lexemes with the operators &, |, !, <-> and <N>. @@ tests a match. A text search configuration (for example english) says which parser to use and, for each token type, an ordered chain of dictionaries: each dictionary either returns lexemes, returns an empty array (a stop word, the token is dropped), or returns nothing (pass the token to the next dictionary). The final dictionary in the chain should always recognize everything (simple or a *_stem).
-- Which configurations and dictionaries exist (PostgreSQL 17 lab: 31 configurations, 28 stemming dictionaries)
\dF
\dFd
-- Accent-insensitive English: unaccent runs first, then the stemmer
CREATE EXTENSION IF NOT EXISTS unaccent;
CREATE TEXT SEARCH CONFIGURATION public.english_unaccent (COPY = pg_catalog.english);
ALTER TEXT SEARCH CONFIGURATION public.english_unaccent
ALTER MAPPING FOR hword, hword_part, word WITH unaccent, english_stem;
SELECT to_tsvector('public.english_unaccent', 'Café résumés'); -- 'cafe':1 'resum':2
-- unaccent() is STABLE, so it cannot be used in an index or generated column directly.
-- Wrap it (an immutable wrapper is the documented workaround; keep the dictionary name explicit):
CREATE FUNCTION public.immutable_unaccent(text) RETURNS text
LANGUAGE sql IMMUTABLE PARALLEL SAFE
AS $$ SELECT public.unaccent('public.unaccent', $1) $$;Functions to know: to_tsvector, to_tsquery, plainto_tsquery, phraseto_tsquery, websearch_to_tsquery, setweight, strip, ts_rank, ts_rank_cd, ts_headline, ts_rewrite, ts_debug, ts_lexize, ts_stat. A configuration named in to_tsvector('english', ...) must be written explicitly in an index expression; relying on default_text_search_config makes the expression non-immutable and PostgreSQL refuses it.
Weights are labels A, B, C, D attached to lexemes with setweight; the labels are applied when you build the vector and positions continue across concatenation:
SELECT setweight(to_tsvector('english', 'Title words'), 'A') || setweight(to_tsvector('english', 'body words here'), 'D');
-- 'bodi':3 'titl':1A 'word':2A,4GIN versus GiST for text search Must-know
The manual: "GIN indexes are the preferred text search index type." A GiST index "is lossy, meaning that the index might produce false matches, and it is necessary to check the actual table row to eliminate such false matches". The index structure and operator classes are in Indexing; the FTS-specific decisions are:
| Question | GIN (USING GIN (search_vector)) | GiST (USING GIST (search_vector)) |
|---|---|---|
| Search speed | Fast; one lookup per term | Slower: signature lossy, extra heap rechecks |
| Build and update | Slow to update (one entry per lexeme); fastupdate pending list absorbs writes; maintenance_work_mem helps build | Cheaper to update, not sensitive to maintenance_work_mem |
| Size | Larger for rare terms, compresses posting lists | Fixed-size signature per row (siglen option, bytes) |
| Weight labels | Not stored: a weighted query needs a recheck against the row | Not stored either |
| Best when | Read-heavy, many documents | Frequent updates, smaller corpora |
| Knobs | fastupdate (on by default), gin_pending_list_limit (default 4 MB) | siglen |
CREATE INDEX articles_search_idx ON articles USING GIN (search_vector);
-- If response-time consistency matters more than write speed:
ALTER INDEX articles_search_idx SET (fastupdate = off);
-- Flush the pending list now (it is also flushed by VACUUM and when it passes gin_pending_list_limit):
SELECT gin_clean_pending_list('articles_search_idx'); GIN pending list and search (fastupdate = on)
1 INSERT of 100 rows -> entries appended to the pending list (cheap)
2 SELECT ... @@ query -> scans the main index AND the whole pending list
3 ... thousands of inserts -> pending list reaches gin_pending_list_limit (4 MB)
4 next INSERT (or VACUUM) -> pays the cost of merging the list into the index (latency spike)
-- a large pending list slows searches; autovacuum keeps it shortGenerated columns are the right place for the tsvector: PostgreSQL maintains a GENERATED ALWAYS AS (...) STORED column with no trigger, and the expression can combine columns with weights. Adding one to a large table rewrites the table (4.2 s for 100,000 rows in the lab), so do it in a maintenance window or build a nullable column and backfill in batches, per Zero-Downtime Schema Migrations. A generated expression must be immutable, which rules out unaccent unless wrapped, and rules out to_tsvector without an explicit configuration name.
pg_trgm in detail Must-know
| Function or operator | Meaning | Default threshold |
|---|---|---|
similarity(a, b) and a % b | Share of trigrams in common (0 to 1) | pg_trgm.similarity_threshold 0.3 |
word_similarity(a, b) and a <% b | Similarity of a to the best matching word extent in b | pg_trgm.word_similarity_threshold 0.6 |
strict_word_similarity(a, b) and a <<% b | Same, but the extent must follow word boundaries | pg_trgm.strict_word_similarity_threshold 0.5 |
a <-> b | Distance, 1 minus similarity; used for KNN ordering with GiST | none |
show_trgm(text) | Show the trigrams (word gives " w", " wo", ord, rd , wor) | none |
LIKE, ILIKE, ~, ~* | Index-assisted with gin_trgm_ops or gist_trgm_ops; patterns with no extractable trigram degrade to a full index scan | n/a |
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX articles_title_trgm ON articles USING GIN (title gin_trgm_ops);
SET pg_trgm.similarity_threshold = 0.4; -- per session
SELECT title, similarity(title, 'invertd indx') AS s
FROM articles WHERE title % 'invertd indx' ORDER BY s DESC LIMIT 10;
SELECT title FROM articles WHERE title ILIKE '%ndexi%'; -- uses the trigram indexLIKE acceleration in practice: in the lab, ILIKE '%ndexi%' on 100,000 titles went from 109 ms (sequential scan) to 24 ms (bitmap scan on the trigram GIN), and the plan shows Bitmap Index Scan on lab_docs_trgm. pg_trgm extracts trigrams only from characters the database locale classifies as alphanumeric. In the lab (UTF8 database, en_US.utf8 collation and ctype) Persian and Chinese text produced trigrams and LIKE '%تاب%' used the GIN index; on a database created with the C locale non-ASCII letters may be skipped, which is the reason pg_bigm documents itself as the option for Japanese. Test your own locale before trusting it.
Elasticsearch internals: shards, segments, refresh and merge Must-know
An index is split into shards (number_of_shards, fixed at creation; default 1 in current versions) and each shard has replicas (number_of_replicas, default 1). A document goes to shard hash(_routing or _id) mod number_of_shards. Each shard is a Lucene index made of immutable segments. Elasticsearch's own description: "A segment is similar to an inverted index, but the word index in Lucene means 'a collection of segments plus a commit point'."
Near-real-time visibility
1 PUT /articles/_doc/1 {...} -> document goes to the in-memory buffer and the translog (durable)
2 GET /articles/_search -> does NOT see doc 1 (not in any searchable segment yet)
3 refresh (every index.refresh_interval, default 1s) -> buffer written as a new segment, opened for search
4 GET /articles/_search -> sees doc 1
5 flush (translog size or time) -> segments fsynced, Lucene commit, translog trimmed
6 merge (background) -> small segments merged, deleted documents physically droppedThe documentation puts it exactly: "By default, Elasticsearch periodically refreshes indices every second, but only on indices that have received one search request or more in the last 30 seconds." You can force visibility with POST /articles/_refresh or ?refresh=wait_for on the write, but each forced refresh creates a tiny segment, so do not refresh per document.
| Concept | What it does | Knob or API |
|---|---|---|
| Primary and replica shard | Write goes to the primary then replicas; searches use any copy | number_of_replicas (dynamic), number_of_shards (fixed; use _split, _shrink or reindex) |
| Segment | Immutable unit of the Lucene index; deletes are bit flags | _segments, _cat/segments |
| Refresh | Make recent writes searchable | index.refresh_interval (1s; -1 during bulk loads), _refresh |
| Flush and translog | Durability between commits | index.translog.durability, _flush |
| Merge | Combine segments, drop deleted docs | Tiered merge policy, _forcemerge (read-only indices only) |
| Update | Delete old version plus index new one | _update, optimistic concurrency with if_seq_no and if_primary_term |
| Relevance statistics | IDF is computed per shard, which skews scores on small indices | search_type=dfs_query_then_fetch |
| Deep pagination | from + size is capped by index.max_result_window (10,000) | search_after with a point in time (PIT) |
| Cluster health | green, yellow (a replica is unassigned), red (a primary is unassigned) | _cluster/health |
A mapping declares field types and analyzers; changing an existing field's analyzer or type needs a new index and a reindex, so build against an alias from the start:
{
"settings": {
"number_of_shards": 3,
"number_of_replicas": 1,
"analysis": {
"filter": { "edge_2_10": { "type": "edge_ngram", "min_gram": 2, "max_gram": 10 } },
"analyzer": {
"autocomplete": { "tokenizer": "standard", "filter": ["lowercase", "edge_2_10"] }
}
}
},
"mappings": {
"dynamic": "strict",
"properties": {
"title": {
"type": "text",
"analyzer": "standard",
"fields": {
"exact": { "type": "text", "analyzer": "keyword" },
"ac": { "type": "text", "analyzer": "autocomplete", "search_analyzer": "standard" }
}
},
"body": { "type": "text", "analyzer": "persian" },
"category": { "type": "keyword" },
"published_at": { "type": "date" },
"suggest": { "type": "completion" }
}
}
}text fields are analyzed for full-text search; keyword fields are indexed as one exact term for filters, sorting and aggregations; multi-fields (fields) index the same value several ways.
Lucene internals, briefly Good to know
| Piece | Role |
|---|---|
IndexWriter | Buffers documents, flushes them as segments, runs the merge policy |
| Term dictionary and index (an FST) | Maps a term to its postings; the FST is an in-memory compressed automaton, which is also what makes prefix, fuzzy and regex term enumeration practical |
| Postings with skip data | Doc ids, frequencies, positions, offsets; skip lists make intersections jump instead of walk |
| Norms | Per-field length factor used by BM25 |
| Doc values | Column-oriented per-field storage for sorting, aggregations and scripts |
| Stored fields | The original values (Elasticsearch _source) |
| BKD trees | Numeric, date and geo-point range indexes ("points") |
| HNSW graphs | Approximate nearest-neighbour vector index per segment |
| Tiered merge policy | Merges similar-sized segments; deleted documents vanish at merge time |
Immutability is the design: writers never modify a segment, so readers need no locks, caches stay valid, and a crash loses only the uncommitted buffer (rebuilt from the translog). The cost is write amplification from merges and the fact that updates are delete-plus-insert; the same trade-off as an LSM-tree in Storage Engines.
Limits and error messages you will meet Must-know
| Engine | Error or limit | Meaning |
|---|---|---|
| PostgreSQL | ERROR: syntax error in tsquery: "fat & ) rat", ERROR: no operand in tsquery: "fat &" | Raw user input passed to to_tsquery; use websearch_to_tsquery |
| PostgreSQL | ERROR: word is too long (3000 bytes, max 2047 bytes) | A lexeme over the 2 KB limit in a tsvector value (to_tsvector only prints NOTICE: word is too long to be indexed and skips it); also string is too long for tsvector when one value passes 1 MB |
| PostgreSQL | Lexeme over 2 KB, over 256 positions per lexeme, positions up to 16,383 | Documented limits; long words are skipped or truncated |
| PostgreSQL | ERROR: functions in index expression must be marked IMMUTABLE (SQLSTATE 42P17), ERROR: generation expression is not immutable | unaccent or a config-less to_tsvector in an index or generated column |
| MySQL | ERROR 1191 (HY000): Can't find FULLTEXT index matching the column list | MATCH column list does not equal an existing FULLTEXT index |
| Elasticsearch | index_not_found_exception (404), mapper_parsing_exception (400) | Missing index, value that does not fit the mapping |
| Elasticsearch | es_rejected_execution_exception / HTTP 429 | Write or search queue full; back off and retry |
| Elasticsearch | version_conflict_engine_exception (409) | Optimistic concurrency check failed |
| Elasticsearch | Result window is too large, from + size must be less than or equal to: [10000] | Deep paging; use search_after |
| Meilisearch | invalid_search_filter | Filtering on an attribute not in filterableAttributes |
| SQLite | fts5: syntax error near "..." | Unquoted punctuation in the MATCH string |
Solving the classic problems
PostgreSQL full-text search, the right way
| Solution | How | Advantage | Cost or limit |
|---|---|---|---|
LIKE '%x%' (before) | Sequential scan | Nothing to set up | Reads every row, no stemming, no ranking |
Stored generated tsvector + GIN | GENERATED ALWAYS AS (...) STORED, websearch_to_tsquery, ts_rank | Transactional, no sync, ranked | Table rewrite on add; ranking cost grows with matches |
| Expression index | CREATE INDEX ... USING GIN (to_tsvector('english', title)) | No extra column | The query must repeat the exact expression; no weights without more work |
| Trigram fallback | pg_trgm % when FTS returns nothing | Typos, partial words | Second query, larger index |
Before: Go. A leading-wildcard ILIKE. It returns correct rows but scans the whole table, finds no foxes when you type fox, and returns them in arbitrary order.
// Package before searches titles with a leading-wildcard ILIKE.
// It is correct, but a B-tree index cannot help: the planner has no
// sorted prefix to seek to, so every row is read for every query.
package before
import (
"context"
"database/sql"
)
type Article struct {
ID int64
Title string
}
func Search(ctx context.Context, db *sql.DB, q string) ([]Article, error) {
rows, err := db.QueryContext(ctx,
`SELECT id, title FROM articles WHERE title ILIKE '%' || $1 || '%' LIMIT 20`, q)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Article
for rows.Next() {
var a Article
if err := rows.Scan(&a.ID, &a.Title); err != nil {
return nil, err
}
out = append(out, a)
}
return out, rows.Err()
}After: SQL and Go. First the DDL: a stored generated tsvector column with weights, a GIN index and a trigram index.
-- Generated tsvector column: PostgreSQL keeps it in sync with title/body.
-- The title is weighted A and the body C, so title hits rank higher.
ALTER TABLE articles
ADD COLUMN search_vector tsvector
GENERATED ALWAYS AS (
setweight(to_tsvector('english', coalesce(title, '')), 'A') ||
setweight(to_tsvector('english', coalesce(body, '')), 'C')
) STORED;
-- GIN is the preferred index type for text search.
CREATE INDEX articles_search_idx ON articles USING GIN (search_vector);
-- Trigram index for typo-tolerant and substring matching on titles.
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX articles_title_trgm_idx ON articles USING GIN (title gin_trgm_ops);Then the query: websearch_to_tsquery for user input, ts_rank for ordering, and a pg_trgm % fallback when nothing matched.
// Package after uses a stored tsvector with a GIN index, and falls back to
// pg_trgm similarity when full-text search finds nothing (typos, partial words).
package after
import (
"context"
"database/sql"
)
type Article struct {
ID int64
Title string
Rank float64
}
const ftsQuery = `
SELECT id, title, ts_rank(search_vector, query) AS rank
FROM articles, websearch_to_tsquery('english', $1) AS query
WHERE search_vector @@ query
ORDER BY rank DESC, id
LIMIT 20`
// The % operator uses pg_trgm.similarity_threshold (default 0.3).
const fuzzyQuery = `
SELECT id, title, similarity(title, $1) AS rank
FROM articles
WHERE title % $1
ORDER BY rank DESC, id
LIMIT 20`
func Search(ctx context.Context, db *sql.DB, q string) ([]Article, error) {
out, err := run(ctx, db, ftsQuery, q)
if err != nil || len(out) > 0 {
return out, err
}
return run(ctx, db, fuzzyQuery, q)
}
func run(ctx context.Context, db *sql.DB, query, q string) ([]Article, error) {
rows, err := db.QueryContext(ctx, query, q)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Article
for rows.Next() {
var a Article
if err := rows.Scan(&a.ID, &a.Title, &a.Rank); err != nil {
return nil, err
}
out = append(out, a)
}
return out, rows.Err()
}database/sql has no search abstraction, and none is needed: tsvector and tsquery are SQL-side concepts, so the Go code is one parameterised statement. Always pass user input as a bind parameter ($1) to websearch_to_tsquery, not to to_tsquery.
Before: Laravel. A like '%...%' clause in Eloquent. Same scan, same missing ranking.
<?php
// app/Http/Controllers/ArticleSearchController.php
// A leading wildcard cannot use a B-tree index: every row is scanned,
// there is no stemming, and there is no ranking.
namespace App\Http\Controllers;
use App\Models\Article;
use Illuminate\Http\Request;
final class ArticleSearchController
{
public function __invoke(Request $request)
{
$q = $request->string('q')->toString();
return Article::query()
->where('title', 'like', "%{$q}%")
->limit(20)
->get();
}
}After: Laravel. A migration with DB::statement for the generated column and GIN index (the Blueprint has no generated tsvector type), a model with a ranked scope, a portable whereFullText scope and Scout's Searchable trait, and the Scout driver config.
<?php
// database/migrations/2026_01_01_000000_add_search_vector_to_articles.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
public function up(): void
{
// The Blueprint has no generated tsvector type, so use raw SQL.
DB::statement(<<<'SQL'
ALTER TABLE articles
ADD COLUMN search_vector tsvector
GENERATED ALWAYS AS (
setweight(to_tsvector('english', coalesce(title, '')), 'A') ||
setweight(to_tsvector('english', coalesce(body, '')), 'C')
) STORED
SQL);
DB::statement('CREATE INDEX articles_search_idx ON articles USING GIN (search_vector)');
}
public function down(): void
{
DB::statement('DROP INDEX IF EXISTS articles_search_idx');
DB::statement('ALTER TABLE articles DROP COLUMN search_vector');
}
};<?php
// app/Models/Article.php
namespace App\Models;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;
class Article extends Model
{
// Scout keeps an external index in sync through model observers.
// With SCOUT_DRIVER=meilisearch this model is searched there instead.
use Searchable;
// Ranked search on the generated column; uses the GIN index.
// Named "matching", not "search": Scout's Searchable trait already owns Article::search().
public function scopeMatching(Builder $query, string $term): Builder
{
return $query
->whereRaw("search_vector @@ websearch_to_tsquery('english', ?)", [$term])
->orderByRaw("ts_rank(search_vector, websearch_to_tsquery('english', ?)) DESC", [$term]);
}
// Portable variant for a column that has a full-text index declared with
// $table->fullText('title')->language('english') in a migration.
public function scopeSearchPortable(Builder $query, string $term): Builder
{
return $query->whereFullText('title', $term);
}
// Only these fields are sent to the external engine.
public function toSearchableArray(): array
{
return [
'id' => $this->id,
'title' => $this->title,
'body' => $this->body,
];
}
}<?php
// config/scout.php (excerpt): the driver is chosen by environment.
// SCOUT_DRIVER=meilisearch, MEILISEARCH_HOST=http://127.0.0.1:7700, MEILISEARCH_KEY=masterKey
return [
'driver' => env('SCOUT_DRIVER', 'database'),
'queue' => true,
'meilisearch' => [
'host' => env('MEILISEARCH_HOST', 'http://localhost:7700'),
'key' => env('MEILISEARCH_KEY'),
],
];
// Usage:
// Article::query()->matching('postgres full text')->take(20)->get(); // PostgreSQL FTS scope
// Article::search('postgres full text')->take(20)->get(); // Scout (Meilisearch/database driver)The query builder documents whereFullText and orWhereFullText "for columns that have full text indexes", transformed "into the appropriate SQL for the underlying database system", with MATCH AGAINST on MySQL and MariaDB; the migration fullText('body')->language('english') declares such an index on PostgreSQL. The documentation does not spell out the SQL it generates for PostgreSQL, so for a generated tsvector column with weights and ts_rank, whereRaw is the honest tool.
Search that survives typos
FTS matches lexemes, so invertd indx finds nothing. The standard fix is a two-step query: full-text first (precise, ranked), trigram second (fuzzy) only when the first returns nothing, or a blend of both.
-- Step 2 of the fallback: trigram similarity over title, best first
SELECT id, title, similarity(title, $1) AS rank
FROM articles
WHERE title % $1
ORDER BY rank DESC, id
LIMIT 20;
-- A blend: union both, keep the best score per row
SELECT id, max(score) AS score FROM (
SELECT id, ts_rank(search_vector, q) AS score
FROM articles, websearch_to_tsquery('english', $1) q WHERE search_vector @@ q
UNION ALL
SELECT id, similarity(title, $1) FROM articles WHERE title % $1
) u GROUP BY id ORDER BY score DESC LIMIT 20;Laravel Scout's database engine does exactly this fallback: with 'trigram' => ['title'] it "retries searches using trigram matching only when the initial search returns no results", and trigram_mode set to blend includes both. See Laravel Scout. Meilisearch and Typesense do it inside the engine: Meilisearch "accepts one typo for query terms containing five or more characters, and up to two typos if the term is at least nine characters long", Typesense uses num_typos with min_len_1typo 4 and min_len_2typo 7 by default.
Persian search in PostgreSQL
PostgreSQL has no persian configuration, so normalize first and tokenize with simple. The function must be IMMUTABLE to live in a generated column or index. The same function runs on the query text.
CREATE FUNCTION fa_normalize(t text) RETURNS text LANGUAGE sql IMMUTABLE PARALLEL SAFE AS $$
SELECT regexp_replace(
translate(replace(replace(t, E'\u200c', ' '), E'\u0640', ''),
E'\u064a\u0649\u0643\u0629\u06c0', -- Arabic yeh, alef maksura, kaf, teh marbuta, heh+yeh above
E'\u06cc\u06cc\u06a9\u0647\u0647'), -- Persian yeh, yeh, keheh, heh, heh
E'[\u064b-\u065f\u0670]', '', 'g') -- harakat and dagger alef
$$;
CREATE TABLE fa_docs (
id serial PRIMARY KEY,
body text,
search_vector tsvector GENERATED ALWAYS AS (to_tsvector('simple', fa_normalize(body))) STORED);
CREATE INDEX ON fa_docs USING GIN (search_vector);
INSERT INTO fa_docs(body) VALUES ('میشود كتاب جديد'), ('مُحَمَّد کتابها');
SELECT id FROM fa_docs WHERE search_vector @@ websearch_to_tsquery('simple', fa_normalize('می شود كتاب')); -- 1
SELECT id FROM fa_docs WHERE search_vector @@ websearch_to_tsquery('simple', fa_normalize('محمد')); -- 2Lab result: the first row is stored as 'جدید':4 'شود':2 'می':1 'کتاب':3 (ZWNJ became a space, ك and ي were mapped), and the two queries above matched the expected rows. Plural handling (کتاب versus کتابها) still needs either a stemmer or the trigram index: similarity('کتاب', 'کتابها') was 0.5 in the lab.
The application layer uses the same rules (the Go and PHP versions are byte-for-byte the same mapping):
// Package persian normalises Persian/Arabic text before it reaches a search
// engine that has no Persian analyzer (PostgreSQL 'simple', Meilisearch, FTS5).
package persian
import "strings"
// Normalize maps Arabic letter variants to the Persian ones, drops optional
// diacritics and tatweel, turns the zero-width non-joiner into a space and
// folds Persian and Arabic-Indic digits to ASCII digits.
func Normalize(s string) string {
return strings.Map(func(r rune) rune {
switch {
case r == '\u064A' || r == '\u0649': // Arabic yeh, alef maksura -> Persian yeh U+06CC
return '\u06CC'
case r == '\u0643': // Arabic kaf -> Persian keheh U+06A9
return '\u06A9'
case r == '\u0629' || r == '\u06C0': // teh marbuta, heh with yeh above -> heh U+0647
return '\u0647'
case r >= '\u064B' && r <= '\u065F', r == '\u0670', r == '\u0640': // harakat, dagger alef, tatweel
return -1
case r == '\u200C' || r == '\u200D' || r == '\u200F': // ZWNJ, ZWJ, RLM -> space
return ' '
case r >= '\u06F0' && r <= '\u06F9': // Persian digits
return '0' + (r - '\u06F0')
case r >= '\u0660' && r <= '\u0669': // Arabic-Indic digits
return '0' + (r - '\u0660')
}
return r
}, s)
}<?php
// app/Support/PersianNormalizer.php
namespace App\Support;
final class PersianNormalizer
{
// Same rules as the Go and SQL versions on the page: one normalisation,
// applied at index time AND at query time, or terms never meet.
public static function normalize(string $text): string
{
$text = strtr($text, [
"\u{064A}" => "\u{06CC}", // Arabic yeh -> Persian yeh
"\u{0649}" => "\u{06CC}", // alef maksura -> Persian yeh
"\u{0643}" => "\u{06A9}", // Arabic kaf -> Persian keheh
"\u{0629}" => "\u{0647}", // teh marbuta -> heh
"\u{06C0}" => "\u{0647}", // heh with yeh above -> heh
"\u{200C}" => ' ', // ZWNJ -> space
"\u{200D}" => ' ', // ZWJ -> space
"\u{0640}" => '', // tatweel
]);
// Harakat (diacritics) U+064B..U+065F and dagger alef U+0670.
$text = preg_replace('/[\x{064B}-\x{065F}\x{0670}]/u', '', $text) ?? $text;
// Persian and Arabic-Indic digits to ASCII.
return strtr($text, [
'۰' => '0', '۱' => '1', '۲' => '2', '۳' => '3', '۴' => '4',
'۵' => '5', '۶' => '6', '۷' => '7', '۸' => '8', '۹' => '9',
'٠' => '0', '١' => '1', '٢' => '2', '٣' => '3', '٤' => '4',
'٥' => '5', '٦' => '6', '٧' => '7', '٨' => '8', '٩' => '9',
]);
}
}Elasticsearch ships the analyzer. The documented definition of persian is a char filter plus three token filters, which you can copy and extend:
{
"settings": {
"analysis": {
"char_filter": { "zero_width_spaces": { "type": "mapping", "mappings": ["\\u200C=>\\u0020"] } },
"filter": { "persian_stop": { "type": "stop", "stopwords": "_persian_" } },
"analyzer": {
"rebuilt_persian": {
"tokenizer": "standard",
"char_filter": ["zero_width_spaces"],
"filter": ["lowercase", "decimal_digit", "arabic_normalization", "persian_normalization", "persian_stop", "persian_stem"]
}
}
}
}
}Autocomplete
-- PostgreSQL: prefix over a tsvector (GIN-backed), last word as a prefix
SELECT id, title FROM articles
WHERE to_tsvector('simple', title) @@ to_tsquery('simple', 'inver:*')
LIMIT 10;
-- Prefix on the whole string: a B-tree with text_pattern_ops (or a C collation)
CREATE INDEX articles_title_prefix ON articles (lower(title) text_pattern_ops);
SELECT title FROM articles WHERE lower(title) LIKE 'inver%' ORDER BY title LIMIT 10;{
"query": { "match": { "title.ac": { "query": "inve" } } },
"size": 5
}The title.ac sub-field is the edge n-gram field from the mapping in Elasticsearch internals: edge n-grams at index time, the standard analyzer at search time. The completion suggester is queried separately:
{
"suggest": {
"title-suggest": {
"prefix": "inv",
"completion": { "field": "suggest", "size": 5, "skip_duplicates": true, "fuzzy": { "fuzziness": 1 } }
}
}
}In Meilisearch and Typesense nothing is configured: the last word is a prefix by default, so inve already returns inverted. Debounce keystrokes (100 to 200 ms), cancel the previous request, and cache the first one or two characters.
Keeping the index in sync
The search index is a derived read model: the database stays the source of truth, and the index must be rebuildable from it. The central question is how a change in the database reaches the index.
| Approach | How | Advantage | Cost or failure mode |
|---|---|---|---|
| Dual write | The application writes the database, then the index | Simplest code | A crash, timeout or retry between the two writes leaves them different, silently; two concurrent writers can apply in opposite orders |
| Periodic full reindex | Rebuild everything on a schedule | Self-healing, simple | Stale between runs; expensive at scale |
Polling by updated_at | Job selects rows changed since a watermark | No new tables | Misses hard deletes; clock and long-transaction gaps |
| Transactional outbox | Insert an event row in the same transaction as the change; a relay drains it | Atomic with the data; works on any database | Small delay; the relay must be idempotent; the table needs cleanup |
| CDC (change data capture) | Read the WAL (PostgreSQL logical decoding) or binlog (MySQL) with Debezium | No application change; captures every writer; no outbox table | More moving parts (connector, Kafka or equivalent), schema-change care; see Change Data Capture |
| Scout observers (Laravel) | Model events queue an indexing job | One line to enable | Misses writes that bypass Eloquent (DB::table, raw SQL, other services) |
Dual write, two concurrent requests for the same article
Request A Request B
1 UPDATE articles SET title='v1'
2 UPDATE articles SET title='v2'
3 index.upsert(id=42, title='v2')
4 index.upsert(id=42, title='v1') -- arrives late
-- database says v2, index says v1, and nothing will ever correct it Transactional outbox
1 BEGIN
2 UPDATE articles SET title='v2' WHERE id=42
3 INSERT INTO search_outbox(article_id, op) VALUES (42, 'upsert')
4 COMMIT -- both rows exist, or neither does
5 relay: DELETE ... FOR UPDATE SKIP LOCKED RETURNING -- claim a batch
6 relay: read CURRENT row 42, POST it to the index (upsert by id)
7 relay: COMMIT -- claim is released; on crash it rolls back and is retriedThe relay reads the current row, not the event payload, and upserts by id, so duplicates and reordering are harmless: applying "upsert 42" twice gives the same document. The outbox table and an optional trigger (so no code path can forget it):
CREATE TABLE search_outbox (
id bigserial PRIMARY KEY,
article_id bigint NOT NULL,
op text NOT NULL CHECK (op IN ('upsert', 'delete')),
created_at timestamptz NOT NULL DEFAULT now());
CREATE FUNCTION articles_outbox() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO search_outbox(article_id, op)
VALUES (COALESCE(NEW.id, OLD.id), CASE WHEN TG_OP = 'DELETE' THEN 'delete' ELSE 'upsert' END);
RETURN NULL;
END $$;
CREATE TRIGGER articles_outbox_trg AFTER INSERT OR UPDATE OR DELETE ON articles
FOR EACH ROW EXECUTE FUNCTION articles_outbox();The pattern itself (relay, ordering, cleanup, at-least-once delivery) is in Transactional Outbox Pattern. The relay for a search index, in Go:
// Package indexsync drains a transactional outbox into a search index
// (Meilisearch HTTP API shown; Elasticsearch _bulk works the same way).
// Delivery is at-least-once, so every index write is an idempotent upsert
// of the row's CURRENT state, never of a stale event payload.
package indexsync
import (
"bytes"
"context"
"database/sql"
"encoding/json"
"fmt"
"net/http"
)
// SKIP LOCKED lets several relay workers drain the table without waiting on each other.
const claim = `
DELETE FROM search_outbox
WHERE id IN (
SELECT id FROM search_outbox ORDER BY id FOR UPDATE SKIP LOCKED LIMIT $1)
RETURNING article_id, op`
type Relay struct {
DB *sql.DB
HTTP *http.Client
Index string // e.g. http://localhost:7700/indexes/articles
Key string
}
// Once claims one batch, applies it to the index and commits. A failure
// rolls the DELETE back, so the events are retried on the next call.
func (r *Relay) Once(ctx context.Context, batch int) (int, error) {
tx, err := r.DB.BeginTx(ctx, nil)
if err != nil {
return 0, err
}
defer tx.Rollback()
rows, err := tx.QueryContext(ctx, claim, batch)
if err != nil {
return 0, err
}
last := map[int64]string{} // collapse repeated events for one article
for rows.Next() {
var id int64
var op string
if err := rows.Scan(&id, &op); err != nil {
rows.Close()
return 0, err
}
last[id] = op
}
if err := rows.Err(); err != nil {
return 0, err
}
rows.Close()
var docs []map[string]any
var gone []int64
for id := range last {
var title, body string
err := tx.QueryRowContext(ctx, `SELECT title, body FROM articles WHERE id = $1`, id).Scan(&title, &body)
if err == sql.ErrNoRows {
gone = append(gone, id) // deleted after the event was written
continue
}
if err != nil {
return 0, err
}
docs = append(docs, map[string]any{"id": id, "title": title, "body": body})
}
if len(docs) > 0 {
if err := r.send(ctx, http.MethodPost, "/documents", docs); err != nil {
return 0, err
}
}
if len(gone) > 0 {
if err := r.send(ctx, http.MethodPost, "/documents/delete-batch", gone); err != nil {
return 0, err
}
}
return len(last), tx.Commit()
}
func (r *Relay) send(ctx context.Context, method, path string, payload any) error {
b, err := json.Marshal(payload)
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, method, r.Index+path, bytes.NewReader(b))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+r.Key)
resp, err := r.HTTP.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
return fmt.Errorf("index returned %s", resp.Status)
}
return nil
}Rebuilding is part of the design, because changing an analyzer or mapping means a new index. Build the new index beside the old one, fill it from the database, then flip an alias in one atomic call:
{
"actions": [
{ "remove": { "index": "articles_v1", "alias": "articles" } },
{ "add": { "index": "articles_v2", "alias": "articles" } }
]
}Practical rules: give each document an external version (Elasticsearch version_type=external with the row's updated_at epoch or a version column) so a late old write is rejected with a 409 instead of overwriting a newer one; run a periodic drift check (count by id range, or compare max(updated_at)); keep the outbox drain running during the reindex and replay the events that arrived meanwhile; and treat the search index as disposable.
Laravel Scout: drivers, engines, indexing strategies and queueing
Scout "provides a simple, driver-based solution for adding full-text search to your Eloquent models. Using model observers, Scout will automatically keep your search indexes in sync with your Eloquent records." Drivers in the documented set (Laravel 13):
| Driver | Where the search runs | When to use |
|---|---|---|
database | In your MySQL or PostgreSQL, with full-text indexes and LIKE | No external service; moderate data; PostgreSQL gets stored tsvector, mode, rank and trigram options |
collection | In PHP: loads records and filters with Str::is | Prototypes, "a few hundred records", and tests |
| Meilisearch | External engine | Typo tolerance, filters, instant search, small operations |
| Typesense | External engine | Same class; schema defined in config/scout.php |
| Algolia | Hosted | No operations; cost per record and request |
| Turbopuffer | Hosted, full-text, semantic and hybrid | Vector-heavy search |
Indexing strategies and the knobs Scout gives you:
| Need | Scout feature |
|---|---|
| Index only some rows | shouldBeSearchable() (applies to save, create, queries and relationships; not to a direct searchable() call, and not to the database engine) |
| Shape the document | toSearchableArray(); searchableAs() or #[SearchableAs] for the index name; getScoutKey() for a custom id |
| Backfill an existing table | php artisan scout:import "App\Models\Article", or scout:queue-import ... --chunk=500 |
| Clear an index | php artisan scout:flush "App\Models\Article" |
| Bulk edits without index traffic | Article::withoutSyncingToSearch(fn () => ...) |
| Index by query | Order::where('price', '>', 100)->searchable() and ->unsearchable() chunk the results |
| Queue indexing | 'queue' => true, or ['connection' => 'redis', 'queue' => 'scout'], plus a worker: php artisan queue:work redis --queue=scout |
| Avoid duplicate jobs on write-heavy models | Scout::makeSearchableUsing(MakeSearchableUniquely::class) and removeFromSearchUsing(RemoveFromSearchUniquely::class) |
| Meilisearch settings | index-settings in config/scout.php (filterableAttributes, sortableAttributes, others), applied with php artisan scout:sync-index-settings in the deploy |
| Filters | search('x')->where('user_id', 1), whereIn, whereNotIn; Meilisearch needs the attribute filterable |
| Hydrate with relations | ->query(fn ($q) => $q->with('author')) (not for filtering on external engines) |
| Soft deletes | Scout handles them when the model is in index-settings; Typesense needs a __soft_deleted field |
The documentation warns that for an engine other than database or collection you should "strongly consider configuring a queue driver", and that Algolia and Meilisearch index asynchronously even with queue false: a write is acknowledged before it is searchable. Scout's observers see only Eloquent events, so bulk DB::table() updates, other services and migrations bypass them; use an outbox or CDC (above) when anything other than Eloquent writes the table.
<?php
// app/Models/Article.php (Scout with an external engine: sync and indexing strategy)
namespace App\Models;
use App\Support\PersianNormalizer;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Laravel\Scout\Searchable;
class Article extends Model
{
use Searchable, SoftDeletes;
// The document the engine receives. Normalise here so the index holds one
// spelling per word; normalise the query the same way before searching.
public function toSearchableArray(): array
{
return [
'id' => $this->id,
'title' => PersianNormalizer::normalize($this->title),
'body' => PersianNormalizer::normalize($this->body),
'published_at' => $this->published_at?->timestamp,
];
}
// Drafts never reach the index. Applies to save/create/queries, not to a
// direct ->searchable() call on a collection.
public function shouldBeSearchable(): bool
{
return $this->published_at !== null;
}
}
// Bulk work without per-row index traffic, then one explicit import:
// Article::withoutSyncingToSearch(fn () => Article::factory()->count(10_000)->create());
// php artisan scout:queue-import "App\Models\Article" --chunk=500
// php artisan scout:flush "App\Models\Article"
// php artisan scout:sync-index-settings
//
// Query side: normalise the user's text, filter with where (needs
// filterableAttributes on Meilisearch), then hydrate through Eloquent.
// Article::search(PersianNormalizer::normalize($q))
// ->where('published_at', '>', now()->subYear()->timestamp)
// ->query(fn ($q) => $q->with('author'))
// ->paginate(20);<?php
// config/scout.php (excerpt): queue indexing and declare the Meilisearch index settings.
use App\Models\Article;
return [
'driver' => env('SCOUT_DRIVER', 'meilisearch'),
// Indexing runs on a queue worker, so a slow engine never slows the request.
// Run: php artisan queue:work redis --queue=scout
'queue' => ['connection' => 'redis', 'queue' => 'scout'],
'meilisearch' => [
'host' => env('MEILISEARCH_HOST', 'http://localhost:7700'),
'key' => env('MEILISEARCH_KEY'),
// Applied by: php artisan scout:sync-index-settings (put it in the deploy script).
'index-settings' => [
Article::class => [
'searchableAttributes' => ['title', 'body'], // order = attribute ranking
'filterableAttributes' => ['published_at'],
'sortableAttributes' => ['published_at'],
],
],
],
];The database engine, with weights, a language and trigram typo tolerance on PostgreSQL:
<?php
// app/Models/Page.php: Scout "database" engine on PostgreSQL, no external service.
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Attributes\SearchUsingFullText;
use Laravel\Scout\Searchable;
class Page extends Model
{
use Searchable;
// Needs a stored tsvector column and trigram indexes, created in a migration with:
// $table->searchable(columns: ['title' => 'A', 'body' => 'D'], language: 'english',
// trigram: ['title'], tsvector: 'search_vector');
// 'vector' => true: search the stored column; 'trigram' => typo-tolerant fallback.
#[SearchUsingFullText(['search_vector'], ['vector' => true, 'mode' => 'websearch', 'trigram' => ['title']])]
public function toSearchableArray(): array
{
return ['search_vector' => null];
}
}
// Per-call override:
// Page::search('"full text" -mysql')->options(['mode' => 'websearch'])->get();MySQL FULLTEXT and SQLite FTS5
MySQL InnoDB FULLTEXT. The index is created with FULLTEXT(col) and queried with MATCH(col) AGAINST('...' IN NATURAL LANGUAGE MODE) or IN BOOLEAN MODE (+must, -not, word* prefix, "phrase"). Defaults that bite: innodb_ft_min_token_size is 3 (shorter words are not indexed), stop words are on (innodb_ft_enable_stopword), there is no stemming, and a column list in MATCH must equal the column list of a FULLTEXT index or you get error 1191. The default parser needs spaces between words; for Chinese, Japanese or Korean use WITH PARSER ngram, where ngram_token_size (default 2) sets the gram length. Verified on mysql:8.0.36:
CREATE TABLE a (id int PRIMARY KEY AUTO_INCREMENT, body text, FULLTEXT (body)) ENGINE=InnoDB;
CREATE TABLE b (id int PRIMARY KEY AUTO_INCREMENT, body text, FULLTEXT (body) WITH PARSER ngram) ENGINE=InnoDB;
INSERT INTO a(body) VALUES ('PostgreSQL full text search'), ('the quick brown foxes'), ('东京都');
INSERT INTO b(body) SELECT body FROM a;
SELECT id FROM a WHERE MATCH(body) AGAINST('foxes' IN NATURAL LANGUAGE MODE); -- 2
SELECT id FROM a WHERE MATCH(body) AGAINST('fox*' IN BOOLEAN MODE); -- 2 (prefix)
SELECT id FROM a WHERE MATCH(body) AGAINST('the' IN NATURAL LANGUAGE MODE); -- empty: stop word
SELECT id FROM a WHERE MATCH(body) AGAINST('京都' IN NATURAL LANGUAGE MODE); -- empty: default parser sees one token
SELECT id FROM b WHERE MATCH(body) AGAINST('京都' IN NATURAL LANGUAGE MODE); -- 3: ngram parser
SELECT id FROM a WHERE MATCH(body) AGAINST('+postgresql +search' IN BOOLEAN MODE); -- 1<?php
// database/migrations/2026_01_02_000000_add_fulltext_to_posts.php (MySQL / MariaDB)
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
// Word-based FULLTEXT index (InnoDB). whereFullText() generates MATCH ... AGAINST.
Schema::table('posts', function (Blueprint $table) {
$table->fullText(['title', 'body']);
});
// CJK text has no spaces: the ngram parser indexes fixed-size grams instead.
// The Blueprint cannot express WITH PARSER, so use raw SQL.
DB::statement('ALTER TABLE posts ADD FULLTEXT INDEX posts_ngram_ft (title) WITH PARSER ngram');
}
public function down(): void
{
DB::statement('ALTER TABLE posts DROP INDEX posts_ngram_ft');
Schema::table('posts', function (Blueprint $table) {
$table->dropFullText(['title', 'body']);
});
}
};
// Queries:
// DB::table('posts')->whereFullText(['title', 'body'], 'web developer')->get();
// // Boolean mode (+must -must_not prefix*) needs raw SQL:
// DB::table('posts')
// ->whereRaw('MATCH(title, body) AGAINST (? IN BOOLEAN MODE)', ['+laravel -wordpress'])
// ->selectRaw('posts.*, MATCH(title, body) AGAINST (?) AS score', ['laravel scout'])
// ->orderByDesc('score')->get();SQLite FTS5. A virtual table with its own tokenizer; the full engine story (file format, WAL, one writer) is in SQLite in Depth. Verified on SQLite 3.54:
CREATE VIRTUAL TABLE docs USING fts5(title, body, tokenize = 'porter unicode61 remove_diacritics 2');
INSERT INTO docs VALUES ('Foxes and dogs', 'The quick brown foxes jumped'), ('Cafe', 'crème brûlée');
SELECT title, bm25(docs) FROM docs WHERE docs MATCH 'fox jump' ORDER BY bm25(docs); -- bm25 is negative: lower is better
SELECT highlight(docs, 1, '<b>', '</b>') FROM docs WHERE docs MATCH 'fox'; -- The quick brown <b>foxes</b> jumped
SELECT snippet(docs, 1, '[', ']', '...', 5) FROM docs WHERE docs MATCH 'brulee'; -- crème [brûlée]
CREATE VIRTUAL TABLE t USING fts5(x, tokenize = 'trigram');
SELECT x FROM t WHERE x LIKE '%gresq%'; -- substring search through the trigram tokenizerOther FTS5 features to know: external-content tables (content='articles') avoid storing the text twice but need triggers to stay in sync, contentless tables store only the index, prefix='2 3' builds prefix indexes, and the optimize and merge commands maintain the segment structure.
Go clients: official go-elasticsearch, olivere/elastic and meilisearch-go
| Client | Status and shape | Pick it when |
|---|---|---|
github.com/elastic/go-elasticsearch/v8 | Official; thin HTTP client with transport, retries and a typed API (typedapi); you send JSON bodies or typed structs | Default for Elasticsearch 8 and 9; follow the server's major version |
github.com/olivere/elastic/v7 | Community query builder, the long-time favourite; its version matrix on pkg.go.dev ends at Elasticsearch 7.x | Only on an existing 7.x estate; do not start a new project on it |
| OpenSearch | github.com/opensearch-project/opensearch-go (separate client; the Elasticsearch clients refuse OpenSearch servers) | OpenSearch clusters |
github.com/meilisearch/meilisearch-go | Official Meilisearch client; methods take a context.Context (verified at v0.37.0) | Meilisearch |
Plain net/http | The lab program uses it | Small integrations; fewer dependencies |
// Package clients shows the three Go clients side by side. It compiles but is
// not meant to be run: it needs a reachable cluster and a Meilisearch key.
package clients
import (
"context"
"strings"
"github.com/elastic/go-elasticsearch/v8"
"github.com/meilisearch/meilisearch-go"
"github.com/olivere/elastic/v7"
)
const query = `{"query":{"match":{"title":{"query":"inverted index","fuzziness":"AUTO"}}},"size":20}`
// Official client: a thin HTTP client; the request body is plain JSON.
func official(ctx context.Context) error {
es, err := elasticsearch.NewClient(elasticsearch.Config{Addresses: []string{"http://localhost:9200"}})
if err != nil {
return err
}
res, err := es.Search(
es.Search.WithContext(ctx),
es.Search.WithIndex("articles"),
es.Search.WithBody(strings.NewReader(query)),
)
if err != nil {
return err
}
defer res.Body.Close()
return nil
}
// olivere/elastic: a typed query builder for Elasticsearch 7.x; its version
// matrix on pkg.go.dev ends at 7.x, so use it only on existing 7.x estates.
func olivere(ctx context.Context) error {
c, err := elastic.NewClient(elastic.SetURL("http://localhost:9200"), elastic.SetSniff(false))
if err != nil {
return err
}
q := elastic.NewMatchQuery("title", "inverted index").Fuzziness("AUTO")
_, err = c.Search().Index("articles").Query(q).Size(20).Do(ctx)
return err
}
// meilisearch-go: documents in, search out; typo tolerance is the default.
func meili(ctx context.Context) error {
c := meilisearch.New("http://localhost:7700", meilisearch.WithAPIKey("masterKey"))
idx := c.Index("articles")
if _, err := idx.AddDocuments(ctx, []map[string]any{{"id": 1, "title": "Inverted index"}}, nil); err != nil {
return err
}
_, err := idx.Search(ctx, "invertd indx", &meilisearch.SearchRequest{Limit: 20})
return err
}The work in Go is rarely the client call; it is the mapping, the bulk indexing (use _bulk or BulkIndexer in go-elasticsearch, AddDocuments batches of a few thousand in Meilisearch) and the sync pipeline above. Meilisearch writes are asynchronous: AddDocuments returns a task, and the documents are searchable only after the task succeeds, so wait for the task in tests.
Choosing
| Workload | Recommended | Extra technique | Reason |
|---|---|---|---|
| Internal tool, tickets, docs; up to a few million rows; one language | PostgreSQL generated tsvector + GIN | pg_trgm on short fields (names, titles) | Transactional with the data, no sync, no new system |
| Same, but Laravel and you want zero code | Scout database engine on PostgreSQL | searchable() migration with trigram | One config line; stored vector and typo fallback |
| Need BM25 ranking but must stay in Postgres | ParadeDB pg_search | Hybrid with pgvector through RRF | BM25 and aggregates in the database; check hosting support |
| Product catalogue, instant search, typo tolerance, small team | Meilisearch or Typesense | Outbox or Scout queue for sync; filterableAttributes | Great defaults, tiny operations |
| Large corpus, many languages, aggregations, log analytics, relevance engineering | Elasticsearch or OpenSearch | Alias-based reindex, outbox/CDC, judged query set | Analyzers, shards, aggregations, tuning knobs |
| Persian or Arabic content | Elasticsearch persian analyzer, or PostgreSQL simple with fa_normalize | Trigram index for plurals | PostgreSQL has no Persian stemmer |
| Japanese, Chinese, Korean | pg_bigm, MySQL ngram parser, FTS5 trigram, or Elasticsearch cjk/ICU analyzers | Short queries (1 to 2 characters) are the hard case | No spaces to split on |
| Mobile or desktop app, local search | SQLite FTS5 | porter unicode61 remove_diacritics 2 | Embedded, BM25 included |
| MySQL shop, simple search | InnoDB FULLTEXT, ngram parser for CJK | Move to a dedicated engine when relevance matters | No new infrastructure |
| Semantic search ("find similar meaning") | Vectors plus keywords | RRF; see Vector Search & pgvector | Keyword alone misses paraphrases |
In architecture: from a single process to a distributed system
Full-text search is a derived structure. The question at every size is whether the index lives in the same transaction as the data or somewhere that must be kept in sync, and what the user sees in the gap.
Monolith: one process, one database
A Laravel app and one PostgreSQL. Add a generated tsvector column and a GIN index (a migration, ten lines), search with websearch_to_tsquery, rank with ts_rank, highlight the top 20 with ts_headline. A row saved is searchable in the same commit: no queue, no lag, no second thing to monitor. Add a trigram index on titles for typos. This is the right design until a measured need says otherwise, and the migration path to a dedicated engine is clean because the table stays the source of truth.
Modular monolith and multiple databases
Each module owns its tables and its search vector, and a global search box needs results from several modules. Options: query each module and merge in code (simple, loses cross-module ranking), a materialized search table (a denormalized "search document" per entity with a type column, rebuilt by triggers or the outbox), or a single dedicated index fed by every module. Multi-tenant data adds a decision: one index with a tenant_id filter (cheap, risk of leaking if the filter is forgotten; see Multi-Tenancy Strategies) versus an index per tenant (isolation, many small indexes and shards). Filter first, always: apply the tenant and permission filter inside the search request, never after.
Microservices: an indexer, events and permissions
The catalogue service owns writes; a search service owns the index and exposes a query API. The flow: catalogue commits the row and an outbox event in one transaction; the relay publishes ProductChanged(id, version) to a broker; the indexer consumes it, loads the current product (and joins in data from other services, such as price or stock), builds the denormalized document and upserts it with an external version. Deletions are events too (a tombstone). What does not survive the boundary: a transaction across the catalogue and the index (the index is eventually consistent), and permissions (a document visible to some users needs an allowed_groups field filtered at query time, and a permission change is another event that must reindex). Make the indexer idempotent and replayable, because a bad mapping means replaying history into a new index. See Transactional Outbox Pattern and Change Data Capture.
Distributed data: replicas, refresh lag and clusters
Three kinds of lag stack up. Database replication lag: a search served from a PostgreSQL replica can miss a row just written (see Replication). Index lag: the outbox relay and the engine's refresh (Elasticsearch 1 s, Meilisearch asynchronous tasks) mean a write is searchable seconds later. Read-your-writes: a user who just created an item and is sent to a search results page will not see it; show it from the database, or use refresh=wait_for for that one write, or redirect to the item page. In an Elasticsearch cluster, replicas serve searches and failover shards, shard-local IDF skews scores on small indices, deep pages are capped at 10,000 hits, and cross-cluster replication handles multi-region. A cache of popular queries (a few seconds) absorbs traffic but must be keyed by the tenant and permission context.
Scaling path: 1x, 10x, 100x
| Scale | Design | What changes |
|---|---|---|
| 1x (thousands of rows) | ILIKE or Scout database engine | Nothing to tune; it just works |
| 10x (millions of rows) | Generated tsvector + GIN, pg_trgm on titles, ts_headline on the top 20 only | Watch ranking cost on broad queries (limit candidates), fastupdate and pending lists on write-heavy tables |
| 100x (tens of millions, many languages, facets) | Dedicated engine behind an outbox or CDC feed; alias-based reindex; hybrid with vectors | Shard count chosen up front, replicas for read load, index per time window for logs, query cache, judged relevance set |
| Beyond | Separate search tier with its own SLOs, per-tenant routing, learning to rank | See Search Systems |
Lab
One generated corpus (100,000 documents, deterministic seed, Zipf-distributed vocabulary with inflected forms) loaded into PostgreSQL and Meilisearch, and the same questions timed against ILIKE, PostgreSQL FTS, pg_trgm and Meilisearch. Use throw-away containers.
// Command lab loads one generated corpus into PostgreSQL and Meilisearch and
// times the same questions against: ILIKE, PostgreSQL FTS (GIN), pg_trgm (GIN),
// and Meilisearch. Run it against throw-away containers, never a real database.
//
// go run ./lab -n 100000 -dsn postgres://postgres:pw@localhost:55440/postgres \
// -meili http://localhost:7700 -key masterKey
package main
import (
"bytes"
"context"
"encoding/json"
"flag"
"fmt"
"io"
"math/rand"
"net/http"
"os"
"sort"
"strings"
"time"
"github.com/jackc/pgx/v5"
)
var base = strings.Fields(`index search query token tokenizer analyzer stemmer lexeme posting segment shard replica
ranking relevance score document field mapping filter facet cluster node vector trigram phrase prefix typo
synonym stopword language persian arabic unicode normalize highlight snippet cache refresh commit merge
inverted forward corpus term frequency inverse length saturation boost weight payload offset position
database table column row page tuple heap btree gin gist lucene postgres elastic meilisearch typesense`)
// buildWord returns one of several inflected forms so that stemming matters.
func buildWord(r *rand.Rand, z *rand.Zipf) string {
i := int(z.Uint64())
if i < len(base)*4 {
w := base[i/4]
switch i % 4 {
case 1:
return w + "s"
case 2:
return w + "ing"
case 3:
return w + "ed"
}
return w
}
// Long tail: synthetic words that appear rarely.
syl := []string{"ka", "lo", "mi", "ra", "te", "vu", "zo", "ni", "pe", "su"}
return syl[i%10] + syl[(i/10)%10] + syl[(i/100)%10] + syl[(i/1000)%10]
}
type doc struct {
ID int `json:"id"`
Title string `json:"title"`
Body string `json:"body"`
}
func corpus(n int) []doc {
r := rand.New(rand.NewSource(42))
z := rand.NewZipf(r, 1.15, 2, uint64(len(base)*4+4000))
out := make([]doc, n)
for i := range out {
var t, b []string
for j := 0; j < 4+r.Intn(3); j++ {
t = append(t, buildWord(r, z))
}
for j := 0; j < 30+r.Intn(30); j++ {
b = append(b, buildWord(r, z))
}
out[i] = doc{ID: i + 1, Title: strings.Join(t, " "), Body: strings.Join(b, " ")}
}
return out
}
func must(err error) {
if err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
}
func timed(label string, f func() error) {
t := time.Now()
must(f())
fmt.Printf("%-44s %8.1f ms\n", label, float64(time.Since(t).Microseconds())/1000)
}
func median(f func() (int, error)) (float64, int) {
var ds []float64
hits := 0
for i := 0; i < 25; i++ {
t := time.Now()
h, err := f()
must(err)
hits = h
if i >= 5 { // the first five runs warm caches
ds = append(ds, float64(time.Since(t).Microseconds())/1000)
}
}
sort.Float64s(ds)
return ds[len(ds)/2], hits
}
func meili(method, url, key string, body any) (map[string]any, error) {
var rd io.Reader
if body != nil {
b, _ := json.Marshal(body)
rd = bytes.NewReader(b)
}
req, _ := http.NewRequest(method, url, rd)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+key)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var m map[string]any
err = json.NewDecoder(resp.Body).Decode(&m)
return m, err
}
func waitTask(host, key string, m map[string]any) error {
uid := int(m["taskUid"].(float64))
for {
t, err := meili("GET", fmt.Sprintf("%s/tasks/%d", host, uid), key, nil)
if err != nil {
return err
}
switch t["status"] {
case "succeeded":
return nil
case "failed", "canceled":
return fmt.Errorf("task %d: %v", uid, t["error"])
}
time.Sleep(200 * time.Millisecond)
}
}
func main() {
n := flag.Int("n", 100000, "documents")
dsn := flag.String("dsn", "postgres://postgres:pw@localhost:55440/postgres", "PostgreSQL DSN")
host := flag.String("meili", "http://localhost:7700", "Meilisearch URL")
key := flag.String("key", "masterKey", "Meilisearch key")
flag.Parse()
ctx := context.Background()
docs := corpus(*n)
conn, err := pgx.Connect(ctx, *dsn)
must(err)
defer conn.Close(ctx)
exec := func(sql string) func() error {
return func() error { _, err := conn.Exec(ctx, sql); return err }
}
must(exec(`CREATE EXTENSION IF NOT EXISTS pg_trgm`)())
must(exec(`DROP TABLE IF EXISTS lab_docs`)())
must(exec(`CREATE TABLE lab_docs (id int PRIMARY KEY, title text, body text)`)())
timed("load: COPY into PostgreSQL", func() error {
_, err := conn.CopyFrom(ctx, pgx.Identifier{"lab_docs"}, []string{"id", "title", "body"},
pgx.CopyFromSlice(len(docs), func(i int) ([]any, error) {
return []any{docs[i].ID, docs[i].Title, docs[i].Body}, nil
}))
return err
})
must(exec(`ANALYZE lab_docs`)())
type probe struct {
name string
sql string
arg string
}
run := func(p probe) {
ms, hits := median(func() (int, error) {
rows, err := conn.Query(ctx, p.sql, p.arg)
if err != nil {
return 0, err
}
defer rows.Close()
c := 0
for rows.Next() {
c++
}
return c, rows.Err()
})
fmt.Printf("%-44s %8.2f ms hits=%d\n", p.name, ms, hits)
}
fmt.Println("\n-- 1. baseline: no text index, ILIKE scans the heap")
run(probe{"ILIKE '%tokenizer%' on body (all matches)", `SELECT id FROM lab_docs WHERE body ILIKE '%' || $1 || '%'`, "tokenizer"})
run(probe{"ILIKE '%ndexi%' on title (all matches)", `SELECT id FROM lab_docs WHERE title ILIKE '%' || $1 || '%'`, "ndexi"})
fmt.Println("\n-- 2. PostgreSQL FTS: generated tsvector + GIN")
timed("build: generated column (table rewrite)", exec(`ALTER TABLE lab_docs ADD COLUMN sv tsvector GENERATED ALWAYS AS (
setweight(to_tsvector('english', title), 'A') || setweight(to_tsvector('english', body), 'C')) STORED`))
timed("build: GIN (tsvector)", exec(`CREATE INDEX lab_docs_sv ON lab_docs USING GIN (sv)`))
must(exec(`ANALYZE lab_docs`)())
run(probe{"FTS 'tokenizer' stemmed (all matches)", `SELECT id FROM lab_docs WHERE sv @@ websearch_to_tsquery('english', $1)`, "tokenizer"})
run(probe{"FTS 'inverted index' ranked top 20", `SELECT id FROM lab_docs WHERE sv @@ websearch_to_tsquery('english', $1) ORDER BY ts_rank(sv, websearch_to_tsquery('english', $1)) DESC LIMIT 20`, "inverted index"})
run(probe{"FTS typo 'invertd indx' (no match)", `SELECT id FROM lab_docs WHERE sv @@ websearch_to_tsquery('english', $1)`, "invertd indx"})
fmt.Println("\n-- 3. pg_trgm: GIN gin_trgm_ops on title")
timed("build: GIN (gin_trgm_ops)", exec(`CREATE INDEX lab_docs_trgm ON lab_docs USING GIN (title gin_trgm_ops)`))
must(exec(`ANALYZE lab_docs`)())
run(probe{"trigram % 'invertd indx' on title", `SELECT id FROM lab_docs WHERE title % $1 ORDER BY similarity(title, $1) DESC LIMIT 20`, "invertd indx"})
run(probe{"ILIKE '%ndexi%' on title (trgm GIN)", `SELECT id FROM lab_docs WHERE title ILIKE '%' || $1 || '%'`, "ndexi"})
var size string
must(conn.QueryRow(ctx, `SELECT pg_size_pretty(pg_table_size('lab_docs')) || ' table, ' ||
pg_size_pretty(pg_relation_size('lab_docs_sv')) || ' GIN fts, ' ||
pg_size_pretty(pg_relation_size('lab_docs_trgm')) || ' GIN trgm (title only)'`).Scan(&size))
fmt.Println("sizes:", size)
fmt.Println("\n-- 4. Meilisearch")
_, _ = meili("DELETE", *host+"/indexes/lab_docs", *key, nil)
timed("build: index documents (async task)", func() error {
for i := 0; i < len(docs); i += 20000 {
end := min(i+20000, len(docs))
m, err := meili("POST", *host+"/indexes/lab_docs/documents?primaryKey=id", *key, docs[i:end])
if err != nil {
return err
}
if err := waitTask(*host, *key, m); err != nil {
return err
}
}
return nil
})
for _, q := range []string{"tokenizer", "inverted index", "invertd indx"} {
ms, hits := median(func() (int, error) {
m, err := meili("POST", *host+"/indexes/lab_docs/search", *key,
map[string]any{"q": q, "limit": 20})
if err != nil {
return 0, err
}
h, _ := m["hits"].([]any)
return len(h), nil
})
fmt.Printf("%-44s %8.2f ms hits=%d\n", "Meilisearch '"+q+"'", ms, hits)
}
}1. Start the engines.
docker run -d --name fts-pg -e POSTGRES_PASSWORD=pw -p 55440:5432 postgres:17
docker run -d --name fts-meili -p 7700:7700 -e MEILI_MASTER_KEY=masterKey -e MEILI_ENV=development getmeili/meilisearch:v1.122. Run the comparison from docs/snippets/database/full-text-search/go:
go run ./lab -n 100000 -dsn postgres://postgres:pw@localhost:55440/postgres -meili http://localhost:7700 -key masterKey3. Read the output. Measured on an Apple-silicon laptop with the containers in Docker, PostgreSQL 17.12 (pgvector/pgvector:pg17 image, which is plain PostgreSQL 17 plus an extension), Meilisearch v1.12, one run, median of 20 timed executions after 5 warm-ups. Your numbers will differ; the shape should not.
load: COPY into PostgreSQL 258.2 ms
-- 1. baseline: no text index, ILIKE scans the heap
ILIKE '%tokenizer%' on body (all matches) 429.93 ms hits=66386
ILIKE '%ndexi%' on title (all matches) 109.30 ms hits=20957
-- 2. PostgreSQL FTS: generated tsvector + GIN
build: generated column (table rewrite) 4245.5 ms
build: GIN (tsvector) 453.5 ms
FTS 'tokenizer' stemmed (all matches) 25.83 ms hits=94423
FTS 'inverted index' ranked top 20 17.44 ms hits=20
FTS typo 'invertd indx' (no match) 0.34 ms hits=0
-- 3. pg_trgm: GIN gin_trgm_ops on title
build: GIN (gin_trgm_ops) 830.1 ms
trigram % 'invertd indx' on title 16.08 ms hits=7
ILIKE '%ndexi%' on title (trgm GIN) 24.36 ms hits=20957
sizes: 78 MB table, 7432 kB GIN fts, 9184 kB GIN trgm (title only)
-- 4. Meilisearch
build: index documents (async task) 11411.3 ms
Meilisearch 'tokenizer' 1.30 ms hits=20
Meilisearch 'inverted index' 1.36 ms hits=20
Meilisearch 'invertd indx' 0.93 ms hits=20| Question | What the numbers show |
|---|---|
| ILIKE on body versus FTS | 430 ms (sequential scan, 66,386 rows) versus 26 ms (GIN, 94,423 rows). FTS returns more rows because the Snowball stemmer turns tokenizer into token, so tokens and tokenizing match too |
| Cost of ranking | The ranked inverted index query took 17 ms for 20 rows, because ts_rank had to score every one of the 5,067 matches before the top-N sort |
Typo invertd indx | FTS: 0 rows. Trigram on title: 7 rows in 16 ms. Meilisearch: 20 rows in under 1 ms |
Substring %ndexi% | 109 ms sequential scan before, 24 ms with the trigram GIN after (same 20,957 rows) |
| Build cost | Generated column 4.2 s (table rewrite), FTS GIN 0.45 s, trigram GIN 0.83 s, Meilisearch ingestion 11.4 s (asynchronous). Indexes: 7.4 MB for FTS, 9.2 MB for trigram on titles only, on a 78 MB table |
| Fairness | The PostgreSQL FTS rows are all matches (a count), Meilisearch returns the top 20 and an estimate. One client, no concurrency, warm caches: this is a shape comparison, not a benchmark |
4. Persian check (any PostgreSQL; the function and table are in Persian search):
SELECT to_tsvector('simple', 'میشود'), to_tsvector('simple', 'می شود');
-- 'میشود':1 'شود':2 'می':1 <- different terms until you normalize
SELECT id FROM fa_docs WHERE search_vector @@ websearch_to_tsquery('simple', fa_normalize('می شود كتاب'));
-- 15. MySQL ngram and SQLite FTS5, with the statements from MySQL FULLTEXT and SQLite FTS5: the default parser returns nothing for 京都 inside 东京都 and the ngram parser returns the row; FTS5 bm25() prints a negative number and orders ascending.
6. Break it on purpose. Run SELECT to_tsquery('english', 'fat &') (no operand in tsquery) and compare with websearch_to_tsquery('english', 'fat &') (no error); raise pg_trgm.similarity_threshold to 0.8 and watch the typo query lose its rows; stop the relay and watch the index drift while the database stays correct.
Clean up with docker rm -f fts-pg fts-meili.
Common misconceptions
| Belief | Reality |
|---|---|
"A B-tree index on the column makes LIKE '%x%' fast" | It cannot seek on a leading wildcard; only trigram (pg_trgm, pg_bigm) or ngram indexes can (109 ms to 24 ms in the lab) |
| "Full-text search is typo tolerant" | FTS matches normalized words; invertd indx matched 0 rows. Use trigram or an engine with fuzziness |
| "Stemming understands language" | It cuts suffixes by rule: tokenizer becomes token, university becomes univers |
"ts_rank is BM25" | It ranks by lexeme frequency and weights, with no corpus statistics; BM25 needs ParadeDB or an external engine |
| "A higher score is better across queries" | Scores are only comparable inside one query; normalization 32 is cosmetic |
| "Elasticsearch is real-time" | It is near-real-time: visible after a refresh (1 s by default) |
| "Elasticsearch is my database" | It is a derived index; keep the source of truth elsewhere and rebuild from it |
| "Dual write is fine if I wrap it in try/catch" | A crash between the writes, or two concurrent writers, leaves them different with no error |
| "Postgres supports Persian search" | It stores Persian fine; there is no persian configuration, and ZWNJ, ی/ک and diacritics need your own normalization |
| "Add the BM25 and cosine scores" | Different scales; fuse by rank (RRF, k = 60) or normalize |
| "Scout keeps the index in sync" | Only for writes that go through Eloquent; DB::table(), other services and raw SQL bypass the observers |
"ts_headline is free" | It re-parses the text of each row; apply it to the final page of results only |
| "More shards means faster" | Each shard has overhead and local IDF; pick the count from data size, and it cannot be changed later without _split or reindex |
| "SQLite has no real search" | FTS5 has BM25, highlight, snippet, prefix and trigram tokenizers |
Cheat sheet
| Topic | What to remember |
|---|---|
| Inverted index | Term to sorted postings; query = lookups and merge; text stored elsewhere |
| PostgreSQL recipe | Generated tsvector with setweight, GIN, websearch_to_tsquery, ts_rank, ts_headline on the top 20 |
| Configuration | Always name it: to_tsvector('english', ...); \dF lists them; none for Persian |
| GIN vs GiST | GIN for reads; GiST lossy; fastupdate and gin_pending_list_limit (4 MB) |
| Limits | tsvector under 1 MB, lexeme under 2 KB, 256 positions, <N> up to 16,384 |
| Ranking | ts_rank weights {0.1, 0.2, 0.4, 1.0} for D, C, B, A; BM25 k1 1.2 and b 0.75 |
| pg_trgm | % threshold 0.3, word_similarity 0.6, GIN for LIKE '%x%', GiST for KNN <-> |
| Typos | Trigram, fuzziness: AUTO (Elasticsearch), default on (Meilisearch: 5 and 9 characters; Typesense: 4 and 7) |
| Persian | ZWNJ U+200C to space, U+064A to U+06CC, U+0643 to U+06A9, strip U+064B to U+065F |
| Elasticsearch | Shards fixed at creation, refresh 1 s, max_result_window 10,000, alias plus reindex for mapping changes |
| Autocomplete | Edge n-grams (index time) with a plain search analyzer, or the completion suggester |
| Hybrid | RRF: sum of 1/(k + rank), k = 60; never add raw scores |
| Sync | Outbox or CDC, idempotent upsert of current state, external version, drift check, alias swap |
| Scout | scout:import, scout:flush, scout:sync-index-settings, queue it, shouldBeSearchable |
| MySQL / SQLite | FULLTEXT min token 3 and stop words; ngram parser for CJK; FTS5 bm25() is negative |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why can a B-tree not speed up LIKE '%word%', and which two index types can? Must-know
Answer
Answer: A B-tree orders whole keys, so it can only seek to a known prefix. pg_trgm and pg_bigm GIN or GiST indexes store character fragments, so any substring with enough characters can be looked up (109 ms to 24 ms in the lab).
2 — What does an inverted index store, and how does quick AND fox use it? Must-know
Answer
Answer: A sorted term dictionary where each term points to postings (document ids, often positions and frequencies). The query reads the posting lists for quick and fox and intersects them; no rows are read until the intersection is known.
3 — Why did to_tsvector('english', 'Café') not match a search for cafe, and what fixes it? Important
Answer
Answer: english_stem does not fold accents, so the lexeme is café. Put the unaccent dictionary before the stemmer in the configuration (ALTER MAPPING ... WITH unaccent, english_stem), and wrap unaccent in an immutable function if it must live in a generated column.
4 — Name the Persian-specific problems a search must handle. Good to know
Answer
Answer: ZWNJ (U+200C) versus a space versus nothing; Arabic ي and ك versus Persian ی and ک; diacritics and tatweel; Persian, Arabic-Indic and ASCII digits; and the plural suffix ها with or without ZWNJ. Normalize on write and on query.
5 — What do BM25's k1 and b control, and what are their Elasticsearch defaults? Good to know
Answer
Answer: k1 (1.2) controls how fast repeated term occurrences saturate; b (0.75) controls how much document length normalizes term frequency.
6 — Why is ts_rank expensive on a broad query, and how do you limit the cost? Important
Answer
Answer: It must read the tsvector of every matching row to compute a rank before the top-N sort (5,067 rows scored to return 20 in the lab). Narrow the candidate set with filters, cap candidates in a subquery, and apply ts_headline only to the final rows.
7 — What does refresh do in Elasticsearch, and what is the default behaviour? Important
Answer
Answer: It writes the in-memory buffer as a new segment and opens it for search. By default every second (only on indices that received a search in the last 30 seconds), so search is near-real-time, not real-time.
8 — Why is a bare dual write unsafe, and what replaces it? Must-know
Answer
Answer: The two writes are not atomic: a crash between them, a retry, or two concurrent writers applying in opposite order leave the index different from the database forever. Use a transactional outbox or CDC with an idempotent upsert of the current row, plus an external version and a drift check.
9 — How does Reciprocal Rank Fusion combine keyword and vector results? Important
Answer
Answer: Each document scores the sum of 1 / (k + rank) over the lists it appears in (k = 60 by default in Elasticsearch). It uses ranks, not raw scores, so BM25 and cosine similarity scales do not matter.
10 — When is Laravel Scout's observer-based sync not enough? Important
Answer
Answer: When anything other than Eloquent writes the table (DB::table(), raw SQL, another service, a migration): the observers never fire. Use an outbox or CDC, or run scout:import on a schedule as a safety net.
11 — Why would you pick Meilisearch over PostgreSQL FTS, and what do you give up? Important
Answer
Answer: You gain typo tolerance, instant search and good defaults with little configuration (0.9 ms for a typo query in the lab versus 0 rows from FTS). You give up transactional consistency with your data: you now need sync, monitoring, and a rebuild path.
Glossary
| Term | Meaning |
|---|---|
| Inverted index | Term-to-documents lookup built at write time |
| Postings (posting list) | Sorted list of documents (and positions) for one term |
| Dictionary / term dictionary | The sorted set of all terms in an index |
| Tokenization | Splitting text into tokens |
| Token | One unit produced by the tokenizer |
| Normalization | Making spellings comparable (case, accents, letter variants) |
| Stop words | Very common words dropped from the index |
| Stemming | Rule-based cutting of word endings (Snowball, Porter) |
| Lemmatization | Mapping a word to its dictionary form using a lexicon |
| Lexeme | A normalized term stored in a PostgreSQL tsvector |
| Analyzer | Elasticsearch chain of char filters, one tokenizer and token filters |
| Char filter | Rewrites raw text before tokenizing (HTML strip, ZWNJ mapping) |
| Token filter | Transforms tokens after tokenizing (lowercase, stem, stop, synonym) |
| N-gram | Contiguous run of n characters |
| Trigram | 3-gram; the unit of pg_trgm |
| Edge n-gram | N-grams anchored at the start of a word, for prefix matching and autocomplete |
tsvector | PostgreSQL type: sorted lexemes with positions and weights |
tsquery | PostgreSQL query type with &, |, !, <-> operators |
| Text search configuration | Parser plus dictionary chains per token type, for example english |
| Dictionary (PostgreSQL) | Component that turns a token into lexemes or drops it (simple, stem, ispell, thesaurus, synonym, unaccent) |
websearch_to_tsquery | Query parser for raw user input; never raises syntax errors |
phraseto_tsquery | Builds a phrase query using <-> |
ts_rank / ts_rank_cd | PostgreSQL ranking by frequency / by cover density (proximity) |
ts_headline | Returns a fragment of the document with matches marked |
setweight | Labels lexemes A to D for ranking |
| Generated column | A column the database computes and stores from other columns |
| GIN | Generalized Inverted Index; preferred for tsvector |
| GiST | Generalized Search Tree; lossy signature index; supports KNN for trigram |
fastupdate | GIN pending-list mechanism that batches inserts |
pg_trgm | Trigram similarity and LIKE-accelerating extension |
pg_bigm | 2-gram extension for LIKE, strong for Japanese |
ParadeDB / pg_search | Postgres extension adding a BM25 index |
| BM25 | Probabilistic ranking function with saturation and length normalization |
| TF-IDF | Term frequency times inverse document frequency |
k1, b | BM25 parameters: saturation and length normalization |
| Lucene | Java search library under Elasticsearch, OpenSearch and Solr |
| Shard | A partition of an Elasticsearch index; each is a Lucene index |
| Segment | Immutable on-disk piece of a Lucene index |
| Refresh | Opening a new segment so recent writes become searchable |
| Merge | Background combining of segments; drops deleted documents |
| Mapping | Field types and analyzers of an Elasticsearch index |
text vs keyword | Analyzed full-text field versus single exact term |
| Aggregation / facet | Counting values of a field inside a result set |
| Alias | A name that points to one or more indices; swapped to cut over a reindex |
| OpenSearch | Fork of Elasticsearch 7.10 with its own plugins |
| Meilisearch | Rust search engine with typo tolerance and ranking rules |
| Typesense | C++ in-memory search engine with typo tolerance |
| Typo tolerance | Matching words within an edit distance |
| Instant search / search-as-you-type | Results update on every keystroke |
| Completion suggester | Elasticsearch FST-based prefix suggester |
| ZWNJ | Zero-width non-joiner, U+200C, used inside Persian words |
| Diacritics (harakat) | Optional vowel marks in Arabic script, U+064B to U+065F |
| RRF | Reciprocal Rank Fusion: sum of 1/(k + rank) across ranked lists |
| Hybrid search | Keyword plus vector retrieval, fused |
| Dual write | Writing database and index separately from the application |
| CDC | Change data capture: reading the database log to publish changes |
| Outbox | Event rows written in the same transaction as the data change |
| MySQL FULLTEXT | InnoDB full-text index used with MATCH ... AGAINST |
| ngram parser | MySQL parser that indexes fixed-size character grams (CJK) |
| SQLite FTS5 | SQLite virtual-table full-text extension with bm25() |
| Laravel Scout | Laravel package with drivers that syncs Eloquent models to a search engine |
whereFullText | Laravel query builder full-text clause |
| go-elasticsearch | Official Elasticsearch client for Go |
| olivere/elastic | Community Elasticsearch client for Go (7.x) |
| meilisearch-go | Official Meilisearch client for Go |
References
- PostgreSQL, 12.1 Introduction, 12.2 Tables and Indexes, 12.3 Controlling Text Search, 12.6 Dictionaries, 12.7 Configuration Example, 12.9 Preferred Index Types, 12.11 Limitations, GIN, pg_trgm
- pg_bigm documentation (comparison with pg_trgm), ParadeDB: How text search works, ParadeDB: Create an index
- Elasticsearch, Text analysis overview, Language analyzers, Similarity module, Near real-time search, Edge n-gram tokenizer, Suggesters, Reciprocal rank fusion
- OpenSearch, Text analysis
- Meilisearch, Typo tolerance settings, Ranking rules; Typesense, Search parameters
- SQLite, FTS5 extension; MySQL InnoDB FULLTEXT and the ngram parser: behaviour verified in the lab on
mysql:8.0.36(the MySQL manual refused automated fetches, so it is not linked as a source) - Stephen Robertson and Hugo Zaragoza, The Probabilistic Relevance Framework: BM25 and Beyond, Foundations and Trends in Information Retrieval, 2009
- Laravel 13: Scout, Query Builder: full text where clauses, Migrations
- Go packages: go-elasticsearch v8, olivere/elastic v7, meilisearch-go
- Related chapters: Indexing, Vector Search & pgvector, SQLite in Depth, Search Systems, Transactional Outbox Pattern, Change Data Capture