diff --git a/wrolpi/files/lib.py b/wrolpi/files/lib.py
index d8fee320..b129fec2 100644
--- a/wrolpi/files/lib.py
+++ b/wrolpi/files/lib.py
@@ -1498,12 +1498,6 @@ def search_files(session: Session, search_str: str, limit: int, offset: int, mim
# Nothing usable to search (punctuation-only or all-negated query); match nothing, like
# an empty websearch_to_tsquery did.
return [], 0
- if fts_search:
- joins.append(fts_search.join)
- selects.append(fts_search.rank_select)
- params.update(fts_search.params)
- order_by = '2 DESC'
-
wheres, params = mimetypes_to_sql_wheres(wheres, params, mimetypes)
if model:
params['model'] = model
@@ -1531,6 +1525,7 @@ def search_files(session: Session, search_str: str, limit: int, offset: int, mim
if in_progress:
wheres.append('fg.progress > 0 AND fg.progress < 1')
+ with_headlines = bool(headline)
if fts_search and headline:
# b/c/d headlines come from FTS5 snippets (computed in the fts subquery); the title
# headline is computed in Python by `handle_file_group_search_results` (title is not an
@@ -1549,6 +1544,21 @@ def search_files(session: Session, search_str: str, limit: int, offset: int, mim
# Only filter out unviewed files if search_str is not provided.
wheres.append('viewed IS NOT NULL')
+ # With nothing but the search to filter by, rank, page and count inside the FTS index: a common term can match
+ # most of the library, and joining every match to file_group reads one large row per match.
+ fts_only = bool(fts_search) and not wheres and order not in ('viewed', '-viewed')
+ page_offset = offset
+ if fts_search:
+ if fts_only:
+ fts_search = fts.file_group_search_join(search_str, deep=deep, headlines=with_headlines, paged=True)
+ page_offset = 0
+ joins.append(fts_search.join)
+ selects.append(fts_search.rank_select)
+ params.update(fts_search.params)
+ if order not in ('viewed', '-viewed'):
+ order_by = '2 DESC'
+ params['page_offset'] = page_offset
+
where_sql = ('WHERE\n' + '\n AND '.join(wheres)) if wheres else ''
extra_selects = f', {", ".join(selects)}' if selects else ''
join = '\n'.join(joins)
@@ -1559,7 +1569,7 @@ def search_files(session: Session, search_str: str, limit: int, offset: int, mim
{join}
{where_sql}
ORDER BY {order_by}
- LIMIT :limit OFFSET :offset
+ LIMIT :limit OFFSET :page_offset
'''
logger.debug(stmt)
@@ -1570,6 +1580,9 @@ def search_files(session: Session, search_str: str, limit: int, offset: int, mim
and not path and not viewed_only and not in_progress:
count_stmt = 'SELECT COUNT(*) AS total FROM file_group'
count_params = dict()
+ elif fts_only:
+ count_stmt = 'SELECT COUNT(*) AS total FROM file_group_fts WHERE file_group_fts MATCH :fts_match'
+ count_params = dict(fts_match=params['fts_match'])
elif fts_search:
# Count via a direct FTS join (no ranking) rather than the snippet subquery.
fts_count = fts.file_group_search(search_str, deep=deep)
diff --git a/wrolpi/files/test/test_lib.py b/wrolpi/files/test/test_lib.py
index fc59a911..61b13233 100644
--- a/wrolpi/files/test/test_lib.py
+++ b/wrolpi/files/test/test_lib.py
@@ -2283,3 +2283,45 @@ def test_sha256_files(test_directory):
video.write_bytes(b'video changed')
os.utime(video, ns=(0, 0))
assert lib.sha256_files([video], known=known) == {video: (0, hashlib.sha256(b'video changed').hexdigest())}
+
+
+@pytest.mark.parametrize('headline', [False, True])
+def test_search_files_pages_inside_fts(test_session, test_directory, headline):
+ """A search with no other filters ranks, pages and counts inside the FTS index, so only the page's rows are read
+ from file_group (a common term can match most of the library). Results match the filtered (joined) query."""
+ for i in range(1, 7):
+ path = test_directory / f'doc{i}.txt'
+ path.write_text('x')
+ file_group = FileGroup.from_paths(test_session, path)
+ # Each file mentions "solar" a different number of times, so the ranking is strict.
+ file_group.title = file_group.a_text = ' '.join(['solar'] * i + ['filler'] * 10)
+ unrelated = test_directory / 'unrelated.txt'
+ unrelated.write_text('x')
+ FileGroup.from_paths(test_session, unrelated).a_text = 'garden'
+ test_session.commit()
+
+ # Oracle: the same search with a filter that matches every file takes the joined query.
+ expected, expected_total = lib.search_files(test_session, 'solar', 10, 0, path='doc', headline=headline)
+ expected_ids = [i['id'] for i in expected]
+ assert expected_total == 6 and len(expected_ids) == 6
+
+ with mock.patch.object(lib, 'handle_file_group_search_results', wraps=lib.handle_file_group_search_results) \
+ as page_query, \
+ mock.patch.object(lib, 'count_file_groups', wraps=lib.count_file_groups) as count_query:
+ pages = [lib.search_files(test_session, 'solar', 2, offset, headline=headline) for offset in (0, 2, 4, 6)]
+
+ assert [total for _, total in pages] == [6, 6, 6, 6]
+ assert [[i['id'] for i in files] for files, _ in pages] == [expected_ids[0:2], expected_ids[2:4], expected_ids[4:6], []]
+ if headline:
+ def headlines(files):
+ return [(i['title_headline'], i['b_headline'], i['c_headline'], i['d_headline']) for i in files]
+
+ assert headlines([i for files, _ in pages for i in files]) == headlines(expected)
+ assert all('solar' in i['title_headline'] for i in expected)
+
+ # Paged inside the FTS subquery; counted without touching file_group.
+ for call in page_query.call_args_list:
+ statement = call.args[1]
+ assert re.search(r'ORDER BY rank\s+LIMIT :limit OFFSET :offset\s*\)', statement), statement
+ for call in count_query.call_args_list:
+ assert 'file_group fg' not in call.args[1] and 'file_group_fts' in call.args[1], call.args[1]
diff --git a/wrolpi/fts.py b/wrolpi/fts.py
index 84de3753..a41a9d34 100644
--- a/wrolpi/fts.py
+++ b/wrolpi/fts.py
@@ -270,13 +270,18 @@ def file_group_search(search_str: str, deep: bool = False,
def file_group_search_join(search_str: str, deep: bool = False, headlines: bool = False,
fg_alias: str = 'fg', param_name: str = 'fts_match',
- start: str = '', stop: str = '', tokens: int = 16) -> Optional[FileGroupSearch]:
+ start: str = '', stop: str = '', tokens: int = 16,
+ paged: bool = False) -> Optional[FileGroupSearch]:
"""Subquery-join form of `file_group_search`.
SQLite refuses FTS5 auxiliary functions (snippet) in a query that also uses window functions
(e.g. COUNT(*) OVER()), so the rank and snippets are computed inside a subquery and joined.
The returned `join` both filters (INNER JOIN on the MATCH) and provides `fts.ts_rank` (and
- `fts.b_headline`/`c_headline`/`d_headline` when `headlines`); `where` is empty."""
+ `fts.b_headline`/`c_headline`/`d_headline` when `headlines`); `where` is empty.
+
+ `paged` ranks and pages inside the subquery (`:limit`/`:offset`), so only that page is joined to file_group and
+ snippets are computed for that page only. Use it only when nothing else filters the matches; the caller's
+ query must not apply the offset again."""
columns = None if deep else ABC_COLUMNS
match = translate_websearch(search_str, columns=columns)
if match is None:
@@ -286,8 +291,9 @@ def file_group_search_join(search_str: str, deep: bool = False, headlines: bool
snippet_selects = (f", snippet(file_group_fts, 1, '{start}', '{stop}', '…', {tokens}) AS b_headline"
f", snippet(file_group_fts, 2, '{start}', '{stop}', '…', {tokens}) AS c_headline"
f", snippet(file_group_fts, 3, '{start}', '{stop}', '…', {tokens}) AS d_headline")
+ page = ' ORDER BY rank LIMIT :limit OFFSET :offset' if paged else ''
join = (f'JOIN (SELECT rowid, -rank AS ts_rank{snippet_selects} FROM file_group_fts '
- f'WHERE file_group_fts MATCH :{param_name}) fts ON fts.rowid = {fg_alias}.id')
+ f'WHERE file_group_fts MATCH :{param_name}{page}) fts ON fts.rowid = {fg_alias}.id')
return FileGroupSearch(join=join, where='', rank_select='fts.ts_rank AS ts_rank',
params={param_name: match})