AlgoViz

Indexing in distributed search

medium 28 min

How 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

0:00 / 4:01

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

  1. September 2001

    Lucene, a Java library for inverted indexes by Doug Cutting, joins the Apache Software Foundation. Many search engines are built on it.

  2. 2004

    Google publishes MapReduce at OSDI. Building an inverted index is one of the examples in the paper.

  3. 8 February 2010

    The first version of Elasticsearch is released: Lucene indexes as shards of a cluster, behind a JSON API.

  4. 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.

Step 1 of 3

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.

From one big box to labelled drawers
1234All buttons

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

DocumentTerms
D1search, engine, fast, index
D2search, query, result
D3index, document, store

Inverted: from term to documents

TermIn how manyPostings (document : count)
search3D1:3, D2:1, D5:2
index5D1:2, D2:4, D3:1, D4:3, D5:1
document4D1:5, D3:2, D4:1, D5:3
query2D2:2, D4:1
A second, larger collection of five documents. The basics of scoring and of queries are in full-text search.
JSON
{  "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] }  ]}
Document frequency: how rare the term is. Term frequency: how often it is in one document. Positions: needed for phrases such as "new york".
  • 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

StepResult
InputThe Quick Brown Fox jumps over 2 lazy Dogs!
Lowercasethe quick brown fox jumps over 2 lazy dogs!
Tokenizethe, quick, brown, fox, jumps, over, 2, lazy, dogs
Stop wordsquick, brown, fox, jumps, over, 2, lazy, dogs
Stem (Porter)quick, brown, fox, jump, over, 2, lazi, dog
Only the is on our list of stop words, so over stays. Lazi is not a word and does not have to be: the query is stemmed the same way.

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

Keep the position of removed words. Then quick brown still has distance 1, and king of spain still has a gap.

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

nTokensUse
1new, york, cityNormal search
2new york, york cityFast phrases
3new york cityLonger phrases
The same idea with letters gives search while typing. Each extra kind of token makes the index larger.

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

[1,5,12,20,35];→;[1,4,7,8,15][1, 5, 12, 20, 35] ;\to; [1, 4, 7, 8, 15]
With variable bytes, a number below 128 takes one byte. Five ids: 5 bytes instead of 20.

The best case of variable bytes

4 bytes1 byte=4×\frac{4 \text{ bytes}}{1 \text{ byte}} = 4\times
It can never beat 4 times against 32-bit numbers, because each number needs at least one byte. Packing blocks with few bits for each number can: Lucene stores blocks of 128 numbers with one common bit width, and the rest as variable ints.

What an index holds

PartForSkip it if
Document idsFindingnever
FrequenciesScoringyou only filter
PositionsPhrasesno phrase queries
Stored fieldsShowing the resultyou fetch from the database
Column valuesSorting, countingno sorting or aggregations
An id such as an order number should be stored whole and not analyzed as text.

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

Safe and findable are two moments. The log makes it safe after a crash, the refresh makes it findable. Copies on other nodes are left out here.

Three words that are easily mixed up

WordDoesHow often
RefreshMakes the buffer searchable as a segmentAbout every second
Flush or commitPuts segments safely on disk, trims the logNow and then
MergeJoins segments, drops deleted documentsIn the background
Elasticsearch refreshes every second by default, but only indices that were searched in the last 30 seconds. The interval can be changed.

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

86,400 s×1 refresh/s=86,400 segments a day on each busy shard, before merging86{,}400 \text{ s} \times 1 \text{ refresh/s} = 86{,}400 \text{ segments a day on each busy shard, before merging}
Merging in tiers writes each document again each time its segment grows tenfold: about log10(86,400), so five times.

Distributed

Split by document or by term

From a database change to a shard

Changes leave the database through Kafka to an indexing worker. The worker analyzes them and a router sends each document to shard 0, shard 1 or shard 2.
The index is a second copy. The database is the truth, and the index can be rebuilt from it.
By documentBy term
Rulehash of document id, modulo shardshash of term, modulo shards
ExampleD1 to S0, D2 to S1, D3 to S0, D4 to S2search to S1, index to S0, query to S2
Index one documentOne shardAs many shards as its terms touch
Search for one wordAll shardsOne shard
Search for three wordsAll shards, short answersUp to three shards, long lists cross the network
Hot spotsEvenCommon words overload a shard
If a shard is downA part of the results is missingSome words find nothing

What a three-word search moves by term

10,000,000 postings×1.5 bytes=15 MB for one list10{,}000{,}000 \text{ postings} \times 1.5 \text{ bytes} = 15 \text{ MB for one list}
Assumed 1.5 bytes for a posting. By document, each shard joins its lists locally and sends ten ids and scores: well under 1 KB. This is why Elasticsearch and Solr split by document.

Which split?

All answers are by document. That is the honest picture. More about splitting in sharding.

Every shard twice, never on the same machine

Three machines. Machine 1 has the primary of shard 0 and a copy of shard 2. Machine 2 has the primary of shard 1 and a copy of shard 0. Machine 3 has the primary of shard 2 and a copy of shard 1.
A write goes to the primary and then to its copies. A search may use either.

Building

The first build and the stream after it

  1. 1

    Note the position

    Write down where the stream of changes is now.

  2. 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. 3

    Replay the changes

    Apply everything after the noted position.

  4. 4

    Compare

    Count documents and run sample queries against the old index.

  5. 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

Failed documents go to a dead-letter queue with the reason, so that one bad document does not stop the rest. See queues.

Weights

What the index stores for scoring

The simple form of TF-IDF

w=log⁡(1+tf)×log⁡Ndfw = \log(1 + tf) \times \log \frac{N}{df}
A term that is in every document gets weight 0. Engines use BM25, and each shard counts df for its own documents only. How that skews results is in the search system.

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.

Sources