aiml

Lesson 11 of 37Module 5

How BM25 ranks documents

Inspect native SQLite lexical scores

See how matching words and document lengths affect SQLite BM25 ranking. Inspect indexed terms and scores before interpreting a result.

Prerequisites

Document ingestion and corpus maintenance modules; the published vector retrieval course.

By the end, you can

  • Run native SQLite FTS5 BM25 queries over the versioned corpus.
  • Inspect indexed terms, term frequency and document length behind a score.
  • Refuse unsupported query syntax without treating a match as an answer check.
Runtime
Python 3.12+ with sqlite3 and SQLite FTS5 enabled
Dependencies
Python standard library sqlite3 and linked SQLite FTS5; no model or third-party packages

Lab code, tests and fixtures (ZIP, 851 KB)Quiz check your understanding

Progress is saved in this browser.

When a question names an API or a specific term, matching the words in the documents is a useful retrieval baseline. Lexical retrieval searches indexed terms. BM25 ranks those matches using term frequency, document length and the terms’ occurrence across the index.

The index’s tokenizer decides what counts as a term. A method name does not always stay one term: the tokenizer can split it at punctuation. Check the indexed vocabulary before you interpret a score.

When you need this. Use it when exact API words should retrieve matching passages and you need to explain why one lexical match ranks ahead of another.

Follow one example. Search the supplied Python summaries for text. Inspect which passages contain that term, their indexed lengths and SQLite’s native BM25 scores. Passages about reading and about writing both match the word. The ranking selects candidates; it does not tell you which operation the developer needs. In this SQLite interface, lower native BM25 values rank first.

You will ask SQLite FTS5 to score the versioned chunks and inspect the counts behind its ordering. The lab uses the existing local corpus and no model.

Find text through matching words

Literal querytermSupported querysyntaxFTS5 text indexTerm counts andlengthsBM25 rankingNative SQLitescoresMatching chunksSorted by score,then IDInvalid queryValueErrorLiteral querytermSupported querysyntaxFTS5 text indexTerm counts andlengthsBM25 rankingNative SQLitescoresMatching chunksSorted by score,then IDInvalid queryValueError
SQLite FTS5 supplies the real term statistics. Lower native BM25 scores sort first in this adapter. These scores are not answer confidence. Dashed arrows show conditional paths.
  1. Use the supported literal query.
  2. Read actual FTS5 statistics.
  3. Sort native scores in ascending order.
  4. Refuse unsupported query syntax.

Inspect the words the index actually stores

Lexical retrieval searches indexed terms. The lab loads the snapshot from the corpus-maintenance module into an FTS5 table that uses the unicode61 tokenizer. The source ID, chunk ID, version and URL stay attached as unindexed metadata; only the passage text contributes terms.

An API name is not always one indexed term. SQLite’s vocabulary table shows how the tokenizer handled punctuation and underscores in these summaries: the index stores write and text, not write_text. Check that table before you treat write_text as one lookup key.

The lab’s query parser accepts at most 16 distinct terms of ASCII letters and digits, in at most 256 characters. The lab sets these limits; SQLite FTS5 does not. Spaces and underscores separate terms, so write_text searches for write or text. The adapter quotes each term separately, joins the terms with OR and passes the expression as an SQL parameter. A multiword query matches passages that contain any of its terms; it does not require an exact phrase.

Unsupported query syntax. Punctuation outside that input policy raises ValueError. A reserved word such as OR is searched as a literal term, not treated as a caller-supplied operator. The SQL parameter keeps the query out of the SQL statement, but SQLite still reads the parameter’s value as FTS query syntax. The input policy and the per-term quotes control that second layer.

Read native BM25 scores in the right direction

BM25 ranks lexical matches using term frequency, document length and how many documents contain a term. Each extra occurrence of a term adds less than the one before. A passage longer than the average gets a larger length adjustment, which lowers the term’s contribution. SQLite uses fixed k1 and b settings, which the run record lists. It also applies its documented floor to the inverse document frequency (IDF), the part of the score that favors terms found in fewer documents.

The result carries the native bm25() value. In SQLite, a smaller value sorts earlier. The adapter orders by that score and then by chunk ID to make exact ties stable. Do not reverse this ordering because another library presents BM25 as a positive higher-is-better score.

The driver queries indexed terms such as text, newline and overwritten. Each recorded row shows the match’s term frequency, document length, average length and document frequency. For a single-term query, the adapter also recomputes the score from those values as a diagnostic check; SQLite still produces the returned score and ranking. For a multiword query, SQLite adds the term contributions, and the response omits the single-term diagnostic fields. The saved records below are the original single-term runs.

Read the exact saved scores below. They describe this tokenizer, corpus and query; they are not probabilities of relevance. In the saved run, text and newline appear in so many of the passages that their IDF is the floor value and their native scores are close to zero. overwritten appears in one passage, and its score is much further from zero. When a score is close to zero, check the term’s document frequency before you compare passages.

Preserve explicit empty and no-match results

Empty query. Whitespace input returns empty_query and no results. A valid literal absent from the index returns no_match. Neither state asks a model to invent a passage. Handle the two statuses separately in the caller: empty_query means the input was empty or only whitespace, and no_match means no indexed passage contains any query term.

A lexical match can still miss the intended operation or documentation version. The next lessons add a vector retriever and consistent metadata filters. The existing vector retrieval course still covers embeddings and vector-store internals.

Execute the local retrieval contract

Download the complete lab. It includes the README, fixtures, implementation, tests, dependency information and the saved run record.

bm25.pySource · pythonDownload
"""Native SQLite FTS5 BM25 over a validated local documentation snapshot."""
from collections import Counter
import math
import re
import sqlite3
from version_documents import validate_snapshot

class LexicalIndex:
    def __init__(self, snapshot):
        validate_snapshot(snapshot)
        self.connection = sqlite3.connect(':memory:')
        self.connection.row_factory = sqlite3.Row
        try:
            self.connection.execute("CREATE VIRTUAL TABLE passages USING fts5(text,chunk_id UNINDEXED,source_id UNINDEXED,version UNINDEXED,url UNINDEXED, tokenize='unicode61')")
            for document in snapshot['documents']:
                for chunk in document['chunks']:
                    self.connection.execute('INSERT INTO passages(text,chunk_id,source_id,version,url) VALUES(?,?,?,?,?)', (chunk['text'],chunk['chunk_id'],document['source_id'],document['version'],document['url']))
            self.connection.execute("CREATE VIRTUAL TABLE vocabulary USING fts5vocab(passages,'instance')")
            self.connection.execute("CREATE VIRTUAL TABLE terms USING fts5vocab(passages,'row')")
        except sqlite3.OperationalError:
            self.connection.close()
            raise
        self.snapshot_id=snapshot['snapshot_id']
    def close(self):
        self.connection.close()
    def indexed_terms(self):
        return [dict(row) for row in self.connection.execute('SELECT term,doc AS document_frequency,cnt AS occurrences FROM terms ORDER BY term')]
    def search(self, query, limit=10):
        if not isinstance(query,str) or not isinstance(limit,int) or isinstance(limit,bool) or not 1<=limit<=100:
            raise ValueError('invalid_query')
        query=query.strip().lower()
        if not query:
            return {'query':query,'status':'empty_query','results':[]}
        # Bounded literal words; spaces and underscores separate terms, never operators.
        if len(query)>256 or not re.fullmatch(r'[a-z0-9_ ]+',query):
            raise ValueError('invalid_query')
        tokens=list(dict.fromkeys(re.findall(r'[a-z0-9]+',query)))
        if not tokens or len(tokens)>16 or any(len(term)>64 for term in tokens):
            raise ValueError('invalid_query')
        if len(tokens)>1:
            return self._search_terms(query,tokens,limit)
        query=tokens[0]
        lengths={row['rowid']:0 for row in self.connection.execute('SELECT rowid FROM passages')}
        frequencies=Counter()
        for row in self.connection.execute('SELECT term,doc FROM vocabulary'):
            lengths[row['doc']]+=1
            if row['term']==query:frequencies[row['doc']]+=1
        count=len(lengths);average=sum(lengths.values())/count if count else 0
        df=len(frequencies)
        idf=max(math.log((count-df+0.5)/(df+0.5)),1e-6) if count else 0
        rows=self.connection.execute('SELECT rowid,text,chunk_id,source_id,version,url,bm25(passages) AS native_score FROM passages WHERE passages MATCH ? ORDER BY native_score ASC,chunk_id ASC LIMIT ?',('"'+query+'"',limit)).fetchall()
        results=[]
        for row in rows:
            tf=frequencies[row['rowid']];length=lengths[row['rowid']]
            length_factor=1-0.75+0.75*length/average
            saturation=tf*(1.2+1)/(tf+1.2*length_factor)
            results.append({key:row[key] for key in ('chunk_id','source_id','version','url','text','native_score')} | {'term_frequency':tf,'document_length':length,'average_document_length':average,'document_frequency':df,'idf':idf,'length_factor':length_factor,'saturation':saturation,'explained_score':-idf*saturation})
        return {'query':query,'status':'ok' if results else 'no_match','results':results}

    def _search_terms(self, query, tokens, limit):
        expression=' OR '.join('"'+term+'"' for term in tokens)
        rows=self.connection.execute(
            'SELECT text,chunk_id,source_id,version,url,bm25(passages) AS native_score FROM passages WHERE passages MATCH ? ORDER BY native_score ASC,chunk_id ASC LIMIT ?',
            (expression,limit)).fetchall()
        # Single-term diagnostic fields are intentionally absent for a multi-term score.
        return {'query':query,'status':'ok' if rows else 'no_match','results':[dict(row) for row in rows]}
Run the local labTerminal · bash
python3 run.py --output /tmp/bm25-result.json
python3 -m unittest -v test_bm25.py
Saved CLI outputRecorded output · jsonDownload
{
  "execution_mode": "offline-native-sqlite-fts5",
  "queries": [
    {
      "native_scores": [
        -0.0000014220532319391636,
        -0.000001409990574929312,
        -0.000001320388349514563
      ],
      "order": [
        "path-read",
        "path-read-3-13",
        "path-write"
      ],
      "query": "text",
      "status": "ok"
    },
    {
      "native_scores": [
        -0.000001409990574929312,
        -9.432534678436318e-7
      ],
      "order": [
        "path-read-3-13",
        "path-write"
      ],
      "query": "newline",
      "status": "ok"
    },
    {
      "native_scores": [
        -0.7992166451067193
      ],
      "order": [
        "path-write"
      ],
      "query": "overwritten",
      "status": "ok"
    },
    {
      "native_scores": [],
      "order": [],
      "query": "xyznotindexed",
      "status": "no_match"
    },
    {
      "native_scores": [],
      "order": [],
      "query": "",
      "status": "empty_query"
    }
  ],
  "rejected": 4
}
Inspect the complete saved result
Actual local retrieval recordRecorded output · jsonDownload
{
  "execution_mode": "offline-native-sqlite-fts5",
  "sqlite_version": "3.53.4",
  "snapshot_id": "0615d22a3315e97c0a88c6c566c546877304f5a28a97e83f68dd36881d4bbd0e",
  "tokenizer": "unicode61",
  "bm25": {
    "k1": 1.2,
    "b": 0.75,
    "ordering": "native_score ASC, chunk_id ASC",
    "scope": "single term, one indexed text column, no column weights"
  },
  "indexed_terms": [
    {
      "term": "13",
      "document_frequency": 1,
      "occurrences": 2
    },
    {
      "term": "3",
      "document_frequency": 1,
      "occurrences": 2
    },
    {
      "term": "8",
      "document_frequency": 2,
      "occurrences": 4
    },
    {
      "term": "a",
      "document_frequency": 3,
      "occurrences": 7
    },
    {
      "term": "accepts",
      "document_frequency": 1,
      "occurrences": 1
    },
    {
      "term": "added",
      "document_frequency": 1,
      "occurrences": 1
    },
    {
      "term": "an",
      "document_frequency": 1,
      "occurrences": 1
    },
    {
      "term": "and",
      "document_frequency": 3,
      "occurrences": 4
    },
    {
      "term": "as",
      "document_frequency": 1,
      "occurrences": 1
    },
    {
      "term": "ascii",
      "document_frequency": 1,
      "occurrences": 3
    },
    {
      "term": "by",
      "document_frequency": 1,
      "occurrences": 1
    },
    {
      "term": "characters",
      "document_frequency": 2,
      "occurrences": 2
    },
    {
      "term": "closes",
      "document_frequency": 3,
      "occurrences": 3
    },
    {
      "term": "data",
      "document_frequency": 1,
      "occurrences": 1
    },
    {
      "term": "decoded",
      "document_frequency": 1,
      "occurrences": 1
    },
    {
      "term": "does",
      "document_frequency": 1,
      "occurrences": 1
    },
    {
      "term": "dumps",
      "document_frequency": 1,
      "occurrences": 1
    },
    {
      "term": "encoding",
      "document_frequency": 4,
      "occurrences": 6
    },
    {
      "term": "ensure",
      "document_frequency": 1,
      "occurrences": 2
    },
    {
      "term": "errors",
      "document_frequency": 3,
      "occurrences": 3
    },
    {
      "term": "existing",
      "document_frequency": 1,
      "occurrences": 1
    },
    {
      "term": "false",
      "document_frequency": 1,
      "occurrences": 1
    },
    {
      "term": "file",
      "document_frequency": 4,
      "occurrences": 9
    },
    {
      "term": "in",
      "document_frequency": 2,
      "occurrences": 3
    },
    {
      "term": "is",
      "document_frequency": 1,
      "occurrences": 1
    },
    {
      "term": "it",
      "document_frequency": 2,
      "occurrences": 2
    },
    {
      "term": "its",
      "document_frequency": 1,
      "occurrences": 1
    },
    {
      "term": "json",
      "document_frequency": 1,
      "occurrences": 2
    },
    {
      "term": "leaves",
      "document_frequency": 1,
      "occurrences": 1
    },
    {
      "term": "method",
      "document_frequency": 2,
      "occurrences": 2
    },
    {
      "term": "newline",
      "document_frequency": 2,
      "occurrences": 3
    },
    {
      "term": "non",
      "document_frequency": 1,
      "occurrences": 1
    },
    {
      "term": "none",
      "document_frequency": 2,
      "occurrences": 5
    },
    {
      "term": "not",
      "document_frequency": 1,
      "occurrences": 1
    },
    {
      "term": "number",
      "document_frequency": 1,
      "occurrences": 1
    },
    {
      "term": "obj",
      "document_frequency": 1,
      "occurrences": 1
    },
    {
      "term": "of",
      "document_frequency": 1,
      "occurrences": 1
    },
    {
      "term": "opens",
      "document_frequency": 1,
      "occurrences": 1
    },
    {
      "term": "or",
      "document_frequency": 1,
      "occurrences": 1
    },
    {
      "term": "overwritten",
      "document_frequency": 1,
      "occurrences": 1
    },
    {
      "term": "parameter",
      "document_frequency": 1,
      "occurrences": 1
    },
    {
      "term": "path",
      "document_frequency": 3,
      "occurrences": 3
    },
    {
      "term": "python",
      "document_frequency": 1,
      "occurrences": 2
    },
    {
      "term": "read",
      "document_frequency": 2,
      "occurrences": 2
    },
    {
      "term": "reading",
      "document_frequency": 1,
      "occurrences": 1
    },
    {
      "term": "returns",
      "document_frequency": 4,
      "occurrences": 4
    },
    {
      "term": "select",
      "document_frequency": 2,
      "occurrences": 2
    },
    {
      "term": "set",
      "document_frequency": 2,
      "occurrences": 2
    },
    {
      "term": "setting",
      "document_frequency": 1,
      "occurrences": 1
    },
    {
      "term": "string",
      "document_frequency": 2,
      "occurrences": 3
    },
    {
      "term": "text",
      "document_frequency": 3,
      "occurrences": 6
    },
    {
      "term": "that",
      "document_frequency": 1,
      "occurrences": 1
    },
    {
      "term": "the",
      "document_frequency": 4,
      "occurrences": 7
    },
    {
      "term": "to",
      "document_frequency": 1,
      "occurrences": 2
    },
    {
      "term": "true",
      "document_frequency": 1,
      "occurrences": 1
    },
    {
      "term": "used",
      "document_frequency": 1,
      "occurrences": 1
    },
    {
      "term": "utf",
      "document_frequency": 2,
      "occurrences": 4
    },
    {
      "term": "was",
      "document_frequency": 1,
      "occurrences": 1
    },
    {
      "term": "when",
      "document_frequency": 1,
      "occurrences": 1
    },
    {
      "term": "write",
      "document_frequency": 2,
      "occurrences": 2
    },
    {
      "term": "writer",
      "document_frequency": 1,
      "occurrences": 1
    },
    {
      "term": "writes",
      "document_frequency": 1,
      "occurrences": 1
    },
    {
      "term": "written",
      "document_frequency": 1,
      "occurrences": 1
    }
  ],
  "queries": [
    {
      "query": "text",
      "status": "ok",
      "results": [
        {
          "chunk_id": "c737db948e8111ae00e3442d8a22c80c876e43446dc1ee176ffe8ce142a41900",
          "source_id": "path-read",
          "version": "3.12",
          "url": "https://docs.python.org/3.12/library/pathlib.html#pathlib.Path.read_text",
          "text": "Path.read_text(encoding=None, errors=None) opens a file, returns its text as a string and closes the file. Set encoding=\"utf-8\" when reading a UTF-8 file.",
          "native_score": -1.4220532319391636e-06,
          "term_frequency": 2,
          "document_length": 30,
          "average_document_length": 34.0,
          "document_frequency": 3,
          "idf": 1e-06,
          "length_factor": 0.9117647058823529,
          "saturation": 1.4220532319391637,
          "explained_score": -1.4220532319391636e-06
        },
        {
          "chunk_id": "bdaeff5ae3ab88b70b12b9b6d4a0a46de45ea14520b971a7756cb03bbd384f35",
          "source_id": "path-read-3-13",
          "version": "3.13",
          "url": "https://docs.python.org/3.13/library/pathlib.html#pathlib.Path.read_text",
          "text": "In Python 3.13, Path.read_text accepts encoding, errors and newline. The newline parameter was added in Python 3.13. The method returns decoded file text and closes the file.",
          "native_score": -1.409990574929312e-06,
          "term_frequency": 2,
          "document_length": 31,
          "average_document_length": 34.0,
          "document_frequency": 3,
          "idf": 1e-06,
          "length_factor": 0.9338235294117647,
          "saturation": 1.409990574929312,
          "explained_score": -1.409990574929312e-06
        },
        {
          "chunk_id": "c66643a4609c6ee157458bf4353f7446b9c6a200a3ef453846d6a18d5b5069a7",
          "source_id": "path-write",
          "version": "3.12",
          "url": "https://docs.python.org/3.12/library/pathlib.html#pathlib.Path.write_text",
          "text": "Path.write_text(data, encoding=None, errors=None, newline=None) writes text to a file and closes it. Set encoding=\"utf-8\" to select UTF-8. An existing file is overwritten. The method returns the number of characters written.",
          "native_score": -1.320388349514563e-06,
          "term_frequency": 2,
          "document_length": 39,
          "average_document_length": 34.0,
          "document_frequency": 3,
          "idf": 1e-06,
          "length_factor": 1.1102941176470589,
          "saturation": 1.3203883495145634,
          "explained_score": -1.3203883495145633e-06
        }
      ]
    },
    {
      "query": "newline",
      "status": "ok",
      "results": [
        {
          "chunk_id": "bdaeff5ae3ab88b70b12b9b6d4a0a46de45ea14520b971a7756cb03bbd384f35",
          "source_id": "path-read-3-13",
          "version": "3.13",
          "url": "https://docs.python.org/3.13/library/pathlib.html#pathlib.Path.read_text",
          "text": "In Python 3.13, Path.read_text accepts encoding, errors and newline. The newline parameter was added in Python 3.13. The method returns decoded file text and closes the file.",
          "native_score": -1.409990574929312e-06,
          "term_frequency": 2,
          "document_length": 31,
          "average_document_length": 34.0,
          "document_frequency": 2,
          "idf": 1e-06,
          "length_factor": 0.9338235294117647,
          "saturation": 1.409990574929312,
          "explained_score": -1.409990574929312e-06
        },
        {
          "chunk_id": "c66643a4609c6ee157458bf4353f7446b9c6a200a3ef453846d6a18d5b5069a7",
          "source_id": "path-write",
          "version": "3.12",
          "url": "https://docs.python.org/3.12/library/pathlib.html#pathlib.Path.write_text",
          "text": "Path.write_text(data, encoding=None, errors=None, newline=None) writes text to a file and closes it. Set encoding=\"utf-8\" to select UTF-8. An existing file is overwritten. The method returns the number of characters written.",
          "native_score": -9.432534678436318e-07,
          "term_frequency": 1,
          "document_length": 39,
          "average_document_length": 34.0,
          "document_frequency": 2,
          "idf": 1e-06,
          "length_factor": 1.1102941176470589,
          "saturation": 0.943253467843632,
          "explained_score": -9.432534678436319e-07
        }
      ]
    },
    {
      "query": "overwritten",
      "status": "ok",
      "results": [
        {
          "chunk_id": "c66643a4609c6ee157458bf4353f7446b9c6a200a3ef453846d6a18d5b5069a7",
          "source_id": "path-write",
          "version": "3.12",
          "url": "https://docs.python.org/3.12/library/pathlib.html#pathlib.Path.write_text",
          "text": "Path.write_text(data, encoding=None, errors=None, newline=None) writes text to a file and closes it. Set encoding=\"utf-8\" to select UTF-8. An existing file is overwritten. The method returns the number of characters written.",
          "native_score": -0.7992166451067193,
          "term_frequency": 1,
          "document_length": 39,
          "average_document_length": 34.0,
          "document_frequency": 1,
          "idf": 0.8472978603872037,
          "length_factor": 1.1102941176470589,
          "saturation": 0.943253467843632,
          "explained_score": -0.7992166451067194
        }
      ]
    },
    {
      "query": "xyznotindexed",
      "status": "no_match",
      "results": []
    },
    {
      "query": "",
      "status": "empty_query",
      "results": []
    }
  ],
  "rejected_queries": [
    {
      "query": "text OR newline",
      "error": "invalid_query"
    },
    {
      "query": "text*",
      "error": "invalid_query"
    },
    {
      "query": "\"",
      "error": "invalid_query"
    },
    {
      "query": "x; DROP TABLE passages;",
      "error": "invalid_query"
    }
  ]
}

Compare the recorded behavior

Compare the native results for text and overwritten, then inspect their term frequencies and document frequencies. Try write_text through the public query interface: the adapter searches for write or text, rather than treating the API name as one term. Then try unsupported punctuation such as text* and expect a ValueError. Use indexed_terms() to inspect the actual tokenizer output. Finally try whitespace and a valid missing term, and compare their distinct statuses.

SQLite returns two native BM25 scores. Which ordering does this adapter use?

Choose one answer, then check your reasoning.

Read the explanation

Keep each adapter's input, filtering and score contract explicit; a retrieved passage is not an answer-validation result.

What’s next

Continue with Add vector retrieval.

References

Official SQLite FTS5 BM25, FTS query syntax and vocabulary tables were checked on 23 October 2026. The run record names the actual SQLite version. Source summaries retain their original version-specific Python documentation links.

Written by Arjun Prabhulal.

Module 5

Retrieval fundamentals