From c18f7965a04e7702a85d39aec799cc25e301027a Mon Sep 17 00:00:00 2001 From: Alex Castillo Date: Fri, 6 Nov 2026 04:38:28 -0400 Subject: [PATCH 1/3] fix(query): reject TextQuery text emptied by stopwords --- redisvl/query/query.py | 27 +++++++++------------------ tests/unit/test_text_query_weights.py | 25 +++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 18 deletions(-) diff --git a/redisvl/query/query.py b/redisvl/query/query.py index 2beccff26..3dc6c6377 100644 --- a/redisvl/query/query.py +++ b/redisvl/query/query.py @@ -5,9 +5,9 @@ from redisvl.query.filter import FilterExpression, intersect_with_filter, render_filter from redisvl.redis.utils import array_to_buffer +from redisvl.utils.full_text_query_helper import FullTextQueryHelper from redisvl.utils.log import get_logger from redisvl.utils.stopwords import get_stopwords -from redisvl.utils.token_escaper import TokenEscaper from redisvl.utils.utils import denorm_cosine_distance logger = get_logger(__name__) @@ -1350,7 +1350,8 @@ def __init__( within the query text. Defaults to None, as no modifications will be made to the text_scorer score. Raises: - ValueError: if stopwords language string cannot be loaded. + ValueError: If the text is empty after stopword filtering, or the + stopwords language string cannot be loaded. TypeError: If stopwords is not a valid iterable set of strings. """ self._text = text @@ -1359,6 +1360,8 @@ def __init__( self._num_results = num_results self._set_stopwords(stopwords) + # Reject empty text before the query reaches Redis. + self._tokenize_and_escape_query(self._text) self.set_filter(filter_expression) if params: @@ -1420,22 +1423,10 @@ def _tokenize_and_escape_query(self, user_query: str) -> str: Raises: ValueError: If the text string becomes empty after stopwords are removed. """ - escaper = TokenEscaper() - - tokens = [ - escaper.escape( - 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): - if token in self._text_weights: - token_list[i] = f"{token}=>{{$weight:{self._text_weights[token]}}}" - - return " | ".join(token_list) + helper = FullTextQueryHelper( + stopwords=self._stopwords, text_weights=self._text_weights + ) + return helper._tokenize_and_escape_query(user_query) def _parse_field_weights( self, field_spec: str | dict[str, float] diff --git a/tests/unit/test_text_query_weights.py b/tests/unit/test_text_query_weights.py index 081573463..ee570eb20 100644 --- a/tests/unit/test_text_query_weights.py +++ b/tests/unit/test_text_query_weights.py @@ -120,3 +120,28 @@ def test_set_field_weights_method(): query_string = str(text_query) assert "$weight: 5.0" in query_string or "$weight:5.0" in query_string assert "$weight: 2.0" in query_string or "$weight:2.0" in query_string + + +@pytest.mark.parametrize( + "text, stopwords", + [("the a an", "english"), ("only", {"only"}), (" ", None), (", “ ”", None)], +) +def test_text_query_rejects_empty_tokenized_text(text, stopwords): + with pytest.raises( + ValueError, match="text string cannot be empty after removing stopwords" + ): + TextQuery(text=text, text_field_name="body", stopwords=stopwords) + + +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) + + +def test_text_query_preserves_escaping_and_updated_weights(): + query = TextQuery( + "the HELLO, redis-vl", text_field_name="body", text_weights={"hello": 2.0} + ) + assert r"@body:(hello=>{$weight:2.0} | redis\-vl)" in str(query) + query.set_text_weights({"hello": 3.0}) + assert r"@body:(hello=>{$weight:3.0} | redis\-vl)" in str(query) From 82373170c45815050b276eb5c96aa2d23c67fdec Mon Sep 17 00:00:00 2001 From: Alex Castillo Date: Tue, 10 Nov 2026 06:32:40 -0400 Subject: [PATCH 2/3] fix(query): reuse TextQuery full-text helper and validation result --- redisvl/query/query.py | 66 +++++---------------------- tests/unit/test_query_types.py | 55 ++++++++++++++++++++++ tests/unit/test_text_query_weights.py | 18 +------- 3 files changed, 67 insertions(+), 72 deletions(-) diff --git a/redisvl/query/query.py b/redisvl/query/query.py index 3dc6c6377..5d349388a 100644 --- a/redisvl/query/query.py +++ b/redisvl/query/query.py @@ -7,7 +7,6 @@ from redisvl.redis.utils import array_to_buffer from redisvl.utils.full_text_query_helper import FullTextQueryHelper from redisvl.utils.log import get_logger -from redisvl.utils.stopwords import get_stopwords from redisvl.utils.utils import denorm_cosine_distance logger = get_logger(__name__) @@ -1356,20 +1355,22 @@ def __init__( """ self._text = text self._field_weights = self._parse_field_weights(text_field_name) - self._text_weights = self._parse_text_weights(text_weights) + self._ft_helper = FullTextQueryHelper( + stopwords=stopwords, text_weights=text_weights + ) self._num_results = num_results - self._set_stopwords(stopwords) - # Reject empty text before the query reaches Redis. - self._tokenize_and_escape_query(self._text) self.set_filter(filter_expression) + if not text.strip(): + raise ValueError("text string cannot be empty") if params: self._params = params # Initialize the base query super().__init__("*") - self._built_query_string = None + # Validate once and retain the result for the first query build. + self._built_query_string = self._build_query_string() # handle query settings self.scorer(text_scorer) @@ -1389,29 +1390,7 @@ def __init__( @property def stopwords(self): - return self._stopwords - - def _set_stopwords(self, stopwords: str | set[str] | None = "english"): - """Set the stopwords to use in the query. - Args: - stopwords (Optional[Union[str, Set[str]]]): The stopwords to use. If a string - such as "english" "german" is provided then a default set of stopwords for that - language will be used. if a list, set, or tuple of strings is provided then those - will be used as stopwords. Defaults to "english". if set to "None" then no stopwords - will be removed. - Raises: - TypeError: If the stopwords are not a set, list, or tuple of strings. - """ - if not stopwords: - self._stopwords = set() - elif isinstance(stopwords, str): - self._stopwords = get_stopwords(stopwords) - elif isinstance(stopwords, (set, list, tuple)) and all( - isinstance(word, str) for word in stopwords - ): - self._stopwords = set(stopwords) - else: - raise TypeError("stopwords must be a set, list, or tuple of strings") + return self._ft_helper.stopwords def _tokenize_and_escape_query(self, user_query: str) -> str: """Convert a raw user query to a redis full text query joined by ORs @@ -1423,10 +1402,7 @@ def _tokenize_and_escape_query(self, user_query: str) -> str: Raises: ValueError: If the text string becomes empty after stopwords are removed. """ - helper = FullTextQueryHelper( - stopwords=self._stopwords, text_weights=self._text_weights - ) - return helper._tokenize_and_escape_query(user_query) + return self._ft_helper._tokenize_and_escape_query(user_query) def _parse_field_weights( self, field_spec: str | dict[str, float] @@ -1493,33 +1469,13 @@ def text_field_name(self) -> str | dict[str, float]: return field return self._field_weights.copy() - def _parse_text_weights(self, weights: dict[str, float] | None) -> dict[str, float]: - parsed_weights: dict[str, float] = {} - if not weights: - return parsed_weights - for word, weight in weights.items(): - word = word.strip().lower() - if not word or " " in word: - raise ValueError( - f"Only individual words may be weighted. Got {{ {word}:{weight} }}" - ) - if ( - not (isinstance(weight, float) or isinstance(weight, int)) - or weight < 0.0 - ): - raise ValueError( - f"Weights must be positive number. Got {{ {word}:{weight} }}" - ) - parsed_weights[word] = weight - return parsed_weights - def set_text_weights(self, weights: dict[str, float]): """Set or update the text weights for the query. Args: text_weights: Dictionary of word:weight mappings """ - self._text_weights = self._parse_text_weights(weights) + self._ft_helper.set_text_weights(weights) self._built_query_string = None @property @@ -1529,7 +1485,7 @@ def text_weights(self) -> dict[str, float]: Returns: Dictionary of word:weight mappings. """ - return self._text_weights + return self._ft_helper.text_weights def _build_query_string(self) -> str: """Build the full query string for text search with optional filtering.""" diff --git a/tests/unit/test_query_types.py b/tests/unit/test_query_types.py index 30ce81545..99078ef6e 100644 --- a/tests/unit/test_query_types.py +++ b/tests/unit/test_query_types.py @@ -276,6 +276,61 @@ def test_text_query(): assert text_query.filter == filter_expression +@pytest.mark.parametrize( + "text, stopwords", + [("the a an", "english"), ("only", {"only"}), (", “ ”", None)], +) +def test_text_query_rejects_empty_tokenized_text(text, stopwords): + with pytest.raises( + ValueError, match="text string cannot be empty after removing stopwords" + ): + TextQuery(text=text, text_field_name="body", stopwords=stopwords) + + +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) + + +@pytest.mark.parametrize("text", ["", " "]) +def test_text_query_rejects_empty_text_without_stopwords(text): + with pytest.raises(ValueError, match="^text string cannot be empty$"): + TextQuery(text, "body", stopwords=None) + + +def test_text_query_validates_filter_before_stopword_content(): + with pytest.raises(TypeError): + TextQuery("the", "body", filter_expression=123) + + +def test_text_query_does_not_revalidate_mutated_weights_on_rebuild(): + query = TextQuery("hello", "body") + query.text_weights["unrelated words"] = 2.0 + query.set_field_weights("other") + assert "@other:(hello)" in str(query) + + +def test_text_query_tokenizes_once_until_weights_change(monkeypatch): + from redisvl.utils.full_text_query_helper import FullTextQueryHelper + + calls = [] + tokenize = FullTextQueryHelper._tokenize_and_escape_query + + def counted_tokenize(self, text): + calls.append(text) + return tokenize(self, text) + + monkeypatch.setattr( + FullTextQueryHelper, "_tokenize_and_escape_query", counted_tokenize + ) + query = TextQuery("hello world", "body") + assert "@body:(hello | world)" in str(query) + assert calls == ["hello world"] + query.set_text_weights({"hello": 2.0}) + assert "hello=>{$weight:2.0}" in str(query) + assert calls == ["hello world", "hello world"] + + def test_text_query_with_string_filter(): """Test that TextQuery correctly includes string filter expressions in query string. diff --git a/tests/unit/test_text_query_weights.py b/tests/unit/test_text_query_weights.py index ee570eb20..4606a9f7f 100644 --- a/tests/unit/test_text_query_weights.py +++ b/tests/unit/test_text_query_weights.py @@ -122,23 +122,7 @@ def test_set_field_weights_method(): assert "$weight: 2.0" in query_string or "$weight:2.0" in query_string -@pytest.mark.parametrize( - "text, stopwords", - [("the a an", "english"), ("only", {"only"}), (" ", None), (", “ ”", None)], -) -def test_text_query_rejects_empty_tokenized_text(text, stopwords): - with pytest.raises( - ValueError, match="text string cannot be empty after removing stopwords" - ): - TextQuery(text=text, text_field_name="body", stopwords=stopwords) - - -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) - - -def test_text_query_preserves_escaping_and_updated_weights(): +def test_set_text_weights_resets_cached_query_string(): query = TextQuery( "the HELLO, redis-vl", text_field_name="body", text_weights={"hello": 2.0} ) From b990e764648457289ceeeee8a6d5c3a4376561fd Mon Sep 17 00:00:00 2001 From: Alex Castillo Date: Wed, 11 Nov 2026 09:43:52 -0400 Subject: [PATCH 3/3] test(query): remove implementation-specific TextQuery assertions --- tests/unit/test_query_types.py | 28 ---------------------------- 1 file changed, 28 deletions(-) diff --git a/tests/unit/test_query_types.py b/tests/unit/test_query_types.py index 99078ef6e..b40663784 100644 --- a/tests/unit/test_query_types.py +++ b/tests/unit/test_query_types.py @@ -303,34 +303,6 @@ def test_text_query_validates_filter_before_stopword_content(): TextQuery("the", "body", filter_expression=123) -def test_text_query_does_not_revalidate_mutated_weights_on_rebuild(): - query = TextQuery("hello", "body") - query.text_weights["unrelated words"] = 2.0 - query.set_field_weights("other") - assert "@other:(hello)" in str(query) - - -def test_text_query_tokenizes_once_until_weights_change(monkeypatch): - from redisvl.utils.full_text_query_helper import FullTextQueryHelper - - calls = [] - tokenize = FullTextQueryHelper._tokenize_and_escape_query - - def counted_tokenize(self, text): - calls.append(text) - return tokenize(self, text) - - monkeypatch.setattr( - FullTextQueryHelper, "_tokenize_and_escape_query", counted_tokenize - ) - query = TextQuery("hello world", "body") - assert "@body:(hello | world)" in str(query) - assert calls == ["hello world"] - query.set_text_weights({"hello": 2.0}) - assert "hello=>{$weight:2.0}" in str(query) - assert calls == ["hello world", "hello world"] - - def test_text_query_with_string_filter(): """Test that TextQuery correctly includes string filter expressions in query string.