diff --git a/CHANGELOG.md b/CHANGELOG.md index 8a4ed7d..4214e3e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ What changed in each version of WhatsOn, newest first. ## Unreleased +### Fixed +- **Search finds a title when a word has another ending.** "I killed the bear" now finds *I Kill the Bear*: + when the words as typed find nothing, search tries them again without endings like -ed, -ing and -s. A search + that finds a real match in one section no longer fills the others with near misses that share one word, and a + library title that is exactly what you typed comes first. + ## 0.2.9 - 2026-11-26 ### Added diff --git a/docs/adr/0031-search-tries-stricter-matches-first.md b/docs/adr/0031-search-tries-stricter-matches-first.md new file mode 100644 index 0000000..8551016 --- /dev/null +++ b/docs/adr/0031-search-tries-stricter-matches-first.md @@ -0,0 +1,47 @@ +# 0031. Search tries the words as typed, then without their endings, then most of them + +- **Status:** Proposed +- **Date:** 2026-11-26 + +## Context + +A search for "I killed the bear" didn't surface the show "I Kill the Bear". Each search word is matched as the start of +a word, and "killed" isn't the start of "Kill". When no listing had every word, the guide and the library each fell back +on their own to any listing with all but one of the words, which for a two-word search means either word. So "bear" +filled On TV with Chicago Bears games and the library with every bear film, and the show sat third in its row under +them. + +## Decision + +`search.run` tries three levels in order, on the guide, library and episodes together, and stops at the first level that +finds anything in any of them: + +1. **exact:** every word as typed. +2. **stem:** every word without a common ending (`search.stem`: -ing, -ed, -es, -s, kept to a stem of at least four + letters before an undoubled consonant), so "killed" finds "Kill". Skipped when it's the same as the exact query. +3. **loose:** all but one of the words, the any-word fallback that was already there. Never for episode titles. + +Games keep their own matching. A library title equal to the whole search comes first in the library. The library page's +own search box retries with endings dropped when the words as typed find nothing. + +## Consequences + +- A word with a different ending still finds the title, and the exact words always win: "wicked" finds *Wicked*, and + never *John Wick*, because the stem level only runs when the exact words find nothing. +- One section's real match now stops the other sections from showing near misses. A search whose only real answer is in + the library shows nothing on TV, where before it showed one-word matches. +- The stemming is a handful of English rules, not a real stemmer. Irregular forms ("ran" for "run") and other languages + aren't covered. +- Up to three rounds of queries for a search that finds nothing. They're local FTS5 queries, so the cost is small. + +## Alternatives + +- **FTS5's `porter` tokenizer.** Stems properly, but changes how every table is indexed, and stems as typed too, so + "wicked" would also find "Wick". Not done. +- **Keep the fallback per section, only add stemming.** Fixes the reported case, but leaves near misses filling one + section while another has the real answer. + +## Where it lives + +`stem`, `LEVELS`, `run`, `search_guide`, `search_library` and `search_episodes` in `whatson/search.py`; `/api/library` +in `whatson/routes.py`; `tests/test_core.py`. Builds on ADR 0015 and ADR 0030. diff --git a/docs/adr/README.md b/docs/adr/README.md index 819dc75..b2bd51c 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -82,3 +82,4 @@ Never rewrite an accepted ADR's reasoning. Fix a typo or add a link, but change | [0028](0028-sort-bare-guide-listings.md) | Sort bare guide listings from patterns across the guide | Proposed | | [0029](0029-show-typed-matches-beside-the-ai-reading.md) | Show matches for the words as typed beside the AI's reading | Accepted | | [0030](0030-search-episode-titles.md) | Search finds episodes by their own titles | Proposed | +| [0031](0031-search-tries-stricter-matches-first.md) | Search tries the words as typed, then without their endings, then most of them | Proposed | diff --git a/tests/test_core.py b/tests/test_core.py index 79a33b8..007d145 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -258,6 +258,38 @@ def test_any_word_fallback_needs_most_words(): assert [i["title"] for i in search.search_guide(search_db(), search.Filters(text="big city ducks"), NOW)] == ["Big City Greens"] +def test_stem_drops_common_endings_but_leaves_short_words(): + assert [search.stem(w) for w in ("killed", "bears", "stopped", "running", "movies", "news", "speed", "red", "bus")] \ + == ["kill", "bear", "stop", "run", "movi", "news", "speed", "red", "bus"] + assert search.fts_query("killed bears", stemmed=True) == '"kill"* "bear"*' + + +def stem_db(): + conn = db.connect(":memory:") + channels = [Channel("1", "1", "FOX 6"), Channel("2", "2", "PBS")] + airings = [Airing("1", "Live: NFL Football", "", "Otters at Badgers", "sports", NOW - 600, NOW + 3600), + Airing("2", "Badger Country", "", "A year with the badgers", "episode", NOW, NOW + 1800)] + write_guide(conn, channels, airings, []) + write_library(conn, [LibraryItem("1", "show", "I Chase the Badger", 2026, "A thriller", ["Drama"]), + LibraryItem("2", "movie", "Chaser", 2001, "Racing", ["Action"]), + LibraryItem("3", "movie", "Chaser Two", 2004, "More racing", ["Action"])]) + return conn + + +def test_a_search_word_with_another_ending_still_finds_the_title(): + # "chased" is in no title, so the words as typed find nothing; with endings dropped "chase badger" finds the show. + res = search.run(stem_db(), search.basic_filters("I chased the badger"), NOW) + assert [i["title"] for i in res["library"]] == ["I Chase the Badger"] + # A library match stops the one-word near misses ("badger" alone) from filling the guide. + assert res["guide"] == [] + + +def test_words_as_typed_win_over_their_stems_and_an_exact_title_comes_first(): + # "chaser" as typed matches; its stem "chase" would also pull in "I Chase the Badger", and mustn't. + titles = [i["title"] for i in search.run(stem_db(), search.basic_filters("chaser"), NOW)["library"]] + assert titles[0] == "Chaser" and "I Chase the Badger" not in titles + + def test_following_a_school_covers_its_other_college_sports_but_pro_ids_stay_in_their_league(): rows = [{"league": "football/college-football", "team_id": "901"}, {"league": "hockey/nhl", "team_id": "4"}] keys = espn.followed_team_keys(rows) diff --git a/whatson/routes.py b/whatson/routes.py index 9dd064a..4d27486 100644 --- a/whatson/routes.py +++ b/whatson/routes.py @@ -317,6 +317,9 @@ async def library(kind: str = "movie", sort: str = "added", genre: str = "", q: if sort == "added" and q: order = "bm25(library_fts, 10.0, 1.0, 2.0, 3.0)" total = state.conn.execute(f"SELECT count(*) FROM {src} WHERE {' AND '.join(where)}", args).fetchone()[0] + if fq and not total and (stemmed := search.fts_query(q, stemmed=True)) != fq: + args[0] = stemmed # "killed" finds "Kill" when the words as typed find nothing + total = state.conn.execute(f"SELECT count(*) FROM {src} WHERE {' AND '.join(where)}", args).fetchone()[0] rows = state.conn.execute(f"SELECT l.* FROM {src} WHERE {' AND '.join(where)} ORDER BY {order} LIMIT ? OFFSET ?", args + [min(limit, 200), offset]).fetchall() items = [search.library_item(r) for r in rows] diff --git a/whatson/search.py b/whatson/search.py index 6086cd1..d9513d0 100644 --- a/whatson/search.py +++ b/whatson/search.py @@ -116,20 +116,48 @@ def _words(text: str) -> list[str]: return [w for w in re.findall(r"[\w']+", text.lower()) if w not in STOPWORDS] +def stem(word: str) -> str: + """The word without a common ending, so "killed" finds "Kill" and "bears" finds "Bear". Searched as a prefix, + so the stem only has to be the start of the word. Short words are left alone ("red", "news", "speed").""" + if not word.isalpha(): + return word + for ending in ("ing", "ed", "es", "s"): + base = word[: -len(ending)] + if word.endswith(ending) and len(base) >= 4 and not (ending == "s" and base[-1] in "su"): + if base[-1] == base[-2] and base[-1] not in "lsz": # "stopped" -> "stop", but "killed" -> "kill" + base = base[:-1] + return base + return word + + +# How strictly the search words are matched, tried in this order until something matches (see run()). +LEVELS = ("exact", "stem", "loose") + + def enough_words(text: str, hay: str) -> bool: """For the any-word fallback: a result must contain all but one of the search words, each at the start of a word. One shared word isn't enough ("green bay packers" must not find "Big City Greens").""" - words = _words(text) + words = [stem(w) for w in _words(text)] hay = hay.lower() hits = sum(1 for w in words if re.search(rf"\b{re.escape(w)}", hay)) return hits >= max(1, len(words) - 1) -def fts_query(text: str, any_word: bool = False) -> str: - words = _words(text) +def fts_query(text: str, any_word: bool = False, stemmed: bool = False) -> str: + words = [stem(w) if stemmed else w for w in _words(text)] if not words: return "" - return (" OR " if any_word else " ").join(f'"{w.replace(chr(34), "")}"*' for w in words) + return (" OR " if any_word else " ").join(f'"{w.replace(chr(34), "")}"*' for w in dict.fromkeys(words)) + + +def _level_query(text: str, level: str) -> str: + """The FTS query for one level, or "" when the level adds nothing (the stems are the words as typed).""" + if level == "loose" and len(_words(text)) < 2: + return "" + q = fts_query(text, any_word=level == "loose", stemmed=level != "exact") + if level == "stem" and q == fts_query(text): + return "" + return q def basic_filters(text: str) -> Filters: @@ -156,7 +184,8 @@ def _channel_rank(vcn: str, title: str) -> tuple: return (num >= GAME_SLOT_MIN_VCN, "antenna" not in title.lower(), num) -def search_guide(conn: sqlite3.Connection, f: Filters, now: int | None = None) -> list[dict]: +def search_guide(conn: sqlite3.Connection, f: Filters, now: int | None = None, + levels: tuple[str, ...] = LEVELS) -> list[dict]: now = now or int(time.time()) horizon = now + (f.within_minutes * 60 if f.within_minutes else 48 * 3600) where = ["a.ends > ?", "a.begins < ?"] @@ -198,20 +227,21 @@ def search_guide(conn: sqlite3.Connection, f: Filters, now: int | None = None) - LEFT JOIN games g ON g.id = a.game_id WHERE {where} ORDER BY rank, a.begins LIMIT 400""" rows: list[sqlite3.Row] = [] - for any_word in (False, True): - q = fts_query(f.text, any_word) - if q: - rows = conn.execute(sql.format( - rank="bm25(airings_fts, 10.0, 4.0, 1.0, 2.0, 8.0)", - src="airings_fts JOIN airings a ON a.id = airings_fts.rowid", - where=" AND ".join(["airings_fts MATCH ?"] + where)), [q] + args).fetchall() - if any_word: - rows = [r for r in rows if enough_words(f.text, " ".join(str(r[k] or "") for k in ( - "title", "subtitle", "summary", "ch_title", "g_name", "g_home", "g_away")))] - else: - rows = conn.execute(sql.format(rank="0", src="airings a", where=" AND ".join(where)), - args).fetchall() - if rows or not q: + if not fts_query(f.text): + rows = conn.execute(sql.format(rank="0", src="airings a", where=" AND ".join(where)), args).fetchall() + return _group(rows, now)[: f.limit] + for level in levels: + q = _level_query(f.text, level) + if not q: + continue + rows = conn.execute(sql.format( + rank="bm25(airings_fts, 10.0, 4.0, 1.0, 2.0, 8.0)", + src="airings_fts JOIN airings a ON a.id = airings_fts.rowid", + where=" AND ".join(["airings_fts MATCH ?"] + where)), [q] + args).fetchall() + if level == "loose": + rows = [r for r in rows if enough_words(f.text, " ".join(str(r[k] or "") for k in ( + "title", "subtitle", "summary", "ch_title", "g_name", "g_home", "g_away")))] + if rows: break return _group(rows, now)[: f.limit] @@ -241,7 +271,7 @@ def _group(rows: list[sqlite3.Row], now: int) -> list[dict]: return out -def search_library(conn: sqlite3.Connection, f: Filters) -> list[dict]: +def search_library(conn: sqlite3.Connection, f: Filters, levels: tuple[str, ...] = LEVELS) -> list[dict]: kinds = [k for k in f.kinds if k in ("movie", "show")] if "episode" in f.kinds and "show" not in kinds: kinds.append("show") @@ -266,16 +296,16 @@ def search_library(conn: sqlite3.Connection, f: Filters) -> list[dict]: where.append(f"l.content_rating IN ({','.join('?' * len(allowed))})") args += list(allowed) rows: list[sqlite3.Row] = [] - for any_word in (False, True): - q = fts_query(f.text, any_word) + for level in levels if fts_query(f.text) else (): + q = _level_query(f.text, level) if not q: - break + continue rows = conn.execute( "SELECT l.*, bm25(library_fts, 10.0, 1.0, 2.0, 3.0) AS rank FROM library_fts " "JOIN library l ON l.rowid = library_fts.rowid WHERE " - + " AND ".join(["library_fts MATCH ?"] + where) + " ORDER BY rank LIMIT ?", - [q] + args + [f.limit]).fetchall() - if any_word: + + " AND ".join(["library_fts MATCH ?"] + where) + " ORDER BY lower(l.title) = ? DESC, rank LIMIT ?", + [q] + args + [f.text.strip().lower(), f.limit]).fetchall() + if level == "loose": rows = [r for r in rows if enough_words(f.text, " ".join(str(r[k] or "") for k in ( "title", "summary", "genres", "people")))] if rows: @@ -289,11 +319,11 @@ def search_library(conn: sqlite3.Connection, f: Filters) -> list[dict]: EPISODE_LIMIT = 20 # a one-word search can match hundreds of episode titles -def search_episodes(conn: sqlite3.Connection, f: Filters) -> list[dict]: +def search_episodes(conn: sqlite3.Connection, f: Filters, level: str = "exact") -> list[dict]: """Episodes whose own title has every search word, so "duck duck loon" finds that episode of a show whose name shares none of those words (ADR 0030). Only for text searches; the show's genres, rating and year - stand in for the episode's.""" - q = fts_query(f.text) + stand in for the episode's. Never loose: one shared word matches hundreds of episode titles.""" + q = _level_query(f.text, level) if level != "loose" else "" if not q or (f.kinds and not {"show", "episode"} & set(f.kinds)): return [] where, args = ["episodes_fts MATCH ?"], [q] @@ -399,9 +429,19 @@ def split_typed(typed: dict, res: dict) -> dict | None: return typed -def run(conn: sqlite3.Connection, f: Filters) -> dict: - guide = search_guide(conn, f) if f.scope in ("all", "guide") else [] - library = search_library(conn, f) if f.scope in ("all", "library") and not f.on_now else [] - games = search_games(conn, f) if f.scope in ("all", "guide") else [] - episodes = search_episodes(conn, f) if f.scope in ("all", "library") and not f.on_now else [] +def run(conn: sqlite3.Connection, f: Filters, now: int | None = None) -> dict: + """Tries each level (LEVELS) on every section together and stops at the first that finds anything, so a + library title that matches the words keeps the guide from filling up with one-word near misses.""" + on_guide = f.scope in ("all", "guide") + on_library = f.scope in ("all", "library") and not f.on_now + games = search_games(conn, f, now) if on_guide else [] + guide: list[dict] = [] + library: list[dict] = [] + episodes: list[dict] = [] + for level in LEVELS if fts_query(f.text) else ("exact",): + guide = search_guide(conn, f, now, levels=(level,)) if on_guide else [] + library = search_library(conn, f, levels=(level,)) if on_library else [] + episodes = search_episodes(conn, f, level) if on_library else [] + if guide or library or episodes: + break return {"games": games, "guide": guide, "library": library, "episodes": episodes}