Build a tiny search engine from Common Crawl

The code from the documentary I Built a Search Engine From Free Data: two short Python files that read a slice of the free Common Crawl web archive, store it in SQLite with full-text search, and answer searches with no network connection.

Run it

You need Python 3. Python's own SQLite module includes full-text search (FTS5), so there is nothing to install.

python3 build_index.py
python3 search.py artificial intelligence

The first command builds search.db; the second searches it and prints the three best matches with their address, capture date and an extract. Searching needs no internet connection once the database exists.

To keep more pages or use another crawl, pass the crawl id and the number of pages: python3 build_index.py CC-MAIN-2026-47 5000. The list of crawls is on commoncrawl.org.

What it does

  • Downloads the list of WET files (the extracted page text) of one monthly crawl and opens the first file as a stream.
  • Reads the archive records one by one, so it never stores the whole file. It stops as soon as it has the pages it needs.
  • Keeps three things per page: the address, the capture date and the first 5,000 characters of text.
  • Skips duplicate addresses, pages not in English, pages with too little text and adult pages.
  • Stores the pages in an SQLite FTS5 table; search.py ranks matches with BM25 and prints a highlighted extract.

In the film it kept 1,000 pages from the first WET file of the November 2026 crawl after reading 9.8 MB of a 65.9 MB file, in under two seconds. Your numbers depend on your connection and the crawl you pick.

Use it politely and lawfully

Download only what you need, one stream at a time, and read Common Crawl's terms of use. Free access to the archive does not give you rights to the pages' content: copyright, privacy and licensing still apply, which is why we share the code and not the pages it collected.

build_index.py

"""Build a tiny search engine from a small slice of Common Crawl.

Streams one WET file (extracted page text) from Common Crawl's public data, keeps the first
1,000 suitable English pages, and stores them in an SQLite full-text index (FTS5).
Only Python's standard library is used. Nothing is downloaded beyond what is needed:
the stream is closed as soon as 1,000 pages are indexed.

usage: python3 build_index.py [CRAWL_ID] [PAGES]
"""
import gzip
import os
import re
import sqlite3
import sys
import time
import urllib.request
from urllib.parse import urlsplit

CRAWL = sys.argv[1] if len(sys.argv) > 1 else "CC-MAIN-2026-47"   # November 2026
PAGES = int(sys.argv[2]) if len(sys.argv) > 2 else 1000
KEEP = 5000                     # characters of text kept per page
DB = "search.db"
BASE = "https://data.commoncrawl.org/"
UA = {"User-Agent": "ScraperFinderDocBot/1.0 (https://scraperfinder.com; hello@scraperfinder.com)"}


class Metered:
    """Wraps the HTTP response and counts the compressed bytes we actually download."""
    def __init__(self, resp):
        self.resp, self.bytes = resp, 0

    def read(self, n=-1):
        data = self.resp.read(n)
        self.bytes += len(data)
        return data


def fetch(path):
    return urllib.request.urlopen(urllib.request.Request(BASE + path, headers=UA), timeout=60)


def records(stream):
    """Yield (headers, text) for each WARC record in a WET stream."""
    while True:
        line = stream.readline()
        if not line:
            return
        if not line.startswith(b"WARC/"):
            continue
        headers = {}
        while (line := stream.readline()) not in (b"\r\n", b"\n", b""):
            key, _, value = line.decode("utf-8", "replace").partition(":")
            headers[key.strip()] = value.strip()
        body = stream.read(int(headers.get("Content-Length", 0)))
        yield headers, body.decode("utf-8", "replace")


def same_page(url):
    """http://www.example.com/a/ and https://example.com/a are the same page to a reader."""
    u = urlsplit(url)
    host = u.netloc.lower().removeprefix("www.")
    return host + (u.path.rstrip("/") or "/") + ("?" + u.query if u.query else "")


def main():
    # 1. the list of WET files in this crawl (a small text file)
    with fetch(f"crawl-data/{CRAWL}/wet.paths.gz") as r:
        wet_files = gzip.decompress(r.read()).decode().split()
    wet = wet_files[0]
    print(f"{CRAWL}: {len(wet_files):,} WET files. Streaming the first one:")
    print(f"  {wet}")

    if os.path.exists(DB):
        os.remove(DB)
    db = sqlite3.connect(DB)
    db.execute("CREATE VIRTUAL TABLE pages USING fts5(url UNINDEXED, captured UNINDEXED, text)")

    seen, start = set(), time.time()
    skipped = {"duplicate URLs": 0, "not English": 0, "too little text": 0, "adult": 0}
    resp = fetch(wet)
    size = int(resp.headers.get("Content-Length", 0))
    raw = Metered(resp)
    for headers, text in records(gzip.GzipFile(fileobj=raw)):      # 2. read it progressively
        if headers.get("WARC-Type") != "conversion":
            continue                                                 # file header, not a page
        url = headers["WARC-Target-URI"]
        reason = None
        if same_page(url) in seen:
            reason = "duplicate URLs"
        elif not headers.get("WARC-Identified-Content-Language", "").startswith("eng"):
            reason = "not English"
        elif len(text) < 500:
            reason = "too little text"
        elif ADULT.search(url) or len(ADULT.findall(text)) >= 2:
            reason = "adult"
        if reason:
            skipped[reason] += 1
            continue
        seen.add(same_page(url))
        db.execute("INSERT INTO pages VALUES (?, ?, ?)",            # 3. index it
                   (url, headers["WARC-Date"][:10], text[:KEEP]))
        if len(seen) % 100 == 0:
            print(f"  {len(seen):>5,} pages indexed   {raw.bytes / 1e6:6.1f} MB downloaded")
        if len(seen) >= PAGES:
            break                                                    # 4. stop when we have enough
    resp.close()
    db.commit()
    db.execute("VACUUM")
    db.close()

    took = time.time() - start
    print(f"\nDone in {took:.1f} s")
    print(f"  pages indexed : {len(seen):,}")
    print(f"  skipped       : " + ", ".join(f"{n:,} {why}" for why, n in skipped.items()))
    print(f"  downloaded    : {raw.bytes / 1e6:.1f} MB of a {size / 1e6:.1f} MB WET file"
          f" ({raw.bytes / size:.0%})")
    print(f"  database      : {DB}  {os.path.getsize(DB) / 1e6:.1f} MB")


# Adult-content filter (kept at the end of the file so the list stays out of the way).
ADULT = re.compile(r"porn|xxx|nsfw|hentai|milf|onlyfans|camgirl|\bfuck|\bsex ?(video|tube|cam|chat)", re.I)


if __name__ == "__main__":
    main()

search.py

"""Search the tiny Common Crawl index built by build_index.py (works offline).

usage: python3 search.py artificial intelligence
"""
import sqlite3
import sys
import time

BOLD, DIM, HIT, URL, END = "\033[1m", "\033[2m", "\033[1;33m", "\033[36m", "\033[0m"

query = " ".join(sys.argv[1:])
db = sqlite3.connect("search.db")

start = time.perf_counter()
total = db.execute("SELECT count(*) FROM pages WHERE pages MATCH ?", (query,)).fetchone()[0]
rows = db.execute(
    "SELECT url, captured, snippet(pages, 2, ?, ?, ' ... ', 16) FROM pages "
    "WHERE pages MATCH ? ORDER BY bm25(pages) LIMIT 3",
    (HIT, END, query)).fetchall()
ms = (time.perf_counter() - start) * 1000
pages = db.execute("SELECT count(*) FROM pages").fetchone()[0]

print(f"{BOLD}{total} of {pages:,} pages match \"{query}\"{END}  {DIM}({ms:.1f} ms){END}\n")
for n, (url, captured, extract) in enumerate(rows, 1):
    print(f"{BOLD}{n}.{END} {URL}{url}{END}")
    print(f"   {DIM}captured {captured}{END}")
    print("   " + " ".join(extract.split()) + "\n")

MIT licence, copyright 2026 Scraper Finder. Common Crawl is a nonprofit with no connection to Scraper Finder.