Skip to content

[BUG] Title search ranks an exact-title note below longer titles that contain it (bm25 normalizes by whole-row length) #1956

Closed

Description

@Flynn-Kawolsky

Summary

With search_type="title" (CLI --title), when several notes match the title query, the note whose title equals the query can rank below a note whose title merely contains it, e.g. Project Atlas ranks below Project Atlas meeting notes 2026-10-02. The order is decided only by how long each note's body is, not by the title.

Environment

Cause

  • Title mode filters with search_index.title MATCH :title_text, then orders by bm25(search_index, ...).
  • FTS5's bm25() normalizes by the row's total token count across all indexed columns (content_stems, content_snippet, script_ngrams, permalink), not by the title column's length.
  • When all candidates match only in the title with the same term frequency, every row gets the same title contribution, so the shorter body wins. Column weights ([BUG] Text search ignores the title: bm25(search_index) has no column weights #1851 / fix(core): preserve title ranking with metadata filters #1882) scale every row equally and leave the order unchanged.
  • For CJK notes, script_ngrams makes up most of the row length (about 80% of tokens in my case), which amplifies the effect.

Real-world numbers (identifiers withheld). The exact-title note has 2,580 tokens (2,065 in script_ngrams) and scores −1.785. The other note has 1,929 tokens (1,567) and scores −2.232, so it ranks first. On a copy of the DB, padding the second note past 2,580 tokens flips the order. Nothing else changed.

Minimal repro (SQLite only, synthetic data, uses the package's own prepare_search_term and the same FTS5 schema)

import sqlite3
from basic_memory.repository.sqlite_search_query import prepare_search_term

SCHEMA = """CREATE VIRTUAL TABLE search_index USING fts5(
    id UNINDEXED, title, content_stems, content_snippet, script_ngrams, permalink,
    file_path UNINDEXED, type UNINDEXED, project_id UNINDEXED, from_id UNINDEXED, to_id UNINDEXED,
    relation_type UNINDEXED, entity_id UNINDEXED, category UNINDEXED, metadata UNINDEXED,
    created_at UNINDEXED, updated_at UNINDEXED,
    tokenize='unicode61 tokenchars 0x2F', prefix='1,2,3,4')"""

hub_body = " ".join(["Status update on milestones, owners, budget and open risks for the quarter."] * 30)
memo_body = " ".join(["Agenda and talking points prepared before the review meeting."] * 8)
rows = [
    ("Project Atlas", hub_body, "project-atlas", "projects/Project Atlas.md"),
    ("Project Atlas meeting notes 2026-10-02", memo_body, "project-atlas-meeting-notes-2026-10-02",
     "projects/Project Atlas meeting notes 2026-10-02.md"),
]
rows += [(f"Unrelated note {n}", "Some other topic entirely. " * 10, f"unrelated-note-{n}", f"misc/Unrelated note {n}.md")
         for n in range(20)]
db = sqlite3.connect(":memory:")
db.execute(SCHEMA)
for i, (title, body, permalink, fp) in enumerate(rows, 1):
    db.execute("INSERT INTO search_index (id, title, content_stems, content_snippet, script_ngrams, permalink, file_path, type)"
               " VALUES (?, ?, ?, ?, '', ?, ?, 'entity')", (i, title, body.lower(), body, permalink, fp))

q = "Project Atlas"
term = prepare_search_term(q, is_prefix=False)
w = ", ".join(["1.0", "5.0"] + ["1.0"] * 15)  # #1882 weights: title 5, others 1
variants = {
    "0.24.1 (bm25(search_index))": ("bm25(search_index)", ""),
    "#1882 weights (title 5)": (f"bm25(search_index, {w})", ""),
    "proposed (exact title first)": ("bm25(search_index)", "(lower(title) = lower(:q)) DESC, "),
}
for name, (score, prefix) in variants.items():
    res = db.execute(f"SELECT title, round({score}, 4) AS s FROM search_index "
                     f"WHERE search_index.title MATCH :t ORDER BY {prefix}s", {"t": term, "q": q}).fetchall()
    print(f"{name:32s}", res)

Output:

0.24.1 (bm25(search_index))      [('Project Atlas meeting notes 2026-10-02', -3.6999), ('Project Atlas', -1.3596)]
#1882 weights (title 5)          [('Project Atlas meeting notes 2026-10-02', -7.1192), ('Project Atlas', -4.2825)]
proposed (exact title first)     [('Project Atlas', -1.3596), ('Project Atlas meeting notes 2026-10-02', -3.6999)]

Expected

In title search, a note whose title equals the query (case-insensitive) ranks first.

Suggested fix

In title mode, sort exact title equality ahead of the bm25 score, e.g. ORDER BY (lower(search_index.title) = lower(:raw_title)) DESC, score. A secondary option is to prefer shorter titles among equal scores. I have not tested the Postgres backend.

Workaround

read_note / memory:// with the exact title resolves the note directly without ranking.

Activity

  1. added
    bug
    on Oct 29, 2026
  2. phernandez commented on Oct 29, 2026

    @phernandez
    Member

    Thanks @Flynn-Kawolsky for the clear write-up and the minimal repro, which made this quick to confirm. Fixed in #1957: title search now sorts an exact (case-insensitive) title match ahead of the bm25 score. That also fixes Postgres, where a title-only search had no rank and came back in id order. One caveat: SQLite's lower() folds ASCII only, so a non-ASCII title must match case exactly to get the boost. It ships in the next release.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions