Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

fix(doclib): keep operator words in literal search queries

myhloli75a3c1329be4
diff --git a/docs/next/cli/mineru-library.md b/docs/next/cli/mineru-library.md
index 56af849b..8444df11 100644
--- a/docs/next/cli/mineru-library.md
+++ b/docs/next/cli/mineru-library.md
@@ -25,6 +25,8 @@ mineru search "keyword" --min-tier basic --type pdf
行为:
- 查询 `fts_contents`,未建立内容索引的文件不会命中正文检索。
+- 查询按普通检索词处理,`AND`、`OR`、`NOT`、`NEAR` 也作为检索词参与匹配。
+- 含标点的查询可以正常检索;标点通常不参与词项匹配。例如 `C++ guide` 也可能命中 `C guide` 或 `C# guide`。
- 按文档 SHA256 去重。
- 支持按 `file_type`、`tier`、`min_tier` 过滤。
- 返回文档大小、页数、命中片段、可空的 snippet 来源 tier,以及关联的全部 file aliases。
@@ -61,6 +63,7 @@ mineru find "report" --ext pdf --limit 50 --offset 100
行为:
- 查询 `fts_filenames` 和文件 metadata。
+- 查询词及标点的处理规则与 `search` 一致。
- 支持按 `ext` 过滤。
- 默认对最后一个查询词进行前缀匹配,例如 `bench` 可匹配 `bench1.pdf`;多词查询仅最后一词匹配前缀。显式 `bench*` 等价。
- 支持 `--limit/-n`(默认 50)和 `--offset`(默认 0);limit 必须为正,offset 必须非负。
diff --git a/mineru/doclib/core/fts.py b/mineru/doclib/core/fts.py
index 6d1e028e..86a45b5a 100644
--- a/mineru/doclib/core/fts.py
+++ b/mineru/doclib/core/fts.py
@@ -142,21 +142,23 @@ class FTSManager:
def _literal_query_tokens(tokenized: str) -> list[str]:
- """Quote search terms for FTS5 and keep prefix markers outside quotes."""
+ """将检索词转为 FTS5 引号字面量,前缀星号保留在引号外。
+
+ 字面量仍按既有 unicode61 索引分词,标点不保证参与匹配。
+ """
terms: list[str] = []
for token in tokenized.split():
term = token.rstrip("*")
prefix = term != token
if not term:
- # Jieba emits a trailing asterisk as a separate token.
+ # Jieba 会把末尾星号分成独立词项,需将其接回前一个有效词项。
if terms and not terms[-1].endswith("*"):
terms[-1] += "*"
continue
- if term.upper() in ("AND", "OR", "NOT", "NEAR"):
- continue
- # The unicode61 index treats letters, numbers, and private-use characters as token text.
+ # unicode61 索引以字母、数字和私用字符组成词项,跳过独立标点。
if not any(char.isalnum() or unicodedata.category(char) == "Co" for char in term):
continue
+ # 加引号后操作符同名词也只是普通检索词,无需过滤 AND、OR、NOT、NEAR。
escaped = term.replace('"', '""')
suffix = "*" if prefix else ""
terms.append(f'"{escaped}"{suffix}')
diff --git a/tests/unittest/test_doclib_find_pagination.py b/tests/unittest/test_doclib_find_pagination.py
index 234b69a7..32e0f9dd 100644
--- a/tests/unittest/test_doclib_find_pagination.py
+++ b/tests/unittest/test_doclib_find_pagination.py
@@ -18,6 +18,7 @@ from typer.testing import CliRunner
from mineru.cli.commands import search as search_commands
from mineru.cli.main import app
from mineru.doclib.client import DoclibClient
+from mineru.doclib.core import fts as fts_module
from mineru.doclib.core.db import DatabaseManager
from mineru.doclib.core.fts import FTSManager, tokenize_for_index
@@ -80,6 +81,7 @@ def test_doclib_search_accepts_punctuation_in_queries(tmp_path: Path) -> None:
"""使用真实 SQLite 索引验证普通标点不会使文件名或正文查询失效。"""
async def run() -> None:
+ """分别检验文件名前缀和正文显式前缀查询能容纳普通标点。"""
db, fts, _ = await _filename_library(tmp_path, ["C++ guide.pdf", "Python guide.pdf"])
try:
await fts.replace(sha256="a" * 64, tier="standard", text="C++ guide to AT&T services", title="", author="")
@@ -95,6 +97,72 @@ def test_doclib_search_accepts_punctuation_in_queries(tmp_path: Path) -> None:
asyncio.run(run())
[email protected]("use_jieba", [True, False], ids=["jieba", "no-jieba"])
+def test_doclib_search_keeps_operator_words_as_terms(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, use_jieba: bool) -> None:
+ """英文操作符同名词参与查询,单词和多词检索均不能被静默删除或解释为操作符。"""
+ if not use_jieba:
+ monkeypatch.setattr(fts_module, "jieba", None)
+
+ async def run() -> None:
+ """以真实索引和对照文档检查词项保留、大小写及显式前缀语义。"""
+ texts = ["near field", "far field", "OR logic", "logic", "rock and roll", "rock roll", "not included", "included"]
+ db, fts, _ = await _filename_library(tmp_path, [f"{text}.pdf" for text in texts])
+ try:
+ for file_id, text in enumerate(texts, start=1):
+ await fts.replace(sha256=f"{file_id:064x}", tier="standard", text=text, title="", author="")
+ queries = {
+ "AND": {5},
+ "and": {5},
+ "and*": {5},
+ "OR": {3},
+ "or": {3},
+ "or*": {3},
+ "NOT": {7},
+ "not": {7},
+ "not*": {7},
+ "NEAR": {1},
+ "near": {1},
+ "near*": {1},
+ "near field": {1},
+ "OR logic": {3},
+ "rock AND roll": {5},
+ "not included": {7},
+ "field OR logic": set(),
+ "near NOT field": set(),
+ }
+ for query, file_ids in queries.items():
+ assert {row["file_id"] for row in await fts.search_filenames(query)} == file_ids, query
+ assert {row["sha256"] for row in await fts.search(query)} == {f"{file_id:064x}" for file_id in file_ids}, query
+ finally:
+ await db.close()
+
+ asyncio.run(run())
+
+
[email protected]("use_jieba", [True, False], ids=["jieba", "no-jieba"])
+def test_doclib_search_keeps_unicode61_punctuation_semantics(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, use_jieba: bool
+) -> None:
+ """查询转义只消除语法错误,现有索引仍不通过加号或井号区分 C、C++ 和 C#。"""
+ if not use_jieba:
+ monkeypatch.setattr(fts_module, "jieba", None)
+
+ async def run() -> None:
+ """加入相同词项的标点对照样本,明确文件名和正文搜索的匹配边界。"""
+ texts = ["C++ guide", "C guide", "C# guide", "Python guide"]
+ db, fts, _ = await _filename_library(tmp_path, [f"{text}.pdf" for text in texts])
+ try:
+ for file_id, text in enumerate(texts, start=1):
+ await fts.replace(sha256=f"{file_id:064x}", tier="standard", text=text, title="", author="")
+ for query in ("C++ guide", "C# guide", "C guide"):
+ assert {row["file_id"] for row in await fts.search_filenames(query)} == {1, 2, 3}, query
+ assert {row["sha256"] for row in await fts.search(query)} == {f"{file_id:064x}" for file_id in (1, 2, 3)}, query
+ finally:
+ await db.close()
+
+ asyncio.run(run())
+
+
def test_find_paginates_all_candidates_in_stable_order(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""六百余条同分候选跨过旧上限与元信息批次,每页无遗漏且总数不随 limit 变化。"""