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

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(index.search_and(["cat", "dog"]))  # ['doc1']
print(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 and OR 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/

Releasing

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

  1. Merge the change to main.
  2. Tag it: git tag -a vX.Y.Z -m vX.Y.Z && git push origin vX.Y.Z. 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, edit the tag in [tool.uv.sources], run uv lock --upgrade-package <name>, 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
PyOS Operating systems py-os Docs
Pebble Compilers and programming languages pebble-lang Docs
PyDB Relational databases pydb Docs
PyKV Key-value stores pykv Docs
PyDocDB Document databases pydoc-db Docs
PyGraphDB Graph databases pygraphdb Docs
PyTSDB Time-series databases pytsdb Docs
PyVecDB Vector databases pyvecdb Docs
PyColDB Column-family databases pycoldb Docs
PyCrypt Cryptography pycrypt Docs
PyNet Computer networking pynet Docs
PyWeb HTTP web servers pyweb Docs
PyGit Version control pygit Docs
PySearch Search engines pysearch Docs
PyMQ Message queues pymq Docs
PyLLM Language models (the brain) pyllm Docs
PyScheduler Job scheduling pyscheduler Docs
PyStack Full-stack integration pystack Docs

License

MIT -- see LICENSE for details.

Metadata

Release files for fromscratch-pysearch 0.3.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.3.0
File Size Uploaded Provenance
fromscratch_pysearch-0.3.0.tar.gz 82.0 kB With provenance Details

Built distribution (wheel)

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

Total release size: 98.2 kB

Release files / fromscratch_pysearch-0.3.0.tar.gz

Download URL fromscratch_pysearch-0.3.0.tar.gz
Size 82.0 kB
Tags Source
SHA-256 checksum
How to use checksums
42aa61e970c6f2944187c7439cbeb5ea19fdfbde77b5d92373ce253f55d91c86
BLAKE2b-256 checksum
How to use checksums
15d3d9801335a2e6fe33252d8eee524c409f9b01a6909c9abc4895c9bfbaa346
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 26, 2026.

Transparency log

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

Download URL fromscratch_pysearch-0.3.0-py3-none-any.whl
Size 16.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
55d7c13d14c9cb73278147cb41d747263440b3087e5b3d7724b934d1ebd75d60
BLAKE2b-256 checksum
How to use checksums
be47d9544c0061f26a4d486e1412ca4513529dd206312a88284fdd4b57f534c9
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 26, 2026.

Transparency log

Security for fromscratch-pysearch 0.3.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

All 2 files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for fromscratch_pysearch-0.3.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 26, 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.3.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