Menu

Integrations / Cookbook and starters

Long-tail finder

The same question asked twice, with and without the most popular sites, side by side, and the pages only the second search found.

Copy as MarkdownOpen in ChatGPT (opens in a new tab)Open in Claude (opens in a new tab)

AvailablePython 3.9+One file, nothing to installTested 2026-11-19

remove_top_sites leaves out the results of the N most popular sites. This script shows what that does to one query: the left column searches every site, the right one leaves out the top 1,000 (or the number you give), and the list underneath is the pages from sites the first search did not show.

1Get the code

long_tail.py
"""Long-tail finder: the same question with and without the most popular sites, side by side.

    export MILLIONSHORT_API_KEY=ms-YOUR_API_KEY
    python long_tail.py "cast iron skillet restoration" [--remove 1000]

No package to install: Python 3.9 or later. Two searches, 2 credits.
"""
import argparse
import json
import os
import urllib.error
import urllib.request

API = os.environ.get("MILLIONSHORT_BASE_URL", "https://api.millionshort.com").rstrip("/")


def search(query, remove_top_sites):
    body = {"query": query, "num_results": 10, "remove_top_sites": remove_top_sites}
    request = urllib.request.Request(
        f"{API}/v1/search",
        data=json.dumps(body).encode(),
        headers={"Authorization": "Bearer " + os.environ["MILLIONSHORT_API_KEY"], "Content-Type": "application/json"},
    )
    with urllib.request.urlopen(request, timeout=60) as response:
        return json.load(response)["data"]["results"]


def row(result):
    return f"{result['site'][:28]:<28} {result['popularity']['bucket']:<9}"


def main():
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("query")
    parser.add_argument("--remove", type=int, default=1000, help="how many of the most popular sites to leave out (default 1000)")
    args = parser.parse_args()

    try:
        everything = search(args.query, 0)
        long_tail = search(args.query, args.remove)
    except urllib.error.HTTPError as failure:
        raise SystemExit(f"The search failed: HTTP {failure.code} {failure.read().decode(errors='replace')[:300]}")
    print(f"{'All sites':<38} | Without the top {args.remove:,}")
    print("-" * 38 + "-+-" + "-" * 38)
    for n in range(max(len(everything), len(long_tail))):
        left = row(everything[n]) if n < len(everything) else ""
        right = row(long_tail[n]) if n < len(long_tail) else ""
        print(f"{left:<38} | {right}")

    seen = {r["site"] for r in everything}
    new = [r for r in long_tail if r["site"] not in seen]
    print(f"\n{len(new)} of {len(long_tail)} results are on sites that the search of all sites did not show:")
    for r in new:
        print(f"  {r['title'][:70]}\n    {r['url']}")


if __name__ == "__main__":
    main()

2Run it

Shell
export MILLIONSHORT_API_KEY=ms-YOUR_API_KEY
python long_tail.py "fountain pen restoration"
python long_tail.py "sourdough starter" --remove 10000

3What you get

First the two columns: each result's site and its popularity band, from top-100 to top-1m, then long-tail. For "fountain pen restoration", the left column had an encyclopedia in the top 100 and two blog hosts in the top 1,000; the right column was long-tail sites only. Then the list:

Output (the end)
6 of 10 results are on sites that the search of all sites did not show:
  Pens Waterman [Fountain Pen]
    https://www.penparents.org/Waterman/pens-waterman
  Parker Pen renovation ⋆ Parker pen ⋆ Fountain pen. Calligraphy.
    https://pspbuddies.com/parker-pen/parker-pen-renovation.html
  Plunger filler - Vintage Fountain Pen Doctor
    https://vintagependoctor.com/plunger-filler/
  ...

Some queries change little: when no top site ranks for them, both columns are the same.

4Change it

ToChange
Cut deeper--remove 100000
Compare the mainstream viewSearch the second time with only_top_sites in place of remove_top_sites
Look at forums onlyAdd "page_types": ["forums"] to the body (topics and page types)

Costs and limits

Two searches, 1 credit each.

When it fails

What you seeWhyFix
401 AUTH_MISSING_KEY or AUTH_INVALID_KEYThe key is missing or wrongSet MILLIONSHORT_API_KEY; keys start with ms-
400 INVALID_PARAMA field name or value the API does not takeThe message names the field; the search reference lists them all
429 RATE_LIMITED or CAPACITYToo many calls a minute, or no free capacity right nowWait the Retry-After seconds, then retry
429 INSUFFICIENT_CREDITSThe plan's credits are used upStop and add credits; do not retry

This page as Markdown · llms.txt