Skip to main content
TutorialsNovember 30, 2026 ยท 24 min read

Domain filters, location preferences, and time ranges in search APIs

Learn which search API filters are enforced and which are only hints, and test domain, country and time options on the same query.

Domain filters, location preferences, and time ranges in search APIs

A research product has to choose its sources: these sites, that country, the last week. Search API domain filters, location options and time ranges all promise to help. They don't all promise the same thing, and a result that looks filtered may not be.

This tutorial separates what is enforced from what is only a hint. It builds a probe that runs one query with and without each option, checks every result against the rule, and prints a table that marks each filter as enforced or a preference.

Install the package and put your Spidra key in the environment as SPIDRA_API_KEY:

# pip install spidra
import argparse
import json
import os
import re
import sys
import time

from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from pathlib import Path
from types import SimpleNamespace
from urllib.parse import parse_qsl, urlencode, urlsplit
from spidra import (
    Spidra,
    SpidraAuthenticationError,
    SpidraError,
    SpidraJobFailedError,
    SpidraPaymentRequiredError,
    SpidraRateLimitError,
    SpidraServerError,
    SpidraTimeoutError,
    SpidraValidationError,
)

Three controls, three promises

Search has one option for each need, and they differ in how firmly they hold:

Need

Option

What it does

Promise

Only or never these sites

includeDomains, excludeDomains

Keeps or drops results by domain. Use one list or the other, never both. Web, news, images and videos only.

Enforced. Spidra checks results against the filter before returning them.

A country

country

A two-letter code, or global, eu, asia.

A hint. It shapes results, and it isn't verified as a strict filter.

Recent results

timeRange

hour, day, week, month or year.

A bias. It isn't a hard cutoff, and an unsupported window is ignored.

In a verified run, includeDomains: ["reddit.com"] returned five results, all on reddit.com. For country and time range, no one has verified that they filter strictly, so treat them as preferences.

Other APIs draw the same line more explicitly. Google's Custom Search API has cr, which restricts results to a country, and gl, which only boosts results from one. It also has dateRestrict to restrict by age. Spidra offers hints for country and time, so the work of enforcing them falls to you, and this tutorial shows how.

Domain filters: a rule you can check

An enforced filter is a rule, so you can test it. Every result's host should match an included domain, or none should match an excluded one. A subdomain counts as the domain, but a look-alike doesn't:

def ascii_host(host):
    try:
        return host.encode("idna").decode("ascii")
    except UnicodeError:
        return host


def host_of(url):
    """The host of a URL: lowercase, ASCII, without www or a trailing dot. '' if it has none."""
    host = (urlsplit(url.strip()).hostname or "").rstrip(".").lower()
    return ascii_host(host).removeprefix("www.")
def clean_domain(entry):
    """'https://WWW.Reddit.com/r/x', '*.reddit.com' and 'reddit.com.' all mean reddit.com."""
    text = entry.strip().lower()
    host = urlsplit(text).hostname if "://" in text else text.split("/")[0]
    host = (host or "").removeprefix("*.").rstrip(".").removeprefix("www.")
    if not host:
        raise ValueError(f"not a domain: {entry!r}")
    return ascii_host(host)


def matches(host, domain):
    """True for the domain itself and its subdomains: old.reddit.com matches reddit.com."""
    return host == domain or host.endswith("." + domain)
def violation(host, include, exclude):
    if include and not any(matches(host, d) for d in include):
        return "not on an included domain"
    if any(matches(host, d) for d in exclude):
        return "on an excluded domain"
    return ""
def check_domains(urls, include=(), exclude=()):
    """Every URL against the rule. The API takes one list or the other, so both is an error."""
    if include and exclude:
        raise ValueError("use include or exclude, not both")
    inc, exc = [clean_domain(d) for d in include], [clean_domain(d) for d in exclude]
    found = [(url, host_of(url)) for url in urls]
    bad = [
        {"url": u, "host": h, "reason": violation(h, inc, exc)}
        for u, h in found
        if violation(h, inc, exc)
    ]
    return {"checked": len(found), "violations": bad, "held": len(found) - len(bad)}

These functions reduce each URL to its host, then test it against the rule. They name every result that breaks it and say why.

urls = ["https://www.reddit.com/r/a", "https://old.reddit.com/r/b", "https://notreddit.com/x"]
urls.append("https://example.org/y")
found = check_domains(urls, include=["Reddit.com"])
print(found["held"], "of", found["checked"], "follow the rule")
for v in found["violations"]:
    print(v["host"], "->", v["reason"])

Output:

2 of 4 follow the rule
notreddit.com -> not on an included domain
example.org -> not on an included domain

old.reddit.com counts as reddit.com, and notreddit.com doesn't, even though its name ends the same way. That distinction is why the match tests for a dot before the domain.

The API takes one list or the other. Asking for both returns the validation message Use "includeDomains" or "excludeDomains", not both., and the check refuses the same combination:

try:
    check_domains(["https://a.test/"], include=["a.test"], exclude=["b.test"])
except ValueError as error:
    print(error)

Output:

use include or exclude, not both

Pick the list that matches your need. If you must exclude some sites and include others, include the ones you want, since an include list already leaves everything else out.

Country: a hint you can measure

A country option leans results. It doesn't select them, so you can't pass or fail it. You can measure what it changed: how many results are shared with the baseline, and how many sit on the country's own domain. That share is a signal, not a verdict, because a UK business can be on a .com.

TRACKING = re.compile(r"^(utm_.+|gclid|fbclid|msclkid)$", re.I)
NOT_COUNTRIES = set(
    "io ai co tv me fm ly gg cc sh to ws im so ac".split()
)  # look like countries, aren't
COUNTRY_TLD = {"gb": "uk"}


def url_key(url):
    """A rough key for comparing results: host, path, and the query without tracking parameters."""
    parts = urlsplit(url.strip())
    if parts.scheme not in ("http", "https") or not host_of(url):
        return ""
    query = urlencode(sorted(p for p in parse_qsl(parts.query) if not TRACKING.match(p[0])))
    return f"{host_of(url)}{parts.path.rstrip('/')}?{query}".rstrip("?")
def keys(urls):
    """Comparison keys for a list of URLs. Addresses that aren't web pages are left out."""
    return {key for key in map(url_key, urls) if key}
def overlap(a_urls, b_urls):
    """Results two runs share. jaccard is 1.0 for identical sets and 0.0 for disjoint ones."""
    a, b = keys(a_urls), keys(b_urls)
    union = len(a | b)
    return {
        "shared": len(a & b),
        "only_a": len(a - b),
        "only_b": len(b - a),
        "jaccard": len(a & b) / union if union else 1.0,
    }


def tld_of(url):
    host = host_of(url)
    return host.rsplit(".", 1)[-1] if "." in host else ""
def country_domain_share(urls, country=None):
    """Share of URLs on a country-code domain, or on this country's own domain. A signal only."""
    tlds = [tld_of(u) for u in urls]
    if not tlds:
        return 0.0
    want = COUNTRY_TLD.get(country, country) if country else None
    hits = [t for t in tlds if (t == want if want else len(t) == 2 and t not in NOT_COUNTRIES)]
    return len(hits) / len(tlds)

url_key builds a rough comparison key, so two addresses for one page match. overlap counts the results two runs share, and country_domain_share finds the fraction on a country-code domain.

base = ["https://a.co.uk/x", "https://b.com/y", "https://c.com/z"]
base.append("https://d.org/w")
de = ["https://k.de/x", "https://l.de/y", "https://b.com/y", "https://c.com/z"]
moved = overlap(base, de)
print("shared:", moved["shared"], "| new:", moved["only_b"], "| dropped:", moved["only_a"])
share = country_domain_share
print("on a .de domain:", share(de, "de"), "| baseline:", share(base, "de"))

Output:

shared: 2 | new: 2 | dropped: 2
on a .de domain: 0.5 | baseline: 0.0

The country variant pulled in two .de results and dropped two others, so it changed the list. Half of its results still aren't on a .de domain, which is what a preference looks like. If you need results from one country, choose domains you trust and use an include list, and check the results anyway.

Time ranges: a bias, and only some sources have dates

Checking a time window needs a date on each result. News, research and developer results carry one. Web, image and video results don't, so a web result's age can't be checked from the response at all. A date also arrives in more than one format, such as ISO text, a written date or "3 hours ago", and "ago" only means something relative to when the search ran:

WINDOW_DAYS = {"hour": 1 / 24, "day": 1.0, "week": 7.0, "month": 31.0, "year": 366.0}
UNIT_DAYS = {
    "second": 1 / 86400,
    "sec": 1 / 86400,
    "minute": 1 / 1440,
    "min": 1 / 1440,
    "hour": 1 / 24,
    "hr": 1 / 24,
    "day": 1.0,
    "week": 7.0,
    "month": 30.0,
    "year": 365.0,
}
RELATIVE = re.compile(r"(?:about\s+)?(\d+|an?|one)\s+([a-z]+?)s?\s+ago", re.I)
WRITTEN = ("%b %d, %Y", "%B %d, %Y", "%d %b %Y", "%d %B %Y", "%Y/%m/%d", "%b %d %Y")
NOW_WORDS = {"now": 0.0, "just now": 0.0, "today": 0.0, "yesterday": 1.0}


def aware(moment):
    return moment if moment.tzinfo else moment.replace(tzinfo=timezone.utc)
def parse_relative(text, now):
    """'3 days ago', 'an hour ago', 'yesterday'. None when it isn't one of those."""
    word = text.strip().lower()
    if word in NOW_WORDS:
        return now - timedelta(days=NOW_WORDS[word])
    found = RELATIVE.fullmatch(word)
    unit = UNIT_DAYS.get(found.group(2)) if found else None
    if unit is None:
        return None
    count = 1 if found.group(1).lower() in ("a", "an", "one") else int(found.group(1))
    return now - timedelta(days=count * unit)
def parse_when(text, now):
    """A moment from an ISO date, a common written date or 'N units ago'. None if unsure."""
    if not isinstance(text, str) or not text.strip():
        return None
    text = text.strip()
    try:
        return aware(datetime.fromisoformat(text))
    except ValueError:
        pass
    for pattern in WRITTEN:
        try:
            return aware(datetime.strptime(text, pattern))
        except ValueError:
            continue
    return parse_relative(text, now)
def age_days(moment, now):
    """Days between a moment and now. Negative when the moment is in the future."""
    return (now - moment).total_seconds() / 86400
def item_age(item, now):
    """The age in days, or the reason there isn't one: 'undated' or 'unparsed'."""
    if not item.get("date"):
        return "undated"
    when = parse_when(item["date"], now)
    return "unparsed" if when is None else age_days(when, now)
def check_window(items, window, now, slack_days=0.0):
    """Each dated result against the window. A future date counts as inside it."""
    limit = WINDOW_DAYS[window] + slack_days
    out = {"checked": 0, "undated": 0, "unparsed": 0, "outside": []}
    for item in items:
        age = item_age(item, now)
        if isinstance(age, str):
            out[age] += 1
            continue
        out["checked"] += 1
        if age > limit:
            out["outside"].append(
                {"url": item["url"], "date": item["date"], "age_days": round(age, 3)}
            )
    return out
def age_text(days):
    """A readable age: hours when it is under two days old, otherwise days."""
    return f"{days * 24:.0f} hours" if days < 2 else f"{days:.1f} days"

parse_when reads the common formats and returns nothing when it isn't sure, instead of guessing. check_window compares each dated result with a window, and counts the ones with no date separately.

now = datetime(2026, 11, 27, 12, 0, tzinfo=timezone.utc)
for text in ["2026-11-26T09:30:00Z", "Nov 12, 2026", "3 hours ago", "2 weeks ago", "03/04/2026"]:
    when = parse_when(text, now)
    print(f"{text:22s} ->", when.date() if when else "unreadable")

Output:

2026-11-26T09:30:00Z   -> 2026-11-26
Nov 12, 2026           -> 2026-11-12
3 hours ago            -> 2026-11-27
2 weeks ago            -> 2026-11-13
03/04/2026             -> unreadable

Four formats parse. 03/04/2026 doesn't, because it could be March 4 or April 3, and a wrong guess would put a result inside or outside a window by mistake.

items = [{"url": "https://a.test/1", "date": "2 hours ago"}]
items.append({"url": "https://a.test/2", "date": "2026-11-20"})
items.append({"url": "https://a.test/3"})
found = check_window(items, "day", now)
print(found["checked"], "dated,", found["undated"], "undated,", len(found["outside"]), "outside")
print(found["outside"][0]["url"], "is", age_text(found["outside"][0]["age_days"]), "old")

Output:

2 dated, 1 undated, 1 outside
https://a.test/2 is 7.5 days old

Of three results, two could be checked and one couldn't. The week-old result is outside a one-day window. The undated one is neither inside nor outside, and it's reported, not hidden.

A search to practice on

To run everything offline, this stand-in for client.search has made-up results. It behaves as the documentation says: a domain filter is enforced, and country and time range only lean the results. It can also leak on purpose, so you can see the check catch it:

NOW = datetime(2026, 11, 27, 12, 0, tzinfo=timezone.utc)
WEB = [
    "forum-example.com/r/espresso/best-grinder",
    "old.forum-example.com/r/coffee/pour-over",
    "roasters-example.com/guides/espresso",
    "beans-example.co.uk/guide",
    "cuppa-example.co.uk/review",
    "kaffee-example.de/test",
    "espresso-example.de/vergleich",
    "blog-example.com/espresso-tips",
    "forum-example.com/r/coffee/grinders",
    "shop-example.com/espresso-machines",
    "notes-example.org/coffee",
]
NEWS = [
    ("news-example.co.uk/coffee-prices", "2 hours ago"),
    ("daily-example.com/espresso-boom", "5 hours ago"),
    ("times-example.de/kaffee", "2026-11-26T08:00:00Z"),
    ("wire-example.com/beans", "2026-11-24"),
    ("post-example.co.uk/cafe", "3 days ago"),
    ("herald-example.com/roast", "Nov 18, 2026"),
    ("tribune-example.org/crop", "2 weeks ago"),
    ("gazette-example.de/preis", "2026-10-30"),
    ("review-example.com/year", "9 months ago"),
    ("archive-example.com/2025", "2025-03-14"),
]
def pool_for(source):
    """The made-up results for a source. News results carry a date, web results don't."""
    if source == "news":
        return [{"url": f"https://{path}", "date": date} for path, date in NEWS]
    return [{"url": f"https://{path}", "date": None} for path in WEB] if source == "web" else []
def on(url, domains):
    return any(matches(host_of(url), d) for d in domains)


def apply_domains(pool, include, exclude, leaky):
    """Enforced: keep only what follows the rule. leaky=True lets one off-domain result through."""
    inc, exc = [clean_domain(d) for d in include or []], [clean_domain(d) for d in exclude or []]
    kept = [r for r in pool if (not inc or on(r["url"], inc)) and not on(r["url"], exc)]
    if leaky and inc and kept:
        kept.insert(min(2, len(kept)), next(r for r in pool if r not in kept))
    return kept
def lean_country(pool, country):
    """A hint: pull up to three results from the country's own domain to the front."""
    tld = COUNTRY_TLD.get(country, country)
    lead = [r for r in pool if tld_of(r["url"]) == tld][:3] if country else []
    return lead + [r for r in pool if r not in lead]


def lean_time(pool, window):
    """A hint: recent results first, then older ones fill the list. Nothing is cut off."""
    if not window or not any(r["date"] for r in pool):
        return pool
    aged = sorted(pool, key=lambda r: age_days(parse_when(r["date"], NOW), NOW))
    return [r for r in aged if age_days(parse_when(r["date"], NOW), NOW) <= WINDOW_DAYS[window]] + [
        r for r in aged if age_days(parse_when(r["date"], NOW), NOW) > WINDOW_DAYS[window]
    ]
def make_items(pool, source, limit):
    rows = [(n, r) for n, r in enumerate(pool[:limit], 1)]
    items = [
        SimpleNamespace(
            position=n, title=f"Result from {host_of(r['url'])}", url=r["url"], date=r["date"]
        )
        for n, r in rows
    ]
    return SimpleNamespace(data=SimpleNamespace(**{source: items}))
class FilterFake:
    def __init__(self, leaky=False):
        self.leaky, self.calls = leaky, []

    def search(self, query, sources, limit, **options):
        """Takes the SDK's options: include_domains, exclude_domains, country, time_range."""
        include, exclude = options.get("include_domains"), options.get("exclude_domains")
        self.calls.append({"query": query, "limit": limit, **options})
        if include and exclude:
            raise SpidraValidationError('Use "includeDomains" or "excludeDomains", not both.')
        pool = apply_domains(pool_for(sources[0]), include, exclude, self.leaky)
        pool = lean_time(lean_country(pool, options.get("country")), options.get("time_range"))
        return make_items(pool, sources[0], limit)

The results are made up, so no real site is named. Here is what each option does to them:

fake = FilterFake()
hosts = lambda items: [host_of(i.url) for i in items]
only = fake.search("q", ["web"], 20, include_domains=["forum-example.com"])
print("include:", hosts(only.data.web))
print("country de, first 3:", hosts(fake.search("q", ["web"], 20, country="de").data.web)[:3])
news = fake.search("q", ["news"], 20, time_range="day").data.news
print("time day:", [i.date for i in news][:4], "...", news[-1].date)

Output:

include: ['forum-example.com', 'old.forum-example.com', 'forum-example.com']
country de, first 3: ['kaffee-example.de', 'espresso-example.de', 'forum-example.com']
time day: ['2 hours ago', '5 hours ago', '2026-11-26T08:00:00Z', '3 days ago'] ... 2025-03-14

The include filter returned only the three matching results. The country option moved two .de results to the front but kept the rest. The day window put the two recent articles first, and the list still runs on to a result from 2025, so nothing was cut off.

Run the same search with each option

The probe runs the baseline and then one variant per option, so each difference comes from one change. Failures need a message and an exit code, so a script that calls the probe can tell them apart:

NO_API_KEY = 3  # missing or rejected
UNKNOWN = 1
BAD_OPTIONS = 11  # the options can't be combined, or a value isn't allowed
ENFORCED_BROKEN = 13  # a filter that should be enforced let a result through


class Failure(Exception):
    def __init__(self, message, code):
        super().__init__(message)
        self.message, self.code = message, code
RULES = [
    (
        SpidraAuthenticationError,
        NO_API_KEY,
        "the Spidra API key was rejected. Check SPIDRA_API_KEY.",
    ),
    (SpidraPaymentRequiredError, 4, "the account is out of credits, or its payment is overdue."),
    (SpidraRateLimitError, 5, "too many requests. Wait a moment, or raise --pause."),
    (SpidraTimeoutError, 6, "the search took too long."),
    (SpidraJobFailedError, 7, None),  # its own message says what failed
    (SpidraValidationError, 8, None),  # its own message says which option was refused
    (SpidraServerError, 9, "Spidra had a problem on its side. Try again."),
]
def explain(error):
    """The first rule that matches wins. List the specific errors before the general one."""
    for kind, code, text in RULES:
        if isinstance(error, kind):
            return Failure(text or str(error), code)
    return Failure(str(error), UNKNOWN)

These define one exit code and one plain message per kind of failure.

DOMAIN_SOURCES = {"web", "news", "images", "videos"}  # the sources the domain filters apply to
DATED_SOURCES = {"news", "research", "developer"}  # the sources whose results carry a date


@dataclass(frozen=True)
class Variant:
    name: str
    options: dict = field(default_factory=dict)
    promise: str = "baseline"  # baseline, enforced or hint


def domain_variant(kind, domains):
    return Variant(f"{kind}:" + ",".join(domains), {f"{kind}_domains": list(domains)}, "enforced")
def check_windows(windows):
    bad = [w for w in windows if w not in WINDOW_DAYS]
    if bad:
        raise ValueError(f"time windows are {', '.join(WINDOW_DAYS)}, not {bad[0]!r}")
def plan(include=(), exclude=(), countries=(), windows=()):
    """The baseline, then one variant for each option. The API takes one domain list, never both."""
    if include and exclude:
        raise ValueError("use include or exclude, not both")
    check_windows(windows)
    variants = [Variant("baseline")]
    variants += [domain_variant("include", include)] * bool(include)
    variants += [domain_variant("exclude", exclude)] * bool(exclude)
    variants += [Variant(f"country:{c}", {"country": c}, "hint") for c in countries]
    return variants + [Variant(f"time:{w}", {"time_range": w}, "hint") for w in windows]
def skip_reason(source, variant):
    """Domain filters don't apply to every source, so say so instead of sending them."""
    domain = {"include_domains", "exclude_domains"} & set(variant.options)
    return (
        f"domain filters don't apply to the {source} source"
        if domain and source not in DOMAIN_SOURCES
        else ""
    )


def to_rows(items):
    return [
        {"position": i.position, "title": i.title, "url": i.url, "date": getattr(i, "date", None)}
        for i in items
    ]
def run_variant(client, query, source, limit, variant):
    """One search. A failure is kept in the run, so one bad option doesn't lose the others."""
    run = {"variant": variant.name, "promise": variant.promise, "options": variant.options}
    run |= {"results": [], "error": "", "code": 0, "skipped": False}
    if reason := skip_reason(source, variant):
        return run | {"error": reason, "skipped": True}
    try:
        result = client.search(query, sources=[source], limit=limit, **variant.options)
    except SpidraError as error:
        failure = explain(error)
        return run | {"error": failure.message, "code": failure.code}
    return run | {"results": to_rows(getattr(result.data, source) or [])}
def utc_now():
    return datetime.now(timezone.utc)


def run_probe(client, query, source, limit, variants, pause=0.0, sleep=time.sleep, clock=utc_now):
    """Every variant, in order. Each run records when it ran, to resolve 'a day ago' later."""
    runs = []
    for variant in variants:
        ran = {"query": query, "source": source, "limit": limit, "ran_at": clock().isoformat()}
        runs.append({**ran, **run_variant(client, query, source, limit, variant)})
        sleep(pause)
    return runs

plan builds the variants and refuses both domain lists. run_variant keeps a failed search in the run, so one bad option doesn't lose the others. Each run records when it ran, so a date like "2 hours ago" can be resolved later.

variants = plan(include=["forum-example.com"], countries=["gb", "de"])
runs = run_probe(FilterFake(), "espresso", "web", 5, variants, clock=lambda: NOW)
for run in runs:
    print(run["variant"], "|", run["promise"], "|", len(run["results"]), "results")

Output:

baseline | baseline | 5 results
include:forum-example.com | enforced | 3 results
country:gb | hint | 5 results
country:de | hint | 5 results

This runs four searches: the baseline, one enforced filter and two hints. Domain filters don't apply to every source, so the probe says so instead of sending them:

include = Variant("include:a.test", {"include_domains": ["a.test"]}, "enforced")
run = run_variant(FilterFake(), "q", "research", 5, include)
print("skipped:", run["skipped"])
print("reason: ", run["error"])

Output:

skipped: True
reason:  domain filters don't apply to the research source

The research and developer sources don't take domain filters, so an include list there would be silently ignored. Skipping it makes that visible.

Read the results: enforced or hint

Each variant gets one row. An enforced filter has a verdict, held or broken. A hint has no pass or fail, so its row describes how far the results moved:

def urls_of(run):
    return [r["url"] for r in run["results"]]


def judge_domains(run):
    """An enforced filter has a clear verdict: it held, or it didn't."""
    inc, exc = run["options"].get("include_domains", []), run["options"].get("exclude_domains", [])
    found = check_domains(urls_of(run), inc, exc)
    total, bad = found["checked"], len(found["violations"])
    if bad:
        return (
            "BROKEN",
            f"{bad} of {total} results broke the rule, such as {found['violations'][0]['host']}",
        )
    return "held", f"all {total} results follow the rule" if total else "no results to check"
def judge_country(run, base):
    """A hint has no pass or fail. Measure how far the results moved."""
    code = run["options"]["country"]
    moved = overlap(urls_of(base), urls_of(run)) if base else None
    here, there = country_domain_share(urls_of(run), code), (
        country_domain_share(urls_of(base), code) if base else 0.0
    )
    change = (
        f"{moved['shared']} results shared with the baseline" if moved else "no baseline to compare"
    )
    return "hint", f"{change}; on the country's own domain: {here:.0%} (baseline {there:.0%})"
def judge_time(run, source, now):
    """A time range is a bias. Check dates where the source has them."""
    if source not in DATED_SOURCES:
        return "hint", f"can't check: {source} results carry no date"
    window = run["options"]["time_range"]
    found = check_window(run["results"], window, now)
    if not found["checked"]:
        return "hint", "no results with a date I could read"
    inside = found["checked"] - len(found["outside"])
    oldest = max((o["age_days"] for o in found["outside"]), default=0)
    note = f", the oldest {age_text(oldest)} old" if found["outside"] else ""
    return "hint", f"{inside} of {found['checked']} dated results inside the {window} window{note}"
def judge(run, base, now):
    options = run["options"]
    if run["error"]:
        return "skipped" if run["skipped"] else "error", run["error"]
    if "include_domains" in options or "exclude_domains" in options:
        return judge_domains(run)
    if "country" in options:
        return judge_country(run, base)
    return (
        judge_time(run, run["source"], now)
        if "time_range" in options
        else ("baseline", f"{len(run['results'])} results")
    )
def now_for(run, default):
    """Relative dates mean 'ago' as of the moment the search ran, not the moment you analyze it."""
    return parse_when(run.get("ran_at"), default) or default


def row_for(run, base, now):
    verdict, detail = judge(run, base, now_for(run, now))
    return {
        "option": run["variant"],
        "promise": run["promise"],
        "results": len(run["results"]),
        "verdict": verdict,
        "detail": detail,
    }
def analyze(runs, now=None):
    now = now or datetime.now(timezone.utc)
    base = next((r for r in runs if r["variant"] == "baseline" and not r["error"]), None)
    return [row_for(run, base, now) for run in runs]
def render_table(rows):
    lines = [
        "| option | promise | results | verdict | what the results show |",
        "|---|---|---|---|---|",
    ]
    lines += [
        f"| {r['option']} | {r['promise']} | {r['results']} | {r['verdict']} | {r['detail']} |"
        for r in rows
    ]
    return "\n".join(lines)


def broken(rows):
    return [r for r in rows if r["promise"] == "enforced" and r["verdict"] == "BROKEN"]

These functions turn each run into one row of the table. Dates are resolved against the time of the search, not the time you read the report.

variants = plan(include=["forum-example.com"], countries=["gb", "de"])
runs = run_probe(FilterFake(), "espresso", "web", 5, variants, clock=lambda: NOW)
print(render_table(analyze(runs, NOW)))

Output:

| option | promise | results | verdict | what the results show |
|---|---|---|---|---|
| baseline | baseline | 5 | baseline | 5 results |
| include:forum-example.com | enforced | 3 | held | all 3 results follow the rule |
| country:gb | hint | 5 | hint | 5 results shared with the baseline; on the country's own domain: 40% (baseline 40%) |
| country:de | hint | 5 | hint | 3 results shared with the baseline; on the country's own domain: 40% (baseline 0%) |

The enforced row says held: all three results follow the rule. The two hints only describe. The gb variant didn't change the five results, and the de variant changed two of them, yet only 40% of its results are on a .de domain. Neither can be said to have filtered anything.

variants = plan(windows=["day", "week", "month"])
runs = run_probe(FilterFake(), "coffee", "news", 8, variants, clock=lambda: NOW)
print(render_table(analyze(runs, NOW)))

Output:

| option | promise | results | verdict | what the results show |
|---|---|---|---|---|
| baseline | baseline | 8 | baseline | 8 results |
| time:day | hint | 8 | hint | 2 of 8 dated results inside the day window, the oldest 28.5 days old |
| time:week | hint | 8 | hint | 5 of 8 dated results inside the week window, the oldest 28.5 days old |
| time:month | hint | 8 | hint | 8 of 8 dated results inside the month window |

On the news source, where results have dates, each window shows how many results fall inside it. A narrow window still returns results that are 28 days old, which is what a bias does.

An enforced filter that leaks must fail loudly. Here the stand-in leaks one result on purpose:

variants = plan(include=["forum-example.com"])
runs = run_probe(FilterFake(leaky=True), "espresso", "web", 5, variants, clock=lambda: NOW)
rows = analyze(runs, NOW)
print(rows[1]["verdict"], "|", rows[1]["detail"])

Output:

BROKEN | 1 of 4 results broke the rule, such as roasters-example.com

The probe flags the off-domain result by name. Against the real API, the same check tells you whether the enforced filter held on your query.

A decision guide

You need

Use

Promise

If you need a guarantee

Only these sites

includeDomains

Enforced on web, news, images, videos

Check hosts anyway, and don't use it on research or developer

Never these sites

excludeDomains

Enforced on the same sources

Same

Results from one country

country

A hint

Include domains you trust, and check hosts and content

Fresh results

timeRange

A bias

Use a dated source and apply your own cutoff

A hard date window

timeRange, then your own filter on date

You enforce it

News, research and developer results carry a date

Sites and a region together

includeDomains with domains from that region

Enforced for sites

Whether a suffix such as co.uk is accepted isn't documented, so test it first

The finished command

The command runs the probe, writes every run to a file, prints the table and exits with a code a scheduler can read:

def split_list(text):
    return [part.strip() for part in (text or "").split(",") if part.strip()]


def write_runs(path, runs):
    with open(path, "w", encoding="utf-8") as handle:
        handle.writelines(json.dumps(run, ensure_ascii=False) + "\n" for run in runs)


def read_runs(path):
    lines = Path(path).read_text(encoding="utf-8").splitlines()
    return [json.loads(line) for line in lines if line.strip()]
def add_filters(ask):
    ask.add_argument("--include", help="comma-separated domains to allow")
    ask.add_argument("--exclude", help="comma-separated domains to drop")
    ask.add_argument("--countries", help="comma-separated country codes, such as gb,de")
    ask.add_argument("--windows", help="comma-separated: hour, day, week, month, year")


def add_run_options(ask):
    ask.add_argument("--pause", type=float, default=1.0, help="seconds between searches")
    ask.add_argument("--out", default="runs.jsonl")
    ask.add_argument("--analyze", help="read this runs file instead of searching")
def build_parser():
    ask = argparse.ArgumentParser(
        description="Probe a search with domain, country and time options."
    )
    ask.add_argument("query", nargs="?", default="")
    ask.add_argument(
        "--source",
        default="web",
        choices=["web", "news", "images", "videos", "research", "developer"],
    )
    ask.add_argument("--limit", type=int, default=10, help="results per run, 1 to 20")
    add_filters(ask)
    add_run_options(ask)
    return ask
def make_client():
    if not os.environ.get("SPIDRA_API_KEY"):
        raise Failure("set SPIDRA_API_KEY to your Spidra key first.", NO_API_KEY)
    return Spidra(api_key=os.environ["SPIDRA_API_KEY"], api_url=os.environ.get("SPIDRA_API_URL"))
def variants_from(args):
    lists = (
        split_list(args.include),
        split_list(args.exclude),
        split_list(args.countries),
        split_list(args.windows),
    )
    try:
        return plan(*lists)
    except ValueError as error:
        raise Failure(str(error), BAD_OPTIONS) from error
def collect(args, client, sleep):
    if not args.query.strip():
        raise Failure("give a topic to search for.", BAD_OPTIONS)
    runs = run_probe(
        client, args.query.strip(), args.source, args.limit, variants_from(args), args.pause, sleep
    )
    write_runs(args.out, runs)
    return runs


def exit_code(runs, rows):
    base = next((r for r in runs if r["variant"] == "baseline"), None)
    if base and base["error"] and not base["skipped"]:
        return base["code"] or 1
    return ENFORCED_BROKEN if broken(rows) else 0
def report(runs):
    last = runs[-1].get("ran_at") if runs else None
    rows = analyze(runs, datetime.fromisoformat(last) if last else None)
    print(render_table(rows))
    return exit_code(runs, rows)
def main(argv=None, client=None, sleep=time.sleep):
    args = build_parser().parse_args(argv)
    try:
        runs = (
            read_runs(args.analyze)
            if args.analyze
            else collect(args, client or make_client(), sleep)
        )
    except Failure as failure:
        print(f"error: {failure.message}", file=sys.stderr)
        return failure.code
    except (ValueError, OSError) as error:
        print(f"error: {error}", file=sys.stderr)
        return 1
    return report(runs)

Save the pieces as filter_probe.py and run python filter_probe.py "espresso machine reviews" --include reddit.com --countries gb,de. Add --source news --windows day,week,month for time ranges, and --analyze runs.jsonl to read a saved file without searching again.

The exit code says what happened: 0 for success, 3 for the key, 4 for credits or an overdue payment, 5 for the rate limit, 11 for options that can't be combined, and 13 when an enforced filter let a result through. That last one is the code to alert on.

What this doesn't prove

A clean run shows that a filter held for one query on one day. It doesn't prove it holds for every query, so run the probe on the queries your product depends on. The country share is a signal, not a location check, and the date check covers only sources that return a date.

And whether includeDomains accepts a suffix such as co.uk, or matches a subdomain the way this check does, isn't documented, so test both before you rely on them.

Selection you can verify

You now have a way to find out what a search option does: run the same query with and without it, check each result against the rule, and read a table that separates a rule from a preference. That matters more than which options an API offers, because the cost of a wrong assumption lands on your users.

Here is what Spidra gives you for selecting sources:

  • A domain filter that is enforced. Results are checked against it before they're returned, so a site list is a rule you can build a product on.
  • Six sources, each on its own. Web, news, images, videos, research and developer results run independently, so one empty source doesn't fail the others.
  • Dates where they matter. News, research and developer results carry a date, so you can apply your own hard cutoff on top of timeRange.
  • Preferences that are labeled as preferences. Country and time range are documented as hints, so you know what you're buying and can check it.
  • The same filters on every page. Pagination tokens continue a search with the same options, and our guide to paginating and deduplicating results shows how.
  • A direct path to the content. Hand the results you keep to Scrape or a batch scrape, and the selection becomes data.

If you need a strict geography or recency guarantee, no search option replaces checking. Spidra gives you the enforced part, the dates to do the rest yourself, and clear documentation of which is which.

Create a free account, run filter_probe.py on a query your product depends on, and read the verdict column. Our post on searching for PDF documents uses another Search filter, and the Search docs list every option.

Frequently asked questions

It depends on the API, so check its documentation. With Spidra Search, domain filters are enforced and results are checked against them before they're returned. Country and time range are hints that shape results without strictly filtering them.

Share this article

You build the product.
Spidra handles the data work.

Start with 300 free credits, about 300 pages. No credit card required.