From 1f24503b9b8b148adfece8d08c454586b88b892e Mon Sep 17 00:00:00 2001 From: Alex Castillo Date: Fri, 13 Nov 2026 22:17:06 -0400 Subject: [PATCH] fix(query): match stopwords and weights before escaping tokens Co-Authored-By: Claude Sonnet 5.5 --- redisvl/utils/full_text_query_helper.py | 18 ++++++++++-------- tests/unit/test_query_types.py | 14 ++++++++++++++ 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/redisvl/utils/full_text_query_helper.py b/redisvl/utils/full_text_query_helper.py index c845065f5..5ec527b14 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 b40663784..a840fd9c0 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)