diff --git a/redisvl/utils/full_text_query_helper.py b/redisvl/utils/full_text_query_helper.py index c845065f..5ec527b1 100644 --- a/redisvl/utils/full_text_query_helper.py +++ b/redisvl/utils/full_text_query_helper.py @@ -111,19 +111,21 @@ def _tokenize_and_escape_query(self, user_query: str) -> str: """ escaper = TokenEscaper() + # Compare stopwords and weights against the raw token, then escape it: + # escaping first would turn "don't" into an escaped form that never matches. tokens = [ - escaper.escape( - token.strip().strip(",").replace("“", "").replace("”", "").lower() - ) + token.strip().strip(",").replace("“", "").replace("”", "").lower() for token in user_query.split() ] - token_list = [ - token for token in tokens if token and token not in self._stopwords - ] - for i, token in enumerate(token_list): + token_list = [] + for token in tokens: + if not token or token in self._stopwords: + continue + escaped = escaper.escape(token) if token in self._text_weights: - token_list[i] = f"{token}=>{{$weight:{self._text_weights[token]}}}" + escaped = f"{escaped}=>{{$weight:{self._text_weights[token]}}}" + token_list.append(escaped) if not token_list: raise ValueError("text string cannot be empty after removing stopwords") diff --git a/tests/unit/test_query_types.py b/tests/unit/test_query_types.py index b4066378..a840fd9c 100644 --- a/tests/unit/test_query_types.py +++ b/tests/unit/test_query_types.py @@ -287,6 +287,20 @@ def test_text_query_rejects_empty_tokenized_text(text, stopwords): TextQuery(text=text, text_field_name="body", stopwords=stopwords) +def test_text_query_filters_stopwords_with_apostrophe(): + query = TextQuery("don't panic", text_field_name="body") + assert "@body:(panic)" in str(query) + + +def test_text_query_applies_weights_to_punctuated_tokens(): + query = TextQuery( + "state-of-the-art search", + text_field_name="body", + text_weights={"state-of-the-art": 3}, + ) + assert "state\\-of\\-the\\-art=>{$weight:3}" in str(query) + + def test_text_query_keeps_stopwords_when_disabled(): query = TextQuery("the a an", text_field_name="body", stopwords=None) assert "@body:(the | a | an)" in str(query)