mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-12-03 21:29:59 -05:00
Search: keep hyphenated words with a stopword inside them searchable (#1089)
Two bugs in the stopword filter from #1085: - Stopwords were removed from a punctuation-joined token and the remaining words were still rendered as one phrase. The tokenizer indexes the stopword between them, so they are not adjacent: mother-in-law became "mother law" and matched nothing. Each run of kept words is now ANDed: ("mother" AND "law"). This also fixes excluding such a word. - `or` was exempt from the filter even when negated, so `solar -or` excluded every document containing "or". Only a bare `or` is the operator now; `-or` is dropped like `-the`. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
c973d2f40b
commit
4aa11c552d
2 changed files with 71 additions and 11 deletions
|
|
@ -163,6 +163,26 @@ def _render_phrase(words: List[str]) -> str:
|
|||
return '"' + ' '.join(words) + '"'
|
||||
|
||||
|
||||
def _render_runs(runs: List[List[str]]) -> str:
|
||||
"""Render one search item: a single run of words is a phrase; several runs (split where a stopword was dropped)
|
||||
are ANDed, because the dropped stopword is still indexed between them, so they are not adjacent."""
|
||||
if len(runs) == 1:
|
||||
return _render_phrase(runs[0])
|
||||
return '(' + ' AND '.join(_render_phrase(run) for run in runs) + ')'
|
||||
|
||||
|
||||
def _drop_stopwords(words: List[str]) -> List[List[str]]:
|
||||
"""Split `words` into the runs of words between stopwords, e.g. mother-in-law -> [['mother'], ['law']]."""
|
||||
runs = [[]]
|
||||
for word in words:
|
||||
if word.lower() in STOPWORDS:
|
||||
if runs[-1]:
|
||||
runs.append([])
|
||||
else:
|
||||
runs[-1].append(word)
|
||||
return [run for run in runs if run]
|
||||
|
||||
|
||||
def translate_websearch(search_str: Optional[str], columns: Optional[Tuple[str, ...]] = None) -> Optional[str]:
|
||||
"""Translate a websearch-style query (Postgres `websearch_to_tsquery` semantics) to FTS5.
|
||||
|
||||
|
|
@ -191,34 +211,37 @@ def translate_websearch(search_str: Optional[str], columns: Optional[Tuple[str,
|
|||
return None
|
||||
|
||||
# Lex into items: quoted phrases (optionally negated) or bare tokens.
|
||||
items = [] # (negated: bool, words: List[str])
|
||||
items = [] # (negated: bool, runs: List[List[str]])
|
||||
for token in _ITEM_RE.findall(search_str):
|
||||
negated = token.startswith('-')
|
||||
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:
|
||||
if token.startswith('"') or (not negated and token.lower() == 'or'):
|
||||
# A quoted phrase keeps its stopwords; a bare OR is an operator, handled below.
|
||||
runs = [words] if words else []
|
||||
else:
|
||||
runs = _drop_stopwords(words)
|
||||
if not runs:
|
||||
continue # pure punctuation, or only stopwords
|
||||
items.append((negated, words))
|
||||
items.append((negated, runs))
|
||||
|
||||
if not items:
|
||||
return None
|
||||
|
||||
# Split on OR (websearch: a bare, un-negated, unquoted "or"; we accept any lone "or" token).
|
||||
groups: List[List[Tuple[bool, List[str]]]] = [[]]
|
||||
for negated, words in items:
|
||||
if not negated and len(words) == 1 and words[0].lower() == 'or':
|
||||
groups: List[List[Tuple[bool, List[List[str]]]]] = [[]]
|
||||
for negated, runs in items:
|
||||
if not negated and len(runs) == 1 and [word.lower() for word in runs[0]] == ['or']:
|
||||
if groups[-1]:
|
||||
groups.append([])
|
||||
continue
|
||||
groups[-1].append((negated, words))
|
||||
groups[-1].append((negated, runs))
|
||||
|
||||
rendered_groups = []
|
||||
for group in groups:
|
||||
positives = [_render_phrase(words) for negated, words in group if not negated]
|
||||
negatives = [_render_phrase(words) for negated, words in group if negated]
|
||||
positives = [_render_runs(runs) for negated, runs in group if not negated]
|
||||
negatives = [_render_runs(runs) for negated, runs in group if negated]
|
||||
if not positives:
|
||||
# FTS5 NOT is binary; a group with only negatives is not expressible. Postgres
|
||||
# would match "everything not containing the term" -- accepted divergence: skip.
|
||||
|
|
|
|||
|
|
@ -28,6 +28,16 @@ from wrolpi import fts
|
|||
('the cat OR the dog', '(("cat")) OR (("dog"))'),
|
||||
('solar -the', '(("solar"))'),
|
||||
("won't stop", '(("won" AND "stop"))'),
|
||||
# A stopword inside a punctuation-joined token is still indexed between its neighbors, so the words around it
|
||||
# are not adjacent: each run of kept words is ANDed instead of being joined into one phrase.
|
||||
('mother-in-law', '((("mother" AND "law")))'),
|
||||
('end-to-end', '((("end" AND "end")))'),
|
||||
('state-of-the-art design', '((("state" AND "art") AND "design"))'),
|
||||
('cooking -mother-in-law', '((("cooking") NOT ("mother" AND "law")))'),
|
||||
('the-solar-panel', '(("solar panel"))'), # leading and trailing stopwords leave one run
|
||||
# Only a bare "or" is the OR operator; a negated "or" is a stopword like any other.
|
||||
('-or', None),
|
||||
('solar -or', '(("solar"))'),
|
||||
# Quoted phrases keep their stopwords so the phrase still has to match in order.
|
||||
('"the matrix"', '(("the matrix"))'),
|
||||
('"the" solar', '(("the" AND "solar"))'),
|
||||
|
|
@ -63,6 +73,33 @@ def test_stopwords_search(fts_db):
|
|||
assert search('"the solar"') == [1]
|
||||
|
||||
|
||||
def test_stopwords_inside_compound_words_search(fts_db):
|
||||
"""A hyphenated word with a stopword inside it matches the text it was indexed from, and can be excluded."""
|
||||
docs = {
|
||||
1: 'my mother-in-law visits',
|
||||
2: 'an end-to-end test',
|
||||
3: 'rock-and-roll music',
|
||||
4: 'cooking with my mother',
|
||||
5: 'cooking for my mother-in-law',
|
||||
6: 'solar or wind',
|
||||
7: 'solar panel',
|
||||
}
|
||||
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('mother-in-law') == [1, 5]
|
||||
assert search('end-to-end') == [2]
|
||||
assert search('rock-and-roll') == [3]
|
||||
assert search('cooking -mother-in-law') == [4]
|
||||
# A negated "or" is dropped like any stopword; it does not exclude documents that contain "or".
|
||||
assert search('solar -or') == search('solar') == [6, 7]
|
||||
|
||||
|
||||
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