Indexing in distributed search
medium 28 minHow documents become a searchable index spread over many machines: the analysis chain, posting lists and their compression, segments and merges, and the choice between splitting by document or by term.
Video lesson · Chapter 1 of 5
A word points back to its documents
Theory
Read or listen first. About 2 min.
What it is
Indexing turns documents into a structure that answers one question fast: which documents contain this word? The structure is an inverted index: a dictionary of terms, and for each term a posting list of documents, with counts and positions.
In distributed search the index is too large or too busy for one machine. It is cut into shards, each with its own complete small index, and each shard is copied. New documents go to one shard, become part of a small segment, and are visible to searches shortly after.
Why it exists
Reading every document for every query is hopeless: 200 GB at 1 GB a second takes 200 seconds. Doing that reading once, at write time, moves the cost to a moment when nobody is waiting.
The price is paid in writes and in freshness. One changed word means a new copy of the document in the index, work on every replica, and later a merge. Designing indexing means choosing how much of that price to pay, and when.
A short history
September 2001
Lucene, a Java library for inverted indexes by Doug Cutting, joins the Apache Software Foundation. Many search engines are built on it.
2004
Google publishes MapReduce at OSDI. Building an inverted index is one of the examples in the paper.
8 February 2010
The first version of Elasticsearch is released: Lucene indexes as shards of a cluster, behind a JSON API.
2010
Google publishes Percolator. The web index is now updated in small steps instead of being rebuilt in batches.
Words to know
- Term
- A word as it is stored in the index, after analysis.
- Posting list
- All documents that contain a term, with count and positions.
- Analyzer
- The chain that turns text into terms.
- Segment
- A small, complete index that never changes after it is written.
- Refresh
- Making recent writes visible to searches.
- Merge
- Writing several segments as one, and dropping deleted documents.
- Shard
- One part of a distributed index, itself a complete index.
How it works
Step through the idea, or press Play.
Analyze. Text becomes terms with positions
Understand it
Start here
The drawers of a button shop
A shop sells buttons on numbered cards. Customers do not ask for card 3. They ask for red buttons, or for stars. So the owner puts labels on drawers.
How the answers of both shops are put together is the topic Inside a distributed search system.
The structure
Forward and inverted
Forward: from document to terms
| Document | Terms |
|---|---|
| D1 | search, engine, fast, index |
| D2 | search, query, result |
| D3 | index, document, store |
Inverted: from term to documents
| Term | In how many | Postings (document : count) |
|---|---|---|
| search | 3 | D1:3, D2:1, D5:2 |
| index | 5 | D1:2, D2:4, D3:1, D4:3, D5:1 |
| document | 4 | D1:5, D3:2, D4:1, D5:3 |
| query | 2 | D2:2, D4:1 |
{ "term": "search", "documentFrequency": 3, "postings": [ { "doc": "D1", "tf": 5, "positions": [2, 15, 42, 78, 156] }, { "doc": "D2", "tf": 2, "positions": [8, 34] }, { "doc": "D5", "tf": 1, "positions": [12] } ]}Lookup
Find the term, then walk its list. Work grows with the list.
Compression
Differences instead of ids, in few bytes.
Analysis
The same chain for documents and queries.
Stemming
Forms of one word share one term.
Weights
Frequencies are stored, so scores are cheap.
Shards
The index is split and copied.
Analysis
The chain, word by word
| Step | Result |
|---|---|
| Input | The Quick Brown Fox jumps over 2 lazy Dogs! |
| Lowercase | the quick brown fox jumps over 2 lazy dogs! |
| Tokenize | the, quick, brown, fox, jumps, over, 2, lazy, dogs |
| Stop words | quick, brown, fox, jumps, over, 2, lazy, dogs |
| Stem (Porter) | quick, brown, fox, jump, over, 2, lazi, dog |
Our list: the, a, an, is, are, was, were, be, been, being, have, has, had, do, does, did, will, would, could, should, may, might, must, shall, can, to, of, in, for, on, with. These words are in nearly every document, so they say little about any of them.
From text to posting
Stemming
- Rules cut endings
- Fast, no dictionary
- running becomes run
- connection becomes connect
- studies becomes studi, which is fine as a key
Lemmatization
- A dictionary gives the base form
- Slower, knows the language
- running becomes run
- better becomes good
- studies becomes study
N-grams of new york city
| n | Tokens | Use |
|---|---|---|
| 1 | new, york, city | Normal search |
| 2 | new york, york city | Fast phrases |
| 3 | new york city | Longer phrases |
Size
Posting lists in few bytes
Document ids in a list are sorted. Store the distance to the one before, and the numbers become small. Then store small numbers in few bytes.
Delta encoding
The best case of variable bytes
What an index holds
| Part | For | Skip it if |
|---|---|---|
| Document ids | Finding | never |
| Frequencies | Scoring | you only filter |
| Positions | Phrases | no phrase queries |
| Stored fields | Showing the result | you fetch from the database |
| Column values | Sorting, counting | no sorting or aggregations |
Writing
Segments: write once, merge later
A posting list in the middle of a file cannot grow. So an engine never changes the files. It writes new documents as a new small index, a segment, and a search looks into all segments.
From write to findable
Three words that are easily mixed up
| Word | Does | How often |
|---|---|---|
| Refresh | Makes the buffer searchable as a segment | About every second |
| Flush or commit | Puts segments safely on disk, trims the log | Now and then |
| Merge | Joins segments, drops deleted documents | In the background |
Delete and update. A segment cannot change, so a deleted document is only marked. An update is a mark plus a new document. The space comes back with a merge. Until then the document still counts in the statistics.
Refresh often (real time)
- Visible in seconds
- News, social media, shops
- Many small segments
- More merging, caches thrown away
Index in bulk (batch)
- Visible in minutes or hours
- Analytics, archives
- Few large segments
- Better compression, less work
Near real time is the middle: collect writes for a second, make one segment, let merges tidy up. During a large load, switch refresh off and replicas to zero, load, then switch both on again.
Why one document for each refresh hurts
Distributed
Split by document or by term
From a database change to a shard
| By document | By term | |
|---|---|---|
| Rule | hash of document id, modulo shards | hash of term, modulo shards |
| Example | D1 to S0, D2 to S1, D3 to S0, D4 to S2 | search to S1, index to S0, query to S2 |
| Index one document | One shard | As many shards as its terms touch |
| Search for one word | All shards | One shard |
| Search for three words | All shards, short answers | Up to three shards, long lists cross the network |
| Hot spots | Even | Common words overload a shard |
| If a shard is down | A part of the results is missing | Some words find nothing |
What a three-word search moves by term
Which split?
Every shard twice, never on the same machine
Building
The first build and the stream after it
- 1
Note the position
Write down where the stream of changes is now.
- 2
Build from a snapshot
Map: read documents, emit term and posting. Reduce: gather a term's postings. One output for each shard. This is the classic MapReduce job.
- 3
Replay the changes
Apply everything after the noted position.
- 4
Compare
Count documents and run sample queries against the old index.
- 5
Switch the name
Queries use an alias. Point it to the new index. Keep the old one for a day.
Events can arrive twice or in the wrong order. Use the document id and its version from the database. An older version must not replace a newer one, and the same version twice changes nothing.
Versions keep order
Weights
What the index stores for scoring
The simple form of TF-IDF
Indexing a document twice without removing the old one counts it twice. Then df and N are wrong, and the results too. Updating by id prevents it.
Rules
Do and do not
Do
- Choose an analyzer for each field
- Store positions where phrases are searched
- Compress lists with differences
- Set the refresh interval to the need
- Watch merges and segment counts
- Send documents in bulk
Do not
- Analyze ids as text
- Remove stop words where phrases like "to be or not to be" matter
- Stem names
- Forget the memory limit of the write buffer
- Refresh after every document
- Change analyzers without reindexing
Summary
The whole topic in one minute.
Text is normalised, split, filtered and stemmed into terms. Each term gets a posting list of document, frequency and positions. Lists are stored as small differences in few bytes. New documents go into a buffer, then into immutable segments, which are merged in the background.
Almost every system splits by document: a write goes to one shard and a search to all of them. Splitting by term makes a one-word search cheap and everything else expensive. Choose the refresh interval by how fresh the results must be, because it is paid with many small segments.
- An inverted index maps a term to its documents, with counts and positions.
- The same analysis chain runs on documents and queries.
- Sorted ids become small differences, and small differences take few bytes.
- Segments never change. Deletes are marks, and merges clean up.
- Safe (log) and findable (refresh) are different moments.
- Split by document: one shard for a write, all shards for a search.