mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-12-03 21:29:59 -05:00
Search: drop stopwords from unquoted terms, as Postgres did (#1085)
Postgres' english websearch_to_tsquery dropped stopwords; FTS5 indexes them. A stopword matches most of the library, so a search containing one read its whole doclist (slow on a cold HDD) and only found files that happened to contain it. translate_websearch now drops Postgres' english stopword list from unquoted terms; quoted phrases keep them. A search with nothing left to search (stopwords or punctuation only) now matches nothing in archive, video and doc search too, as files search, the search estimates and Postgres already did, instead of listing everything. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
a61d528832
commit
45b52a698e
8 changed files with 107 additions and 11 deletions
|
|
@ -1323,9 +1323,11 @@ def search_archives(session: Session, search_str: str, domain: str, limit: int,
|
|||
fts_join = ''
|
||||
headline_columns = ''
|
||||
# The fast (deep=False) search only matches the a/b/c FTS columns; deep also matches d
|
||||
# (page contents). `file_group_search` returns None when the search string is unusable, in
|
||||
# which case we behave as if no search was requested.
|
||||
# (page contents). `file_group_search` returns None when the search string has nothing to search
|
||||
# (punctuation or stopwords only); that matches nothing, like an empty websearch_to_tsquery did.
|
||||
file_group_search = fts.file_group_search(search_str, deep=deep) if search_str else None
|
||||
if search_str and not file_group_search:
|
||||
return [], 0
|
||||
if file_group_search:
|
||||
# A search_str was provided by the user, modify the query to filter by it. Rank and
|
||||
# snippets come from a subquery (FTS5 auxiliary functions cannot mix with some SELECT shapes).
|
||||
|
|
|
|||
|
|
@ -80,9 +80,16 @@ async def test_archives_search(test_session, archive_directory, archive_factory,
|
|||
data = {'search_str': 'baz', 'domain': 'example.org', 'deep': True}
|
||||
await check_results(async_client, data, [3, ])
|
||||
|
||||
# 1's title contains "my". Postgres ignored this stopword; FTS5 has no stopwords, so it matches.
|
||||
# 1's title contains "my", a stopword. A search of only stopwords matches nothing (as Postgres did), rather
|
||||
# than listing every archive.
|
||||
data = {'search_str': 'my', 'deep': True}
|
||||
await check_results(async_client, data, [1, ])
|
||||
await check_results(async_client, data, [])
|
||||
# "my archive" is a search for "archive", which all three titles contain.
|
||||
request, response = await async_client.post('/api/archive/search',
|
||||
content=json.dumps({'search_str': 'archive', 'deep': True}))
|
||||
archive_ids = [i['id'] for i in response.json['file_groups']]
|
||||
assert len(archive_ids) == 3
|
||||
await check_results(async_client, {'search_str': 'my archive', 'deep': True}, archive_ids)
|
||||
|
||||
# 3's title contains "third", found by the default (fast) search and the deep search.
|
||||
data = {'search_str': 'third'}
|
||||
|
|
|
|||
|
|
@ -385,6 +385,9 @@ def _search_docs(session: Session, search_str=None, author=None, subject=None, l
|
|||
# Deep search matches all FTS columns (including d_text, the document contents); the default matches only
|
||||
# the much smaller a/b/c columns.
|
||||
match = fts.translate_websearch(search_str, None if deep else fts.ABC_COLUMNS) if search_str else None
|
||||
if search_str and match is None:
|
||||
# Nothing to search (punctuation or stopwords only); match nothing, like an empty websearch_to_tsquery.
|
||||
return [], 0
|
||||
|
||||
query = session.query(FileGroup).options(*FileGroup.json_options()).join(Doc, Doc.file_group_id == FileGroup.id)
|
||||
|
||||
|
|
|
|||
|
|
@ -162,6 +162,23 @@ async def test_docs_search_title_order(async_client, test_session, doc_factory):
|
|||
assert await search_ids(order_by='-title') == [naturalist, bobby, awls, alps, untitled]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_docs_search_stopwords(async_client, test_session, doc_factory):
|
||||
"""Stopwords are dropped from a search; a search of only stopwords matches nothing (as Postgres did)."""
|
||||
solar, garden = doc_factory(), doc_factory()
|
||||
solar.file_group.title = solar.file_group.a_text = 'the solar panel'
|
||||
garden.file_group.title = garden.file_group.a_text = 'the garden'
|
||||
test_session.commit()
|
||||
|
||||
async def search_ids(**body):
|
||||
request, response = await async_client.post('/api/docs/search', content=json.dumps(body))
|
||||
assert response.status_code == HTTPStatus.OK, response.json
|
||||
return [i['id'] for i in response.json['file_groups']]
|
||||
|
||||
assert await search_ids(search_str='the') == []
|
||||
assert await search_ids(search_str='the solar') == [solar.file_group_id]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_docs_search_defaults_to_rank(async_client, test_session, doc_factory):
|
||||
"""A Docs search without an order puts the most relevant Docs first."""
|
||||
|
|
|
|||
|
|
@ -685,7 +685,7 @@ async def test_search_videos_default_page_pagination(test_session, video_factory
|
|||
await assert_video_search(order_by='-published_datetime', assert_total=6)
|
||||
assert fast_path.called, 'the unfiltered date-ordered page should take the fast path'
|
||||
fast_path.reset_mock()
|
||||
await assert_video_search(order_by='-published_datetime', search_str='a', assert_total=1)
|
||||
await assert_video_search(order_by='-published_datetime', search_str='b', assert_total=1)
|
||||
await assert_video_search(order_by='-size', assert_total=6)
|
||||
assert not fast_path.called, 'searches and other orders use the generic query'
|
||||
|
||||
|
|
@ -786,3 +786,14 @@ async def test_video_json_does_not_read_info_json(async_client, test_session, vi
|
|||
request, response = await async_client.get(f'/api/videos/{video.file_group_id}')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert 'description' not in response.json['file_group']['video']
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_videos_stopwords(test_session, video_factory, assert_video_search):
|
||||
"""Stopwords are dropped from a search; a search of only stopwords matches nothing (as Postgres did)."""
|
||||
solar = video_factory(title='the solar panel', with_video_file=True)
|
||||
video_factory(title='the garden', with_video_file=True)
|
||||
test_session.commit()
|
||||
|
||||
await assert_video_search(search_str='the', assert_ids=[])
|
||||
await assert_video_search(search_str='the solar', assert_ids=[solar.id])
|
||||
|
|
|
|||
|
|
@ -227,6 +227,9 @@ def search_videos(
|
|||
# Rank/snippets come from a subquery so they stay valid if a caller adds window functions.
|
||||
fts_search = fts.file_group_search_join(search_str, deep=deep, headlines=bool(headline)) \
|
||||
if search_str else None
|
||||
if search_str and not fts_search:
|
||||
# Nothing to search (punctuation or stopwords only); match nothing, like an empty websearch_to_tsquery.
|
||||
return [], 0
|
||||
if fts_search:
|
||||
select_columns = f'fg.id, {fts_search.rank_select}'
|
||||
joins.append(fts_search.join)
|
||||
|
|
|
|||
|
|
@ -144,6 +144,19 @@ FTS_TABLE_PREFIXES = ('file_group_fts', 'doc_section_fts', 'repository_fts')
|
|||
_ITEM_RE = re.compile(r'-?"[^"]*"?|\S+')
|
||||
_WORD_RE = re.compile(r'\w+', re.UNICODE)
|
||||
|
||||
# Postgres' english stopword list (snowball `english.stop`), which `websearch_to_tsquery('english', ...)` dropped
|
||||
# from every query. FTS5 indexes these words, so unquoted terms drop them at query time: a stopword matches most
|
||||
# of the library, which made it slow (its doclist is read in full) and narrowed results to files that happen to
|
||||
# contain it. Quoted phrases keep them.
|
||||
STOPWORDS = frozenset('''
|
||||
i me my myself we our ours ourselves you your yours yourself yourselves he him his himself she her hers herself
|
||||
it its itself they them their theirs themselves what which who whom this that these those am is are was were be
|
||||
been being have has had having do does did doing a an the and but if or because as until while of at by for with
|
||||
about against between into through during before after above below to from up down in out on off over under
|
||||
again further then once here there when where why how all any both each few more most other some such no nor
|
||||
not only own same so than too very s t can will just don should now
|
||||
'''.split())
|
||||
|
||||
|
||||
def _render_phrase(words: List[str]) -> str:
|
||||
"""Render sanitized words as a (safe) FTS5 phrase: every term is double-quoted."""
|
||||
|
|
@ -154,7 +167,7 @@ def translate_websearch(search_str: Optional[str], columns: Optional[Tuple[str,
|
|||
"""Translate a websearch-style query (Postgres `websearch_to_tsquery` semantics) to FTS5.
|
||||
|
||||
Supported semantics: bare words are ANDed, "double quotes" form phrases, `-term` excludes,
|
||||
a bare OR separates groups. All user tokens end up inside double-quotes so no FTS5 syntax
|
||||
a bare OR separates groups. Unquoted `STOPWORDS` are dropped, as Postgres did. All user tokens end up inside double-quotes so no FTS5 syntax
|
||||
can be injected; the output either parses or is None (nothing usable to search).
|
||||
|
||||
Punctuation is stripped from terms (`C++` -> `"C"`, `e.g.` -> the phrase `"e g"`). This is
|
||||
|
|
@ -166,11 +179,13 @@ def translate_websearch(search_str: Optional[str], columns: Optional[Tuple[str,
|
|||
`columns` restricts matching to the given FTS columns (the fast/abc path).
|
||||
|
||||
>>> translate_websearch('two words')
|
||||
'("two" AND "words")'
|
||||
'(("two" AND "words"))'
|
||||
>>> translate_websearch('"a phrase" -excluded')
|
||||
'(("a phrase") NOT "excluded")'
|
||||
'((("a phrase") NOT "excluded"))'
|
||||
>>> translate_websearch('cat OR dog')
|
||||
'("cat") OR ("dog")'
|
||||
'(("cat")) OR (("dog"))'
|
||||
>>> translate_websearch('the cat') == translate_websearch('cat')
|
||||
True
|
||||
"""
|
||||
if not search_str or not search_str.strip():
|
||||
return None
|
||||
|
|
@ -182,8 +197,10 @@ def translate_websearch(search_str: Optional[str], columns: Optional[Tuple[str,
|
|||
if negated:
|
||||
token = token[1:]
|
||||
words = _WORD_RE.findall(token)
|
||||
if not token.startswith('"') and token.lower() != 'or': # a lone OR is an operator, handled below
|
||||
words = [word for word in words if word.lower() not in STOPWORDS]
|
||||
if not words:
|
||||
continue # pure punctuation
|
||||
continue # pure punctuation, or only stopwords
|
||||
items.append((negated, words))
|
||||
|
||||
if not items:
|
||||
|
|
|
|||
|
|
@ -17,7 +17,20 @@ from wrolpi import fts
|
|||
('or', None), # a lone OR is not a search
|
||||
('cat OR OR dog', '(("cat")) OR (("dog"))'),
|
||||
('OR cat', '(("cat"))'),
|
||||
("don't", '(("don t"))'), # punctuation-joined tokens become a phrase, like websearch
|
||||
("don't", None), # punctuation-joined tokens become a phrase; "don" and "t" are both stopwords
|
||||
("o'brien", '(("o brien"))'), # punctuation-joined tokens become a phrase, like websearch
|
||||
# Stopwords are dropped from unquoted terms, like Postgres' english websearch_to_tsquery.
|
||||
('the', None),
|
||||
('The', None),
|
||||
('the solar panel', '(("solar" AND "panel"))'),
|
||||
('how to fish', '(("fish"))'),
|
||||
('to be OR not to be', None),
|
||||
('the cat OR the dog', '(("cat")) OR (("dog"))'),
|
||||
('solar -the', '(("solar"))'),
|
||||
("won't stop", '(("won" AND "stop"))'),
|
||||
# Quoted phrases keep their stopwords so the phrase still has to match in order.
|
||||
('"the matrix"', '(("the matrix"))'),
|
||||
('"the" solar', '(("the" AND "solar"))'),
|
||||
('!!! ...', None), # pure punctuation
|
||||
('', None),
|
||||
(None, None),
|
||||
|
|
@ -27,6 +40,29 @@ def test_translate_websearch(search_str, expected):
|
|||
assert fts.translate_websearch(search_str) == expected
|
||||
|
||||
|
||||
def test_stopwords_match_postgres_english():
|
||||
"""The stopword list is Postgres' english list (snowball), so searches behave as they did before SQLite."""
|
||||
assert len(fts.STOPWORDS) == 127
|
||||
assert {'the', 'and', 'of', 'to', 'a', 'is', 'not'} <= fts.STOPWORDS
|
||||
assert not {'solar', 'fish', 'matrix', 'water'} & fts.STOPWORDS
|
||||
|
||||
|
||||
def test_stopwords_search(fts_db):
|
||||
"""A stopword in a query no longer narrows the results: documents that lack it still match."""
|
||||
docs = {1: 'the solar panel', 2: 'solar panel wiring', 3: 'the garden'}
|
||||
for rowid, text in docs.items():
|
||||
fts_db.execute('INSERT INTO file_group (id, a_text) VALUES (?, ?)', (rowid, text))
|
||||
|
||||
def search(query):
|
||||
match = fts.translate_websearch(query)
|
||||
return [row[0] for row in fts_db.execute(
|
||||
'SELECT rowid FROM file_group_fts WHERE file_group_fts MATCH ? ORDER BY rowid', (match,))]
|
||||
|
||||
assert search('the solar panel') == [1, 2]
|
||||
assert search('solar panel') == [1, 2]
|
||||
assert search('"the solar"') == [1]
|
||||
|
||||
|
||||
def test_translate_websearch_columns():
|
||||
result = fts.translate_websearch('word', columns=fts.ABC_COLUMNS)
|
||||
assert result == '{a_text b_text c_text} : ((("word")))'
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue