Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Concept · 25 min · revision 1

Inverted indexes, analyzers and scoring

Turn text into terms with an analyzer, store them in an inverted index with posting lists and positions, and rank matches with BM25, by building a small index in Python and getting the same scores from OpenSearch.

Contentsand lesson path

What you will learn

  • Explain how an inverted index, analyzers and relevance scoring (TF-IDF, BM25) answer full-text queries.

01. Why it matters

Picture an outdoor shop with two million products and a search box. The first version is often a SQL query such as WHERE title ILIKE '%waterproof%'. It works in a demo, but it has three problems. A pattern that starts with a wildcard cannot use an ordinary B-tree index, so the database reads every row for every search (PostgreSQL can speed this up with a trigram index, at the cost of a large extra index). It matches characters, not words, so %boot% also finds bootcut jeans. And it returns the matches in no useful order.

Search engines answer the same question differently. OpenSearch, Elasticsearch and Apache Solr are all built on the Apache Lucene library, and Lucene rests on three ideas that this lesson builds one at a time:

  • An analyzer turns text into terms: lowercase words, with punctuation and very common words removed and some word endings trimmed.
  • An inverted index maps each term to the list of documents that contain it, like the index at the back of a book.
  • A scoring function, usually BM25, ranks the documents that match.

You will write all three in under 100 lines of Python, then load the same eight products into OpenSearch and get the same scores to four decimal places.

02. A small inverted index in Python

The script indexes eight product titles. Read the analyze function first. It lowercases the text, splits it on anything that is not a letter or a digit, and drops 33 common English stop words such as for and with. Then it trims plural endings with the same rules as Lucene's minimal_english filter. That filter is a stemmer: it reduces related word forms to one stem, so that boots and boot become the same term. Each token keeps its position in the original text. Save the file as bm25_index.py and run it with Python 3.12.

Python 3.12 · bm25_index.py
"""A tiny inverted index with BM25 scoring. Python 3.12, standard library only."""
import math
import re
from collections import defaultdict

DOCS = {
    1: 'Waterproof hiking boots for women',
    2: 'Lightweight trail running shoes',
    3: 'Running shoes with a waterproof membrane and a wide toe box',
    4: 'Hiking socks in merino wool, pack of 3',
    5: 'Rain boots for kids, waterproof rubber',
    6: 'Trail running vest with two water bottles',
    7: 'Waterproof jacket for hiking and running in heavy rain',
    8: 'Round boot laces, 120 cm',
}
STOP = set('a an and are as at be but by for if in into is it no not of on or such '
           'that the their then there these they this to was will with'.split())
K1, B = 1.2, 0.75  # Lucene's defaults


def stem(word: str) -> str:
    """Plural-only stemmer: the rules of Lucene's minimal_english filter."""
    if len(word) < 3 or word[-1] != 's' or word[-2] in 'us':
        return word
    if word[-2] == 'e':
        if len(word) > 3 and word[-3] == 'i' and word[-4] not in 'ae':
            return word[:-3] + 'y'
        if word[-3] in 'iaoe':
            return word
    return word[:-1]


def analyze(text: str) -> list[tuple[int, str]]:
    """Tokenize, lowercase, drop stop words, stem. Keep each token's position."""
    words = re.findall(r'[a-z0-9]+', text.lower())
    return [(pos, stem(w)) for pos, w in enumerate(words) if w not in STOP]


index = defaultdict(dict)  # term -> {doc_id: [positions]}  (the posting list)
length = {}  # doc_id -> number of indexed tokens
for doc_id, text in DOCS.items():
    tokens = analyze(text)
    length[doc_id] = len(tokens)
    for pos, term in tokens:
        index[term].setdefault(doc_id, []).append(pos)
N = len(DOCS)
avgdl = sum(length.values()) / N


def bm25(term: str, doc_id: int) -> float:
    postings = index.get(term, {})
    if doc_id not in postings:
        return 0.0
    n = len(postings)  # document frequency
    idf = math.log(1 + (N - n + 0.5) / (n + 0.5))
    tf = len(postings[doc_id])
    norm = K1 * (1 - B + B * length[doc_id] / avgdl)
    return idf * tf * (K1 + 1) / (tf + norm)


def search(query: str) -> list[tuple[int, float]]:
    terms = [t for _, t in analyze(query)]
    candidates = set().union(*(index.get(t, {}).keys() for t in terms))
    scores = {d: sum(bm25(t, d) for t in terms) for d in candidates}
    return sorted(scores.items(), key=lambda item: (-item[1], item[0]))


def phrase(query: str) -> list[int]:
    """Documents where the query terms appear next to each other, in order."""
    terms = [t for _, t in analyze(query)]
    hits = []
    for doc_id in set.intersection(*(set(index.get(t, {})) for t in terms)):
        starts = index[terms[0]][doc_id]
        if any(all(p + i in index[t][doc_id] for i, t in enumerate(terms))
               for p in starts):
            hits.append(doc_id)
    return sorted(hits)


if __name__ == '__main__':
    print(f'{N} docs, {len(index)} terms, average length {avgdl:.3f} tokens')
    print('doc 5 ->', analyze(DOCS[5]))
    for term in ('waterproof', 'boot', 'running'):
        print(f'postings[{term!r}] = {index[term]}')
    print("query 'waterproof running shoes':")
    for doc_id, score in search('waterproof running shoes'):
        print(f'  doc {doc_id}  {score:.4f}  {DOCS[doc_id]}')
    print("phrase 'running shoes':", phrase('running shoes'))
    print("phrase 'shoes waterproof':", phrase('shoes waterproof'))
    idf = math.log(1 + (N - 2 + 0.5) / (2 + 0.5))  # a term in 2 of the 8 docs
    print('tf  raw tf x idf  bm25 (field of average length)')
    for tf in (1, 2, 5, 20):
        print(f'{tf:>2}  {tf * idf:12.3f}  {idf * tf * (K1 + 1) / (tf + K1):.3f}')
Expected output (python3 bm25_index.py)
8 docs, 30 terms, average length 5.375 tokens
doc 5 -> [(0, 'rain'), (1, 'boot'), (3, 'kid'), (4, 'waterproof'), (5, 'rubber')]
postings['waterproof'] = {1: [0], 3: [4], 5: [4], 7: [0]}
postings['boot'] = {1: [2], 5: [1], 8: [1]}
postings['running'] = {2: [2], 3: [0], 6: [1], 7: [5]}
query 'waterproof running shoes':
  doc 3  2.3737  Running shoes with a waterproof membrane and a wide toe box
  doc 2  2.2048  Lightweight trail running shoes
  doc 7  1.3233  Waterproof jacket for hiking and running in heavy rain
  doc 1  0.7742  Waterproof hiking boots for women
  doc 5  0.7135  Rain boots for kids, waterproof rubber
  doc 6  0.6617  Trail running vest with two water bottles
phrase 'running shoes': [2, 3]
phrase 'shoes waterproof': []
tf  raw tf x idf  bm25 (field of average length)
 1         1.281  1.281
 2         2.562  1.761
 5         6.405  2.273
20        25.619  2.659

Each part of the output shows one idea:

  • Document 5 lost the stop word for but kept a gap at position 2, and boots and kids became boot and kid. A query goes through the same analyze function, which is why a search for boot finds this document.
  • postings['waterproof'] is a posting list: the documents that contain the term, each with the positions where it occurs. Real engines keep document IDs sorted and compressed, and keep the term dictionary in a compact structure, so looking up a term stays cheap as the index grows. The work that grows is reading long posting lists.
  • A query with several words reads one posting list per term. An OR query takes the union of the lists. An AND query takes their intersection, and an engine starts from the shortest list, because every result must appear in it.
  • The positions answer phrase queries. running shoes matches documents 2 and 3, where shoes comes straight after running. shoes waterproof matches nothing: in document 3 the two words are three positions apart, because the removed words with and a still occupy positions. Lucene keeps the same gaps, so a phrase query does not join words that were not next to each other.

03. Ranking the matches with BM25

Six documents contain at least one query term. To order them, BM25 adds up one contribution per query term, and each contribution multiplies two parts.

The first part is the inverse document frequency (IDF), log(1 + (N - n + 0.5) / (n + 0.5)), where N is the number of documents and n the number that contain the term. A term that appears in few documents tells you more about a match than one that appears in most of them. Here shoes occurs in 2 of the 8 documents and waterproof in 4, so a match on shoes is worth more.

The second part is a damped term frequency: tf * (k1 + 1) / (tf + k1 * (1 - b + b * dl / avgdl)). It grows with tf, the number of times the term occurs in the document, but it levels off quickly; k1 (default 1.2) sets how quickly. It also compares the document length dl with the average length avgdl; b (default 0.75) sets how strongly. The same single match counts for more in a short field than in a long one, because a short title that mentions waterproof is more likely to be about it.

Both effects are visible in the output. Document 3 is the only one with all three terms, yet it beats document 2 by only 0.17. It has seven terms against document 2's four, so length normalisation discounts each of its matches. Documents 1 and 5 each contain waterproof once, and the four-term title of document 1 ranks above the five-term title of document 5.

Older systems ranked with TF-IDF: raw term frequency times IDF, often with a separate length factor. The last lines of the output compare the two for a term that appears in 2 of the 8 documents, in a field of average length. Raw tf × idf grows in step with the count, so 20 repeats score 20 times as much as one. BM25 gives 1.761 for two matches and 2.659 for twenty, and it never passes idf × (k1 + 1), about 2.818 here, so repeating a keyword soon stops paying. BM25 is the default in Lucene-based engines today. A score has no unit: compare scores only between the results of one query on one index.

04. The same index in OpenSearch

Now run the same steps in a real engine. Start a single OpenSearch node in Docker; this lesson was run with OpenSearch 2.19.4 and was not tested on the 3.x line. The security plugin is switched off and the port is bound to 127.0.0.1 only. That is acceptable for a local lab and never for a server that other machines can reach. The data lives in memory (--tmpfs), so removing the container removes everything. You need about 2 GB of free memory.

Terminal · start OpenSearch and wait until it answers
docker run -d --name search-os -p 127.0.0.1:9200:9200 \
  -e discovery.type=single-node \
  -e DISABLE_SECURITY_PLUGIN=true -e DISABLE_INSTALL_DEMO_CONFIG=true \
  -e OPENSEARCH_JAVA_OPTS="-Xms512m -Xmx1g" \
  --tmpfs /usr/share/opensearch/data:uid=1000,gid=1000 \
  --tmpfs /usr/share/opensearch/logs:uid=1000,gid=1000 --tmpfs /tmp \
  opensearchproject/opensearch:2.19.4
until curl -s localhost:9200 >/dev/null; do sleep 2; done
curl -s localhost:9200 | grep '"number"'
Expected output
    "number" : "2.19.4",

Save os_compare.py in the same folder as bm25_index.py, because it imports the documents and the Python scores from it. The script asks OpenSearch to analyze one sentence with three analyzers. Then it creates an index whose text field uses an analyzer with the same steps as the Python version, indexes the eight products, runs the same query and prints the score explanation for document 1. It talks to http://localhost:9200 unless you set OS_URL.

Python 3.12 · os_compare.py
"""Same documents and query in OpenSearch. Python 3.12, standard library only."""
import json
import os
import urllib.error
import urllib.request

from bm25_index import DOCS, search

OS = os.environ.get('OS_URL', 'http://localhost:9200')


def call(method: str, path: str, body=None, ndjson: str | None = None):
    data = ndjson.encode() if ndjson else json.dumps(body).encode() if body else None
    req = urllib.request.Request(OS + path, data=data, method=method,
                                 headers={'Content-Type': 'application/json'})
    with urllib.request.urlopen(req) as resp:
        return json.load(resp)


def tokens(spec: dict, text: str) -> list[str]:
    result = call('POST', '/_analyze', {**spec, 'text': text})
    return [t['token'] for t in result['tokens']]


MINIMAL = {'tokenizer': 'standard', 'filter': [
    'lowercase', 'stop', {'type': 'stemmer', 'language': 'minimal_english'}]}
sample = 'Running Shoes for Kids with Wi-Fi Trackers'
print('standard:', tokens({'analyzer': 'standard'}, sample))
print('english: ', tokens({'analyzer': 'english'}, sample))
print('minimal: ', tokens(MINIMAL, sample))

try:
    call('DELETE', '/gear')  # start clean when you run the script again
except urllib.error.HTTPError:
    pass
call('PUT', '/gear', {
    'settings': {
        'number_of_shards': 1, 'number_of_replicas': 0,
        'analysis': {
            'filter': {'plural': {'type': 'stemmer', 'language': 'minimal_english'}},
            'analyzer': {'minimal': {'type': 'custom', 'tokenizer': 'standard',
                                     'filter': ['lowercase', 'stop', 'plural']}}}},
    'mappings': {'properties': {'text': {'type': 'text', 'analyzer': 'minimal'}}},
})
lines = [json.dumps(x) for i, t in DOCS.items()
         for x in ({'index': {'_id': str(i)}}, {'text': t})]
call('POST', '/gear/_bulk?refresh=true', ndjson='\n'.join(lines) + '\n')

query = 'waterproof running shoes'
hits = call('POST', '/gear/_search', {'query': {'match': {'text': query}}})
ours = dict(search(query))
print('doc  opensearch  python')
for hit in hits['hits']['hits']:
    doc_id = int(hit['_id'])
    print(f"  {doc_id}  {hit['_score']:10.4f}  {ours[doc_id]:6.4f}")


def show(node: dict, depth: int = 1) -> None:
    print('  ' * depth + f"{node['value']:.4f} {node['description']}")
    for child in node.get('details', []):
        show(child, depth + 1)


print("why doc 1 scores what it does for 'waterproof':")
show(call('POST', '/gear/_explain/1', {'query': {'match': {'text': 'waterproof'}}})
     ['explanation'])
Expected output (python3 os_compare.py, OpenSearch 2.19.4, one shard)
standard: ['running', 'shoes', 'for', 'kids', 'with', 'wi', 'fi', 'trackers']
english:  ['run', 'shoe', 'kid', 'wi', 'fi', 'tracker']
minimal:  ['running', 'shoes', 'kid', 'wi', 'fi', 'tracker']
doc  opensearch  python
  3      2.3737  2.3737
  2      2.2048  2.2048
  7      1.3233  1.3233
  1      0.7742  0.7742
  5      0.7135  0.7135
  6      0.6617  0.6617
why doc 1 scores what it does for 'waterproof':
  0.7742 weight(text:waterproof in 0) [PerFieldSimilarity], result of:
    0.7742 score(freq=1.0), computed as boost * idf * tf from:
      2.2000 boost
      0.6931 idf, computed as log(1 + (N - n + 0.5) / (n + 0.5)) from:
        4.0000 n, number of documents containing term
        8.0000 N, total number of documents with field
      0.5077 tf, computed as freq / (freq + k1 * (1 - b + b * dl / avgdl)) from:
        1.0000 freq, occurrences of term within document
        1.2000 k1, term saturation parameter
        0.7500 b, length normalization parameter
        4.0000 dl, length of field
        5.3750 avgdl, average length of field

The scores agree to four decimals, and the explanation shows the same two parts with N = 8, n = 4, dl = 4 and avgdl = 5.375. OpenSearch reports the (k1 + 1) factor as a boost of 2.2. One difference stays hidden here: Lucene stores each field length in a single byte, so for long fields dl is approximate and scores can drift slightly from an exact calculation. These titles are short enough to be stored exactly.

The first three lines show why choosing an analyzer is a design decision, not a detail:

  • standard only splits and lowercases. It keeps for and with, and it does not connect kids with kid.
  • english adds the Porter stemmer, which reduces running to run and shoes to shoe. More queries find something, at the risk of joining words with different meanings: it maps both university and universe to univers.
  • minimal only removes plurals, and it even leaves shoes alone, because its rules keep words that end in -oes.
  • All three split Wi-Fi into wi and fi. Model numbers and codes need the same care. Fields that hold exact values, such as an SKU, are usually mapped as keyword fields, which skip analysis and match only the whole value.

Whatever you choose, the analysis that runs at search time must produce the same terms as the analysis that ran at index time, or query terms will not line up with stored terms. Changing an analyzer later means reindexing every document, because terms are produced when a document is written. The next lesson shows how to do that without downtime.

05. Check your understanding

Practice check · 3 questions

Terms, positions and BM25

Three questions on tokenization, length normalisation and positions.

Q1. A product title 'Wi-Fi 6E travel router' is indexed with the standard analyzer, and the query uses the same analyzer. A shopper searches for wifi. What happens?
Q2. Two documents contain 'charger' exactly once. Document A is a 6-term title; document B is a 300-term description in the same field. With BM25 defaults, which ranks higher for the query charger?
Q3. To save space, a team sets `index_options: docs` on a description field, so its posting lists keep only document IDs. Which query on that field now fails with an error?
Practice only: not graded, not saved, not evidence.

06. Apply it

Start the first half of this skill's practice task, an inverted index with BM25 over a public text dataset:

  1. Pick a public corpus of a few thousand short texts, for example the 20 newsgroups posts that scikit-learn can download or the paragraphs of a few public-domain books, and write down its licence or terms of use.
  2. Adapt bm25_index.py to read the files, keep the same analyze function, and add a function that returns the 10 best documents for a query.
  3. Load the same texts into OpenSearch with the analyzer from os_compare.py and compare the top 10 for five queries. Explain every difference you find: analysis, length encoding or ties.
  4. Change one thing, such as the english analyzer instead of minimal, or b = 0, and describe how the ranking moves.

07. Review prompt

Without looking back, explain: the stages of an analyzer and why index-time and search-time analysis must agree; what a posting list stores and how a phrase query uses positions; the two parts of a BM25 term score and what k1 and b control; and why a stop word still leaves a gap in the positions.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check