Sub topic 2
How an inverted index works
This chapter assumes you know basic SQL and what a database index is, such as a B-tree on a column. It builds on the previous chapter's question of when to add search. Here you learn the data structure that makes a search service fast.
The problem an inverted index solves
Suppose a products table has a million rows and a user searches for "red jacket". With a database, the obvious query is:
SELECT id FROM products WHERE name LIKE '%red%' AND name LIKE '%jacket%';The leading % means a B-tree index on name cannot help. The database reads every row and scans each string. The cost grows with the total amount of text.
A B-tree answers "which row has this exact value?" An inverted index answers a different question: "which documents contain this word?" It does the work at write time so that read time is cheap.
A few terms used in this chapter:
- A document is one searchable record, such as a product, an article, or a support ticket.
- A term is one searchable unit, usually a word, produced from the text.
- A posting is a record that a term appears in a particular document.
- A postings list is the list of all postings for one term, usually sorted by document ID.
- The term dictionary is the sorted collection of all distinct terms, each pointing to its postings list.
Forward index versus inverted index
A normal table is a forward index. You look up a document ID and get its contents. An inverted index flips this. You look up a term and get document IDs.
Take three documents:
| ID | Text |
|---|---|
| 1 | Red running shoes |
| 2 | Blue running jacket |
| 3 | Red jacket |
After lowercasing and splitting into words, the inverted index looks like this:
| Term | Postings list |
|---|---|
| blue | 2 |
| jacket | 2, 3 |
| red | 1, 3 |
| running | 1, 2 |
| shoes | 1 |
The terms are sorted alphabetically and the postings are sorted numerically. Both orderings matter, as the sections below show.
A minimal implementation
The following Python builds the index above and answers an AND query by intersecting the postings of each query term.
import re
docs = {
1: "Red running shoes",
2: "Blue running jacket",
3: "Red jacket",
}
def tokenize(text):
return re.findall(r"[a-z0-9]+", text.lower())
index = {}
for doc_id, text in docs.items():
for term in set(tokenize(text)):
index.setdefault(term, set()).add(doc_id)
def search(query):
postings = [index.get(t, set()) for t in tokenize(query)]
return set.intersection(*postings) if postings else set()
print(search("red jacket")) # {3}Walk through search("red jacket"):
- The query is tokenized into
redandjacket. index["red"]is{1, 3}andindex["jacket"]is{2, 3}.- The intersection is
{3}.
Three behaviors are worth noting:
- A term that is not in the index gives an empty set. Because the query is an AND, one unknown term makes the whole result empty.
- An empty query returns an empty set. Without the
if postingsguard,set.intersection(*[])would raise an error. - Using
set(tokenize(text))discards how many times a word appears. This index can say whether a document matches but not how well. Ranking needs term frequency, which a later chapter covers.
Combining postings lists
The query cost depends on the length of the postings lists, not on the total corpus size. Searching for a rare word touches a few postings. The operators work like this:
- AND is an intersection. Only documents in every list match.
- OR is a union. Documents in any list match.
- NOT is a difference. Documents in the first list but not the second match.
Real engines keep postings sorted by document ID so that lists can be combined with a linear merge instead of building hash sets. Here is the AND merge on sorted lists:
def intersect(a, b):
i = j = 0
out = []
while i < len(a) and j < len(b):
if a[i] == b[j]:
out.append(a[i])
i += 1
j += 1
elif a[i] < b[j]:
i += 1
else:
j += 1
return out
print(intersect([1, 3, 5, 9], [3, 4, 9, 12])) # [3, 9]Two pointers walk the lists once, so the cost is proportional to the sum of the list lengths. Sorted storage also compresses well. Engines store the gaps between IDs (1, 3, 5, 9 becomes 1, 2, 2, 4), and small numbers take fewer bits.
When one list is very long and the other is short, a linear merge wastes time. Engines add skip pointers, which let the merge jump ahead in the long list. They also process the shortest list first, so the intermediate result stays small.
Storing positions for phrase queries
A plain postings list cannot tell "running shoes" from "shoes running". To support phrase queries, each posting also stores the positions where the term occurs in the document. The next example stores positions and checks that the phrase terms appear next to each other.
import re
from collections import defaultdict
docs = {
1: "Red running shoes",
2: "Blue running jacket",
3: "Red jacket",
}
def tokenize(text):
return re.findall(r"[a-z0-9]+", text.lower())
positional = defaultdict(lambda: defaultdict(list))
for doc_id, text in docs.items():
for pos, term in enumerate(tokenize(text)):
positional[term][doc_id].append(pos)
def phrase_search(phrase):
terms = tokenize(phrase)
if not terms:
return set()
candidates = set(positional[terms[0]])
for t in terms[1:]:
candidates &= set(positional[t])
matches = set()
for doc_id in candidates:
for start in positional[terms[0]][doc_id]:
if all(start + i in positional[terms[i]][doc_id]
for i in range(len(terms))):
matches.add(doc_id)
break
return matches
print(phrase_search("running shoes")) # {1}
print(phrase_search("shoes running")) # set()The first step narrows to documents that contain all the terms, which is the same AND as before. The second step checks positions. Positions make the index larger, so engines let you turn them off for fields that never need phrase queries.
How real engines store it
Lucene is the library under Elasticsearch, OpenSearch, and Solr. It adds several details on top of the model above.
- Immutable segments. The index is written as a set of segments, and each segment is a small self-contained inverted index. Segments are never edited after they are written.
- Updates and deletes. A delete marks the document as deleted in a side structure, and an update is a delete plus a new write. Space is reclaimed later when a background process merges segments.
- Search across segments. A query runs against every segment and merges the results. Many small segments slow queries, which is one reason merging exists.
- Sorted term dictionary. Terms are stored in sorted order in a compact structure. Sorted order makes prefix queries cheap:
run*becomes a range scan over the dictionary that findsrunning,runner, and so on. - Stored statistics. Each term records its document frequency (how many documents contain it). Each posting records its term frequency (how often it appears in that document). Ranking uses both.
Because segments are immutable, a new document is not searchable the instant you write it. It becomes visible when the engine opens a new segment. The consistency chapter returns to this.
Costs and limits
An inverted index is not free:
- Write cost. One document produces many postings, one per distinct term, so indexing is more expensive than inserting a row.
- Disk and memory. The index often takes 20 to 100 percent of the source text's size, depending on positions and stored fields.
- Leading wildcards.
*shoescannot use the sorted dictionary the wayshoes*can, so it is slow. Engines handle it with extra indexed forms, such as reversed terms. - Common terms. A term in nearly every document has a huge postings list and adds little. Ranking handles this by weighting rare terms higher.
- Exact matching depends on the terms. The index only knows the terms it stored. If "Jackets" and "jacket" produce different terms, a search for one will not find the other. Deciding how text becomes terms is the job of text analysis, the next chapter.
Exercises
Exercise
Given the postings lists red = [1, 3, 7, 9] and jacket = [2, 3, 9, 11], what does the query "red AND jacket" return, and what does "red OR jacket" return?
Show answer
AND returns [3, 9], the documents in both lists. OR returns [1, 2, 3, 7, 9, 11], the union of both lists.
Exercise
A phrase query for "running shoes" must not match a document containing "shoes for running". What extra information does the index need to store, and how is it used?
Show answer
It needs the position of each term occurrence in each document. After finding documents that contain both terms, the engine checks that "shoes" appears at the position right after "running". In "shoes for running", "running" comes after "shoes", so the check fails.
Exercise
Why does a query for a rare word stay fast as the corpus grows from one million to one hundred million documents?
Show answer
The engine reads only the postings list of the query terms. A rare word has a short list no matter how large the corpus is. A scan-based LIKE query has to read every document, so its cost grows with the corpus.