INNER CODE UNIT · Python
query
kangarooking/cangjie-skill · scripts/build_index.py:53
def query(db_path: Path, q: str, limit: int, neighbors: int) -> int:
con = sqlite3.connect(db_path)
terms = " OR ".join(f'"{t}"' for t in cjk_bigram(q).split())
rows = con.execute(
"SELECT chunk_id FROM chunks_fts WHERE chunks_fts MATCH ? ORDER BY rank LIMIT ?", (terms, limit)
).fetchall()
if not rows:
print("(无命中;建议放宽查询词或回退全量扫描)")
return 0
seen: set[int] = set()
for (chunk_id,) in rows:
(seq,) = con.execute("SELECT seq FROM chunks WHERE chunk_id=?", (chunk_id,)).fetchone()
for s in range(max(0, seq - neighbors), seq + neighbors + 1):
seen.add(s)
for seq in sorted(seen):
row = con.execute("SELECT chunk_id, heading_path, text FROM chunks WHERE seq=?", (seq,)).fetchone()
if row:
cid, hp, text = row