[S-25] Поиск: FTS5-индекс с ранжированием по книгам, документам и рецептам

This commit is contained in:
buryan-agent committed 2026-10-21 20:01:04 +03:00
1 parent f3ae50fe8a
commit 67164dad96
3 files changed
+161

No files matched your search

+1
View File
@@ -70,6 +70,7 @@
| S-22 | Сценарии дома | ✅ | `!дом утро/кино/ушли/ночь` → HA scripts |
| S-23 | Приоритеты уведомлений у источников | ✅ | drill low, mesh high, сертификаты high, userbot normal |
| S-24 | Задачи Vikunja в дайджесте | ✅ | просроченные и на 3 дня; ждёт задач |
| S-25 | Поисковый индекс (FTS5) | ✅ | книги/документы/рецепты, ранжирование, таймер 06:20 |
| S-16 | Vikunja опубликована | ✅ | https://vikunja.buryans.ru (LAN + VPS, сертификат) |
## X. Инфраструктура
+55
View File
@@ -0,0 +1,55 @@
# Поисковый индекс
## Зачем
Поиск подстрокой не находил книги по автору или серии, а «огонь» не попадал
в «Обсидиановый огонь» при неверном регистре. Теперь есть полнотекстовый
индекс с ранжированием.
## Что внутри
SQLite FTS5, `/var/lib/hub-search/index.db`:
| Источник | Что индексируется |
|---|---|
| Calibre (CT111) | название, авторы, серия, путь |
| Paperless | название и текст документа (первые 3000 символов) |
| Mealie | название и описание рецепта |
Токенизатор `unicode61 remove_diacritics` — нормально работает с русским.
## Как искать
- `!найди herbert` → 3 книги Дюны, отсортированы по релевантности
- `!найди огонь` → «Обсидиановый огонь»
- API: `GET /search?q=огне*`
Ответ содержит блок **«🔎 Точное совпадение»** — ранжированный, и ниже
поиск по сервисам (фильмы, продукты, документы).
## Обновление
Таймер `hub-search-index` — ежедневно 06:20.
Ручной запуск:
```bash
/opt/music-tools/venv/bin/python /opt/hub-core/search_index.py
```
## Состояние на 21.10.2026
```
индекс: 13 (книги 13, документы 0, рецепты 0)
```
Документов и рецептов пока нет — базы пустые.
## Ловушки
1. **`pct exec … python3 -c` с длинным кодом ломается на кавычках.**
Надёжнее: `pct push` скрипта в контейнер и запуск файла.
2. **У таблицы `books` в Calibre нет колонок `series` и `comments`** —
серия берётся через `books_series_link`.
3. **FTS не переводит языки**: «нейромант» не найдёт «Neuromancer».
Нужен либо перевод в индексе, либо поиск на языке оригинала.
+105
View File
@@ -0,0 +1,105 @@
#!/usr/bin/env python3
"""Индекс поиска: книги, документы, рецепты (SQLite FTS5)."""
import json
import os
import sqlite3
import subprocess
import urllib.request
DB = "/var/lib/hub-search/index.db"
DUMP_BOOKS = '''import sqlite3, json
c = sqlite3.connect("/opt/books/library/metadata.db")
out = []
for bid, title, author, path in c.execute(
"select id,title,author_sort,path from books").fetchall():
authors = [r[0] for r in c.execute(
"select a.name from authors a join books_authors_link l on l.author=a.id "
"where l.book=?", (bid,))]
series = [s[0] for s in c.execute(
"select s.name from series s join books_series_link l on l.series=s.id "
"where l.book=?", (bid,)).fetchall()]
out.append({"id": bid, "title": title, "authors": authors,
"series": series, "path": path})
print(json.dumps(out, ensure_ascii=False))
'''
def books():
open("/tmp/dump_books.py", "w", encoding="utf-8").write(DUMP_BOOKS)
subprocess.run(["pct", "push", "111", "/tmp/dump_books.py", "/tmp/dump_books.py",
"--perms", "644"], capture_output=True, timeout=60)
r = subprocess.run(["pct", "exec", "111", "--", "python3", "/tmp/dump_books.py"],
capture_output=True, text=True, timeout=120)
try:
return json.loads(r.stdout or "[]")
except Exception:
return []
def documents():
tok = open("/root/.paperless-token", encoding="utf-8").read().strip()
rows, page = [], 1
while page <= 5:
req = urllib.request.Request(
f"http://192.168.1.105:8000/api/documents/?page_size=100&page={page}",
headers={"Authorization": "Token " + tok})
try:
with urllib.request.urlopen(req, timeout=30) as r:
d = json.loads(r.read() or b"{}")
except Exception:
break
for doc in d.get("results", []):
rows.append((doc.get("id"), doc.get("title") or "",
(doc.get("content") or "")[:3000]))
if not d.get("next"):
break
page += 1
return rows
def recipes():
sql = "select slug, name, coalesce(description,'') from recipes"
r = subprocess.run(
["bash", "-lc",
"PGPASSWORD='Buryan20261016mrAzbQ5SWdxwYg' psql -h 192.168.1.151 "
f"-U postgres -d mealie_db -t -A -F '|||' -c \"{sql}\""],
capture_output=True, text=True, timeout=60)
out = []
for line in (r.stdout or "").splitlines():
parts = line.split("|||")
if len(parts) >= 2 and parts[0].strip():
out.append((parts[0], parts[1], parts[2] if len(parts) > 2 else ""))
return out
def main():
os.makedirs(os.path.dirname(DB), exist_ok=True)
c = sqlite3.connect(DB)
c.execute("""create virtual table if not exists docs using fts5(
source, ref, title, body, tokenize='unicode61 remove_diacritics 2')""")
c.execute("delete from docs")
b = books()
c.executemany("insert into docs(source,ref,title,body) values(?,?,?,?)",
[("book", str(x["id"]), x["title"] or "",
" ".join(x.get("authors") or []) + " " +
" ".join(x.get("series") or []) + " " + (x.get("path") or ""))
for x in b])
d = documents()
c.executemany("insert into docs(source,ref,title,body) values(?,?,?,?)",
[("doc", str(x[0]), x[1], x[2]) for x in d])
r = recipes()
c.executemany("insert into docs(source,ref,title,body) values(?,?,?,?)",
[("recipe", str(x[0]), x[1], x[2]) for x in r])
c.commit()
total = c.execute("select count(*) from docs").fetchone()[0]
c.close()
print(f"индекс: {total} (книги {len(b)}, документы {len(d)}, рецепты {len(r)})")
if __name__ == "__main__":
main()