Skip to main content

PySearch

An educational full-text search engine built from scratch in Python.

The Librarian Who Read Every Book

Imagine a librarian who has read every single book in the library. When you ask her "Which books mention dinosaurs?", she doesn't need to open a single book. She already knows the answer because she kept notes while reading.

For every word she encountered, she wrote down which book it was in and how many times it appeared. Her notebook is called an inverted index, and it lets her answer your question in the blink of an eye.

But what if ten books mention dinosaurs? Which one should you read first? The librarian uses a clever trick called TF-IDF -- she ranks the books so the ones that talk about dinosaurs the most (and about other things the least) float to the top.

PySearch teaches you how to build this librarian from scratch.

Examples

Adding Documents and Searching

from pysearch.engine import SearchEngine

# Create a search engine and add some documents
engine = SearchEngine()
engine.add("doc1", "Python is a great programming language")
engine.add("doc2", "Java is also a popular language")
engine.add("doc3", "Python and Java are both used for web development")

# Search for a single term -- results ranked by relevance
results = engine.search("python")
for doc_id, score in results:
    print(f"{doc_id}: {score:.4f}")

# Boolean queries
results = engine.search("python AND java")   # documents with both
results = engine.search("python OR java")    # documents with either
results = engine.search("python NOT java")   # python, but never java

Using the Tokenizer Directly

from pysearch.tokenizer import tokenize, simple_stem

tokens = tokenize("The quick brown foxes are running!")
print(tokens)  # ['quick', 'brown', 'fox', 'runn']

print(simple_stem("running"))  # 'runn'
print(simple_stem("played"))   # 'play'
print(simple_stem("quickly"))  # 'quick'

Building an Inverted Index

from pysearch.index import InvertedIndex

index = InvertedIndex()
index.add_document("doc1", "cats and dogs")
index.add_document("doc2", "cats and birds")
index.add_document("doc3", "dogs and birds")

print(index.search("cat"))            # ['doc1', 'doc2']
print(sorted(index.search_and(["cat", "dog"])))  # ['doc1']
print(sorted(index.search_or(["cat", "dog"])))   # ['doc1', 'doc2', 'doc3']

Features

  • Tokenizer -- Split text into searchable words, remove stop words, and apply simple stemming
  • Inverted Index -- Map every word to the documents that contain it for instant lookups
  • TF-IDF Ranking -- Score and rank results so the most relevant documents come first
  • Boolean Queries -- Combine search terms with AND, OR and NOT operators
  • 100% Typed -- Full type annotations with strict Pyright checking

Quick Start

# Install from source
git clone https://github.com/robcox2910/pysearch.git
cd pysearch
uv sync --all-extras

# Run the tests
uv run pytest

# Try it in a Python shell
uv run python -c "
from pysearch.engine import SearchEngine
engine = SearchEngine()
engine.add('doc1', 'hello world')
print(engine.search('hello'))
"

Concepts

Saving an engine to disk and loading it back: Saving Your Index.

Documentation

Full docs (with kid-friendly explanations of every idea): https://robcox2910.github.io/pysearch/

Install

PyPI

pip install fromscratch-pysearch

Or get the whole series at once: pip install fromscratch-pystack.

Releasing

Other projects in the series (PyStack) use a released version of this one from PyPI, not whatever is on main. To publish a change for them:

  1. Merge the change to main.
  2. Release it: gh release create vX.Y.Z --target main --generate-notes (or push a vX.Y.Z tag); the release workflow publishes it to PyPI. A change to the public API bumps the minor version (v0.1.0 → v0.2.0); anything else bumps the patch (v0.1.0 → v0.1.1).
  3. In each project that uses it, raise the fromscratch-pysearch>=X.Y.Z floor in pyproject.toml, run uv lock --upgrade-package fromscratch-pysearch, and open a pull request so CI checks the pair together.

This project is one of a series that builds real systems "from scratch in Python" to teach how they work. See the series home for the full story.

Project What it teaches Repository Docs PyPI
PyOS Operating systems py-os Docs fromscratch-pyos
Pebble Compilers and programming languages pebble-lang Docs fromscratch-pebble
PyDB Relational databases pydb Docs fromscratch-pydb
PyKV Key-value stores pykv Docs fromscratch-pykv
PyDocDB Document databases pydoc-db Docs fromscratch-pydocdb
PyGraphDB Graph databases pygraphdb Docs fromscratch-pygraphdb
PyTSDB Time-series databases pytsdb Docs fromscratch-pytsdb
PyVecDB Vector databases pyvecdb Docs fromscratch-pyvecdb
PyColDB Column-family databases pycoldb Docs fromscratch-pycoldb
PyCrypt Cryptography pycrypt Docs fromscratch-pycrypt
PyNet Computer networking pynet Docs fromscratch-pynet
PyWeb HTTP web servers pyweb Docs fromscratch-pyweb
PyGit Version control pygit Docs fromscratch-pygit
PySearch Search engines pysearch Docs fromscratch-pysearch
PyMQ Message queues pymq Docs fromscratch-pymq
PyLLM Language models (the brain) pyllm Docs fromscratch-pyllm
PyScheduler Job scheduling pyscheduler Docs fromscratch-pyscheduler
PyStack Full-stack integration pystack Docs fromscratch-pystack

License

MIT -- see LICENSE for details.

Metadata

Release files for fromscratch-pysearch 0.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fromscratch-pysearch 0.4.0
File Size Uploaded Provenance Actions
fromscratch_pysearch-0.4.0.tar.gz 83.6 kB With provenance Details for fromscratch_pysearch-0.4.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for fromscratch-pysearch 0.4.0
File Interpreter ABI Platform Actions
fromscratch_pysearch-0.4.0-py3-none-any.whl Python 3 none any Details for fromscratch_pysearch-0.4.0-py3-none-any.whl

Total release size: 100.5 kB

Release files / fromscratch_pysearch-0.4.0.tar.gz

Download URL fromscratch_pysearch-0.4.0.tar.gz
Size 83.6 kB
Tags Source
SHA-256 checksum
How to use checksums
e9fbca39cfba5576f3416b637e300f98abe2f9a8622e440017274daee4b9de2b
BLAKE2b-256 checksum
How to use checksums
fdb973ef506e051c181030daf71ce92adcdfdb47cf8cb88e6d616cac52e6145c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 27, 2026.

Transparency log

Release files / fromscratch_pysearch-0.4.0-py3-none-any.whl

Download URL fromscratch_pysearch-0.4.0-py3-none-any.whl
Size 16.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
09f64754faccfd907ca3ff9b458f74f0bf3db0a080823243140814369dfc6cbd
BLAKE2b-256 checksum
How to use checksums
10fdf91de7e06afe63841cd2ee61d742ffbf629f4e31928f4d4234e7e7b153a8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 27, 2026.

Transparency log

Security for fromscratch-pysearch 0.4.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for fromscratch_pysearch-0.4.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 27, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.4.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page