Skip to content

Commit 9cbe13a

Browse files
committed
Fix subject search counts
1 parent 84c1f31 commit 9cbe13a

1 file changed

Lines changed: 55 additions & 3 deletions

File tree

backend/main.py

Lines changed: 55 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1393,6 +1393,55 @@ def log_ai_chat(
13931393
)
13941394

13951395

1396+
def _compute_search_subject_counts(
1397+
con: sqlite3.Connection,
1398+
clean_q: str,
1399+
where_extra: str,
1400+
filter_params: list,
1401+
*,
1402+
has_images: bool,
1403+
) -> dict[str, int]:
1404+
count_where_extra = where_extra
1405+
if has_images:
1406+
count_where_extra += " AND c.text LIKE '%![%'"
1407+
1408+
like_params = [f"%{clean_q}%"] + list(filter_params)
1409+
fts_params = [clean_q] + list(filter_params)
1410+
1411+
try:
1412+
rows = con.execute(
1413+
f"""
1414+
SELECT subject, COUNT(*) AS cnt
1415+
FROM (
1416+
SELECT c.id, c.subject
1417+
FROM chunks c
1418+
WHERE c.text LIKE ? {count_where_extra}
1419+
UNION
1420+
SELECT c.id, c.subject
1421+
FROM chunks c
1422+
JOIN chunks_fts f ON c.id = f.rowid
1423+
WHERE chunks_fts MATCH ? {count_where_extra}
1424+
)
1425+
GROUP BY subject
1426+
ORDER BY cnt DESC, subject
1427+
""",
1428+
like_params + fts_params,
1429+
).fetchall()
1430+
except Exception:
1431+
rows = con.execute(
1432+
f"""
1433+
SELECT c.subject AS subject, COUNT(*) AS cnt
1434+
FROM chunks c
1435+
WHERE c.text LIKE ? {count_where_extra}
1436+
GROUP BY c.subject
1437+
ORDER BY cnt DESC, c.subject
1438+
""",
1439+
like_params,
1440+
).fetchall()
1441+
1442+
return {row["subject"]: row["cnt"] for row in rows}
1443+
1444+
13961445
@app.get("/api/search")
13971446
def search(
13981447
q: str = Query(..., min_length=1, max_length=200),
@@ -1523,9 +1572,12 @@ def search(
15231572
by_subject[s]["results"].append(result_item)
15241573
by_subject[s]["count"] += 1
15251574

1526-
subject_counts_counter = Counter(r["subject"] for r in all_rows)
1527-
subject_counts = dict(
1528-
sorted(subject_counts_counter.items(), key=lambda item: item[1], reverse=True)
1575+
subject_counts = _compute_search_subject_counts(
1576+
con,
1577+
clean_q,
1578+
where_extra,
1579+
filter_params,
1580+
has_images=has_images,
15291581
)
15301582

15311583
# Cross-subject hint

0 commit comments

Comments
 (0)