Full-text search
medium 28 minFull-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
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
1972
Karen Spärck Jones proposes weighing a word by how rare it is. This becomes inverse document frequency.
July 1980
Martin Porter publishes a stemmer: a short list of rules that cuts English words down to a common stem.
1999
Doug Cutting writes Lucene, a search library in Java. It moves to the Apache Software Foundation in 2001.
February 2010
Shay Banon releases Elasticsearch: Lucene as a distributed server with a JSON API.
April 2021
After a licence change at Elastic, AWS names its fork of Elasticsearch and Kibana OpenSearch.
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.
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
| Document | Words |
|---|---|
| Doc 1 | quick, brown, fox |
| Doc 2 | lazy, brown, dog |
| Doc 3 | quick, lazy, cat |
Inverted: word to documents
| Word | Documents |
|---|---|
| brown | 1, 2 |
| cat | 3 |
| dog | 2 |
| fox | 1 |
| lazy | 2, 3 |
| quick | 1, 3 |
"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] } ]}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 parts and their jobs
| Part | Example | What it does |
|---|---|---|
| Character filter | html_strip | Removes HTML tags |
| Character filter | mapping | Replaces characters |
| Character filter | pattern_replace | Replaces by regular expression |
| Tokenizer | standard | Splits at word boundaries by the Unicode rules, not only at spaces |
| Tokenizer | ngram | Makes short character pieces |
| Tokenizer | edge_ngram | Pieces from the start, for prefixes |
| Token filter | lowercase | Fox becomes fox |
| Token filter | stemmer | running becomes run |
| Token filter | synonym | Adds words with the same meaning |
| Token filter | stop | Removes the, a, is |
What a Porter stemmer does
| Words | Stem | Note |
|---|---|---|
| running, runs | run | But ran stays ran: a rule cannot know irregular verbs |
| database, databases | databas | A stem need not be a real word |
| searching, searched | search | searcher stays searcher under the original rules |
| connected, connecting, connection | connect | All three meet |
Searching
What happens in a query
- 1
Parse and analyze
The query quick brown fox becomes the tokens quick, brown and fox.
- 2
Look up
Suppose quick is in 1 and 3, brown is in 1 and 2, fox is in 1 and 9.
- 3
Combine
For all words: the intersection is document 1. For any word: 1, 2, 3 and 9.
- 4
Score and rank
Each match gets a number, and the best few are kept in a small heap.
- 5
Return
The top documents are fetched, with highlighted pieces if asked.
One search over two shards
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
BM25: what engines use today
Why BM25 is better: repetition stops paying
| Times the word occurs | TF-IDF factor | BM25 factor |
|---|---|---|
| 1 | 1 | 1.00 |
| 2 | 2 | 1.38 |
| 5 | 5 | 1.77 |
| 10 | 10 | 1.96 |
| 50 | 50 | 2.15 |
Queries
Kinds of queries
| Query | Idea | Remember |
|---|---|---|
| Match | Analyzed text: quick brown fox | Any word is enough by default; set the operator to and for all |
| Match phrase | Words together and in order | Uses positions |
| Multi-match | Several fields, title boosted with title^2 | The boost doubles the weight of the title |
| Fuzzy | databse finds database | Within an edit distance; AUTO allows 1 edit for 3 to 5 letters and 2 above |
| Bool | must, should, must_not, filter | Filter does not score and can be cached |
| Wildcard | *@example.com | Star is any characters, question mark is one. A leading star is slow |
| Term | Exact value, not analyzed | For keyword fields such as author or status |
| More like this | Documents similar to a given text | Picks the significant words and searches for them |
Which query do I need?
Aggregations: numbers beside the results
| Kind | Examples | Question |
|---|---|---|
| Bucket | terms, range, date_histogram | How many per brand, price range, month? |
| Metric | avg, sum, min, max, cardinality, percentiles | What is the average price? |
| Pipeline | moving_fn, derivative, cumulative_sum | How does the average move? |
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
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
Shards and replicas
Products
Search engines
| Engine | Known for | Good for | Effort |
|---|---|---|---|
| Elasticsearch | Distributed, JSON API, strong aggregations; the Elastic Stack adds Logstash and Kibana | Logs, shop search, security data, application monitoring | High |
| OpenSearch | Fork of Elasticsearch 7.10.2 under Apache 2.0; a managed AWS service exists | The same jobs with that licence | High |
| Apache Solr | Mature, on Lucene; SolrCloud; reads PDF and Word through Apache Tika | Documents and enterprise search | High |
| Meilisearch | Search as you type; its project page aims at under 50 ms; typo tolerance | Simple site search, front ends | Low |
| Typesense | In memory, typo tolerant, an open source alternative to Algolia | Fast product search | Low |
| PostgreSQL | Built-in text search with GIN indexes, which are inverted indexes | Search beside your tables | Lowest |
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.