AlgoViz

Full-text search

medium 28 min

Full-text search finds documents by the words in them and puts the best ones first.

Video lesson · Chapter 1 of 5

Turn a shelf of books inside out

0:00 / 3:55

The inverted index in 90 seconds

1:30Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

Full-text search answers the question "which documents are about these words?" A full-text search database is built for it: it uses inverted indexes, text analysis and relevance scoring to find matching documents and put them in order.

It differs from an ordinary lookup in two ways. The text is analyzed, so that Foxes and fox can meet. And the answer is ranked: not only yes or no, but how well.

Why it exists

A database index on a text column is sorted by the beginning of the text. It cannot help when the word is somewhere in the middle, so the database reads every row.

People also do not search like programs. They make typing errors, use another form of the word, and expect the best result at the top. Exact matching gives none of this.

A short history

  1. 1972

    Karen Spärck Jones proposes weighing a word by how rare it is. This becomes inverse document frequency.

  2. July 1980

    Martin Porter publishes a stemmer: a short list of rules that cuts English words down to a common stem.

  3. 1999

    Doug Cutting writes Lucene, a search library in Java. It moves to the Apache Software Foundation in 2001.

  4. February 2010

    Shay Banon releases Elasticsearch: Lucene as a distributed server with a JSON API.

  5. April 2021

    After a licence change at Elastic, AWS names its fork of Elasticsearch and Kibana OpenSearch.

  6. 2024

    Elastic adds the AGPLv3 as a licence option for Elasticsearch and Kibana.

Words to know

Token
One searchable unit of text, usually a word after cleaning.
Inverted index
A map from each word to the documents that contain it.
Posting list
The entries of one word: documents, counts and positions.
Analyzer
The chain that turns text into tokens: character filters, a tokenizer, token filters.
Stemming
Cutting a word to a common stem, such as running to run.
TF and IDF
How often a word occurs in this document, and how rare it is overall.
BM25
The scoring formula used by default in Lucene and Elasticsearch.
Segment
An immutable piece of the index on disk. New documents create new segments.

Understand it

Start here

The index at the back of the book

Imagine a nature book of 60 pages. You want to read about foxes. You could turn every page. Or you open the index at the back, find the word fox, and go straight to the pages it names.

Finding foxes in a nature book
Page by pagePage 1 of 60Page 2 of 60

The index is extra work when the book is made, and it saves work for every reader.

The idea

Why LIKE is not enough

Full-text search

  • Looks up the word in a sorted dictionary
  • Work grows with the number of matches, not with all the text
  • Ranks by relevance
  • Can accept typing errors and synonyms

SQL LIKE with a leading wildcard

  • A scan of all rows for each search
  • Work grows with the size of the table
  • No ranking
  • No typing errors, no word forms: the pattern for art also matches party

The query WHERE content LIKE '%database%' has nothing to hold on to, because a B-tree is sorted by the start of the value. Some databases offer special indexes for patterns; the point is that ordinary ones do not help.

  • Fast

    Only the lists of the searched words are read.

  • Relevant

    Results are ordered by how well they match.

  • Analyzed

    Words are split, lowercased, stemmed and given synonyms.

  • Language aware

    Each language has its own rules. German and Japanese are not split like English.

The index

Forward and inverted

A forward index is how we write: document to words. An inverted index is how we search: word to documents.

Forward: document to words

DocumentWords
Doc 1quick, brown, fox
Doc 2lazy, brown, dog
Doc 3quick, lazy, cat

Inverted: word to documents

WordDocuments
brown1, 2
cat3
dog2
fox1
lazy2, 3
quick1, 3
The same three documents, turned around. Words are kept sorted, so a word or a prefix is found quickly.
JSON
"database": {  "docFreq": 3,  "postings": [    { "docId": 1, "freq": 2, "positions": [45, 128] },    { "docId": 5, "freq": 1, "positions": [67] },    { "docId": 9, "freq": 3, "positions": [12, 89, 201] }  ]}
docFreq says how many documents hold the word, for IDF. freq is the count in one document, for TF. positions make phrase search possible.

A lookup is not free. Finding the word takes a few steps, and then its posting list must be read. A word that is in most documents has a very long list.

Analysis

From text to tokens

The analysis pipeline

The text was: The Quick Brown Fox! The tokenizer also drops the exclamation mark.

The parts and their jobs

PartExampleWhat it does
Character filterhtml_stripRemoves HTML tags
Character filtermappingReplaces characters
Character filterpattern_replaceReplaces by regular expression
TokenizerstandardSplits at word boundaries by the Unicode rules, not only at spaces
TokenizerngramMakes short character pieces
Tokenizeredge_ngramPieces from the start, for prefixes
Token filterlowercaseFox becomes fox
Token filterstemmerrunning becomes run
Token filtersynonymAdds words with the same meaning
Token filterstopRemoves the, a, is

What a Porter stemmer does

WordsStemNote
running, runsrunBut ran stays ran: a rule cannot know irregular verbs
database, databasesdatabasA stem need not be a real word
searching, searchedsearchsearcher stays searcher under the original rules
connected, connecting, connectionconnectAll three meet
To join ran with run you need lemmatisation or a synonym, which uses a dictionary.

Searching

What happens in a query

  1. 1

    Parse and analyze

    The query quick brown fox becomes the tokens quick, brown and fox.

  2. 2

    Look up

    Suppose quick is in 1 and 3, brown is in 1 and 2, fox is in 1 and 9.

  3. 3

    Combine

    For all words: the intersection is document 1. For any word: 1, 2, 3 and 9.

  4. 4

    Score and rank

    Each match gets a number, and the best few are kept in a small heap.

  5. 5

    Return

    The top documents are fetched, with highlighted pieces if asked.

One search over two shards

Only the winners are fetched. Here they happened to be on shard A.

Relevance

TF, IDF and BM25

Term frequency asks how often the word occurs in this document. Inverse document frequency asks how rare it is in all documents. A rare word such as elasticsearch says much more than the word the.

Classic TF-IDF

score=TF×ln⁡NnN=1000:;n=10→4.61,n=900→0.11\text{score} = \text{TF} \times \ln\frac{N}{n} \qquad N = 1000:; n = 10 \to 4.61,\quad n = 900 \to 0.11
NN is the number of documents and nn how many contain the word. The rare word weighs about 44 times as much.

BM25: what engines use today

IDF×f (k1+1)f+k1(1−b+b ℓℓˉ),IDF=ln⁡ ⁣(1+N−n+0.5n+0.5)\text{IDF} \times \frac{f\,(k_1 + 1)}{f + k_1\left(1 - b + b\,\frac{\ell}{\bar{\ell}}\right)}, \qquad \text{IDF} = \ln\!\left(1 + \frac{N - n + 0.5}{n + 0.5}\right)
ff is the count in the document, ℓ\ell its length and ℓˉ\bar{\ell} the average length. Common values are k1=1.2k_1 = 1.2 and b=0.75b = 0.75.

Why BM25 is better: repetition stops paying

Times the word occursTF-IDF factorBM25 factor
111.00
221.38
551.77
10101.96
50502.15
For a document of average length. The limit is 2.2, so a page that repeats one word fifty times cannot win by that alone.

Queries

Kinds of queries

QueryIdeaRemember
MatchAnalyzed text: quick brown foxAny word is enough by default; set the operator to and for all
Match phraseWords together and in orderUses positions
Multi-matchSeveral fields, title boosted with title^2The boost doubles the weight of the title
Fuzzydatabse finds databaseWithin an edit distance; AUTO allows 1 edit for 3 to 5 letters and 2 above
Boolmust, should, must_not, filterFilter does not score and can be cached
Wildcard*@example.comStar is any characters, question mark is one. A leading star is slow
TermExact value, not analyzedFor keyword fields such as author or status
More like thisDocuments similar to a given textPicks the significant words and searches for them

Which query do I need?

Aggregations: numbers beside the results

KindExamplesQuestion
Bucketterms, range, date_histogramHow many per brand, price range, month?
Metricavg, sum, min, max, cardinality, percentilesWhat is the average price?
Pipelinemoving_fn, derivative, cumulative_sumHow does the average move?
The older moving_avg was removed in Elasticsearch 8; moving_fn takes its place.

How these look as URL parameters is the subject of search and filtering in APIs.

Architecture

A second copy, kept in step

Database first, index second

Users search through an API. The API sends the search to Elasticsearch, and reads and writes rows in PostgreSQL. Changes in PostgreSQL go through Kafka to an indexer, which updates Elasticsearch.
PostgreSQL is the source of truth. The search engine can be rebuilt from it at any time.

Writing to both stores from the application is tempting and wrong: one write can fail and nobody notices. Send the changes of the database through a queue instead, and let an indexer apply them in order.

From write to findable

Elasticsearch refreshes every second by default, on indices that are being searched. So a new document is findable soon, not at once.

Shards and replicas

A coordinating node sends one query to three shards on two machines. Machine 1 holds primary 0, primary 2 and replica 1. Machine 2 holds primary 1, replica 0 and replica 2.
A shard is a horizontal part of an index. A replica never sits on the same machine as its primary.

Products

Search engines

EngineKnown forGood forEffort
ElasticsearchDistributed, JSON API, strong aggregations; the Elastic Stack adds Logstash and KibanaLogs, shop search, security data, application monitoringHigh
OpenSearchFork of Elasticsearch 7.10.2 under Apache 2.0; a managed AWS service existsThe same jobs with that licenceHigh
Apache SolrMature, on Lucene; SolrCloud; reads PDF and Word through Apache TikaDocuments and enterprise searchHigh
MeilisearchSearch as you type; its project page aims at under 50 ms; typo toleranceSimple site search, front endsLow
TypesenseIn memory, typo tolerant, an open source alternative to AlgoliaFast product searchLow
PostgreSQLBuilt-in text search with GIN indexes, which are inverted indexesSearch beside your tablesLowest
Start with what you have. Move to an engine when you need better ranking, typing errors, facets or more scale.

Use a search engine for

  • Words in long texts
  • Ranked results with typing errors
  • Facets and highlighting
  • Logs you explore

Do not use it for

  • Orders and payments: use OLTP
  • The only copy of your data
  • Reads that must see the last write
  • Simple lookups by id

Summary

The whole topic in one minute.

Full-text search keeps an inverted index: for each word, the list of documents that contain it. Text passes through an analyzer before it is stored, and the query passes through the same one, so that different forms of a word meet.

Matching documents are scored. Rare words count more, repeated words count with less and less effect, and long documents are toned down. A search engine is normally a second copy of the data, fed from the main database, and is a moment behind it.

  • An inverted index maps each word to its documents.
  • Documents and queries go through the same analyzer.
  • BM25 rewards rare words, limits repetition and tones down long documents.
  • The engine is a second copy, a moment behind the database, and can be rebuilt.
  • Filter for yes or no, score for how well.

Sources