diff --git a/modules/videos/channel/lib.py b/modules/videos/channel/lib.py index 52af3106..275e0395 100644 --- a/modules/videos/channel/lib.py +++ b/modules/videos/channel/lib.py @@ -217,30 +217,34 @@ async def search_channels_by_name(session: Session, name: str, limit: int = 5, # SQLite sorts by byte value; emulate the old locale-aware (en_US.UTF-8) ordering: compare # names case-insensitively and without spaces, ties broken with lowercase names first. name_order = (func.lower(func.replace(Collection.name, ' ', '')).asc(), Collection.name.desc()) + # Choose the matching Channels by id (Collection names and covering indexes), then read only their rows: a + # channel row holds its yt-dlp info_json, so reading every row is slow from a cold disk cache. + name_filter = or_( + Collection.name.ilike(f'%{name}%'), + Collection.name.ilike(f'%{name_no_spaces}%'), + ) if order_by_video_count: - stmt = session.query(Channel, func.count(Video.id).label('video_count')) \ - .options(*Channel.json_options()) \ + # A correlated count, not GROUP BY channel.id: grouping walks the channel table in rowid order, reading + # every row. + video_count = session.query(func.count(Video.id)).filter(Video.channel_id == Channel.id) \ + .correlate(Channel).scalar_subquery() + stmt = session.query(Channel.id, video_count.label('video_count')) \ .join(Collection) \ - .filter(or_( - Collection.name.ilike(f'%{name}%'), - Collection.name.ilike(f'%{name_no_spaces}%'), - )) \ - .outerjoin(Video, Video.channel_id == Channel.id) \ - .group_by(Channel.id, Collection.id, Collection.name) \ + .filter(name_filter) \ .order_by(desc('video_count'), *name_order) \ .limit(limit) - channels = [i[0] for i in stmt] else: - stmt = session.query(Channel) \ - .options(*Channel.json_options()) \ + stmt = session.query(Channel.id) \ .join(Collection) \ - .filter(or_( - Collection.name.ilike(f'%{name}%'), - Collection.name.ilike(f'%{name_no_spaces}%'), - )) \ + .filter(name_filter) \ .order_by(*name_order) \ .limit(limit) - channels = stmt.all() + channel_ids = [i[0] for i in stmt] + if not channel_ids: + return [] + by_id = {i.id: i for i in session.query(Channel).options(*Channel.json_options()) + .filter(Channel.id.in_(channel_ids))} + channels = [by_id[i] for i in channel_ids] return channels diff --git a/modules/videos/channel/test/test_lib.py b/modules/videos/channel/test/test_lib.py index a8a02f67..83dae4b4 100644 --- a/modules/videos/channel/test/test_lib.py +++ b/modules/videos/channel/test/test_lib.py @@ -165,6 +165,35 @@ async def test_search_channels_by_name(test_session, channel_factory, video_fact await assert_search('bar', ['foobar', 'Foo Bar', 'bar'], True) +@pytest.mark.asyncio +@pytest.mark.parametrize('order_by_video_count', [False, True]) +async def test_search_channels_by_name_reads_only_matching_rows(test_session, channel_factory, video_factory, + order_by_video_count): + """Matching Channels are found from their Collection names and indexes; only the matches' channel rows are read. + A channel row holds its yt-dlp info_json, so scanning every row took seconds from a cold disk cache.""" + foo = channel_factory(name='Foo') + channel_factory(name='Bar') + video_factory(channel_id=foo.id) + test_session.commit() + + statements = [] + connection = test_session.connection().connection.dbapi_connection + connection.set_trace_callback(lambda sql: statements.append(sql) if 'channel' in sql else None) + try: + channels = await lib.search_channels_by_name(test_session, 'foo', order_by_video_count=order_by_video_count) + finally: + connection.set_trace_callback(None) + assert [i.name for i in channels] == ['Foo'] + + for statement in statements: + if not statement.lstrip().upper().startswith(('SELECT', 'WITH')): + continue + plan = [i[3] for i in connection.execute(f'EXPLAIN QUERY PLAN {statement}')] + for step in plan: + if re.match(r'(SEARCH|SCAN) channel\b', step): + assert 'COVERING INDEX' in step or 'INTEGER PRIMARY KEY' in step, (statement, plan) + + @pytest.mark.asyncio async def test_tag_channel_existing(async_client, test_session, test_directory, channel_factory, tag_factory, video_factory, test_channels_config, await_switches): diff --git a/wrolpi/files/lib.py b/wrolpi/files/lib.py index b129fec2..54e13804 100644 --- a/wrolpi/files/lib.py +++ b/wrolpi/files/lib.py @@ -1912,14 +1912,19 @@ async def search_file_suggestion_count(session: Session, search_str: str, tag_na wheres, params = months_selector_to_where(wheres, params, months) wheres, params = date_range_to_where(wheres, params, from_year, to_year) - joins = "\n".join(joins) - wheres = 'WHERE ' + "\nAND ".join(wheres) if wheres else '' - stmt = f''' - SELECT COUNT(*) AS estimate - FROM file_group fg - {joins} - {wheres} - ''' + if deep_match and len(wheres) == 1: + # Only the search string: count inside the FTS index. Joining each match to its (large) file_group row is + # a random read per match, which is slow from a cold disk cache for a common word. + stmt = 'SELECT COUNT(*) AS estimate FROM file_group_fts WHERE file_group_fts MATCH :fts_match' + else: + joins = "\n".join(joins) + wheres = 'WHERE ' + "\nAND ".join(wheres) if wheres else '' + stmt = f''' + SELECT COUNT(*) AS estimate + FROM file_group fg + {joins} + {wheres} + ''' logger.debug(f'search_file_suggestion_count: {stmt} {params}') with session_curs(session) as curs: diff --git a/wrolpi/files/test/test_lib.py b/wrolpi/files/test/test_lib.py index 802840b6..88896274 100644 --- a/wrolpi/files/test/test_lib.py +++ b/wrolpi/files/test/test_lib.py @@ -2398,3 +2398,38 @@ def test_file_statistics_index_does_not_serve_mimetype_lookups(test_session, vid plan = [i[3] for i in connection.execute("EXPLAIN QUERY PLAN SELECT COUNT(*) FROM file_group WHERE mimetype = 'a/b'")] assert not any('file_group_statistics_idx' in i for i in plan), plan + + +@pytest.mark.asyncio +async def test_search_file_suggestion_count_counts_inside_fts(test_session, test_directory, make_files_structure): + """With only a search string, the estimates are counted from the FTS index alone: joining each match to its + (large) file_group row is a random read per match, which took most of a minute from a cold disk cache.""" + make_files_structure(['solar panel.txt', 'solar wiring.txt', 'garden.txt']) + for path, text in [('solar panel.txt', 'roof'), ('solar wiring.txt', 'the roof wiring'), ('garden.txt', 'roof')]: + file_group = FileGroup.from_paths(test_session, test_directory / path) + file_group.a_text = path + file_group.d_text = text + file_group.mimetype = 'text/plain' + test_session.commit() + + statements = [] + connection = test_session.connection().connection.dbapi_connection + connection.set_trace_callback(lambda sql: statements.append(sql) if 'estimate' in sql else None) + try: + assert await lib.search_file_suggestion_count(test_session, 'solar', [], []) == \ + dict(file_groups=2, file_groups_deep=2) + assert await lib.search_file_suggestion_count(test_session, 'roof', [], []) == \ + dict(file_groups=0, file_groups_deep=3) + finally: + connection.set_trace_callback(None) + + assert statements + for statement in statements: + plan = [i[3] for i in connection.execute(f'EXPLAIN QUERY PLAN {statement}')] + assert not any(re.match(r'(SEARCH|SCAN) (file_group|fg)\b', i) for i in plan), plan + + # Other filters still apply to the matches. + assert await lib.search_file_suggestion_count(test_session, 'roof', [], ['text']) == \ + dict(file_groups=0, file_groups_deep=3) + assert await lib.search_file_suggestion_count(test_session, 'roof', [], ['video']) == \ + dict(file_groups=0, file_groups_deep=0)