Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 14 additions & 67 deletions redisvl/query/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,8 @@

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__)
Expand Down Expand Up @@ -1350,23 +1349,28 @@ 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
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)
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)
Expand All @@ -1386,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
Expand All @@ -1420,22 +1402,7 @@ 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)
return self._ft_helper._tokenize_and_escape_query(user_query)

def _parse_field_weights(
self, field_spec: str | dict[str, float]
Expand Down Expand Up @@ -1502,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
Expand All @@ -1538,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."""
Expand Down
27 changes: 27 additions & 0 deletions tests/unit/test_query_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,33 @@ 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_with_string_filter():
"""Test that TextQuery correctly includes string filter expressions in query string.

Expand Down
9 changes: 9 additions & 0 deletions tests/unit/test_text_query_weights.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,12 @@ 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


def test_set_text_weights_resets_cached_query_string():
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)
Loading