Skip to content
Open
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
3 changes: 2 additions & 1 deletion docs/concepts/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,8 @@ The claim must be a single, non-empty string. Anything else refuses the request
| Claim value | Why it is refused |
|---|---|
| Absent, or the request has no token | There is no tenant to scope to. |
| `null` or `""` | An empty tag value would drop the tenant clause from the query entirely. |
| `null` | It renders as `*`, which would drop the tenant clause from the query entirely. |
| `""` | An empty tag value is not a tenant to scope to. |
| A list, such as `["acme", "victim"]` | It would render as a union, `@org_id:{acme\|victim}`, which spans both tenants. |
| An object, number or boolean | It is not a tenant identifier. |
| Padded with whitespace | It cannot be a real tenant identifier, and refusing is safer than guessing which tenant was meant. |
Expand Down
2 changes: 1 addition & 1 deletion docs/concepts/search-and-indexing.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ Both methods share the same safety-oriented options and return a `BulkResult`:

- The return value carries `matched` (documents matching the filter), `processed` (documents actually affected), `completed` (False if a delete stopped early—at its runaway backstop, or on a batch it could not remove; always True for update), and `dry_run`. Read the fields explicitly—`result.processed`, `result.completed`, etc.
- `dry_run=True` reports how many documents *would* be affected—via a count query—without changing anything.
- A match-all filter (empty, `"*"`, or `None`) is refused unless you pass `allow_all=True`; use `clear()` when you intentionally want to empty the index. This guard catches the canonical match-all forms only—it is a convenience backstop, not a security control.
- A match-all filter (an empty string, `"*"`, `None`, or a filter that renders as `*`, such as `Tag(f) == None`) is refused unless you pass `allow_all=True`; use `clear()` when you intentionally want to empty the index. This guard catches the canonical match-all forms only—it is a convenience backstop, not a security control.
- `on_progress(processed, matched)` is called after each write batch for observability on large operations (it runs synchronously—don't pass a coroutine—and raising from it aborts the run). Note `update_by_filter` resolves all matching keys before it writes, so progress callbacks begin only once the write phase starts. `batch_size` tunes how many documents are processed per round-trip.

The related `drop_documents()` and `drop_keys()` helpers delete by document ID or full Redis key and batch large inputs. On Redis Cluster, `drop_keys()` unlinks per-key so it works across hash slots, while `drop_documents()` requires the target keys to share a hash tag and raises `ValueError` otherwise. Unlinking per-key also means a failure on one key is logged rather than raised, so one bad key does not abort the batch—but the returned count can then come back lower than the number of keys you passed with no exception to catch. The count alone cannot tell that apart from a key that simply did not exist.
Expand Down
19 changes: 11 additions & 8 deletions docs/user_guide/02_complex_filtering.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -389,11 +389,13 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"What about scenarios where you might want to dynamically generate a list of tags? Have no fear. RedisVL allows you to do this gracefully without having to check for the **empty case**. The **empty case** is when you attempt to run a Tag filter on a field with no defined values to match:\n",
"What about scenarios where you might want to dynamically generate a list of tags? Redis has no syntax for an empty set of tags, so RedisVL treats one as selecting nothing: a Tag filter built from an empty list **matches no documents**:\n",
"\n",
"`Tag(\"credit_score\") == []`\n",
"\n",
"An empty filter like the one above will yield a `*` Redis query filter which implies the base case -- there is no filter here to use."
"This is deliberate. When the list holds permitted values, such as a user's groups, an empty list must not widen the query. Combined with other filters, an empty list still matches nothing: `(Tag(\"tenant\") == \"acme\") & (Tag(\"groups\") == [])` returns no documents, and in a `|` it adds nothing to the other side's matches.\n",
"\n",
"To mean \"no constraint\", pass `None` instead, which yields a `*` Redis query filter -- there is no filter here to use. Use `!= []` to exclude nothing."
]
},
{
Expand Down Expand Up @@ -422,8 +424,8 @@
}
],
"source": [
"# gracefully fallback to \"*\" filter if empty case\n",
"empty_case = Tag(\"credit_score\") == []\n",
"# None means no constraint, and falls back to the \"*\" filter\n",
"empty_case = Tag(\"credit_score\") == None\n",
"\n",
"v.set_filter(empty_case)\n",
"result_print(index.query(v))"
Expand Down Expand Up @@ -892,8 +894,8 @@
}
],
"source": [
"# gracefully fallback to \"*\" filter if empty case\n",
"empty_case = Text(\"job\") % \"\"\n",
"# None means no constraint, and falls back to the \"*\" filter\n",
"empty_case = Text(\"job\") % None\n",
"\n",
"v.set_filter(empty_case)\n",
"result_print(index.query(v))"
Expand Down Expand Up @@ -1213,11 +1215,12 @@
"\n",
"There are often situations where you may or may not want to use a filter in a\n",
"given query. As shown above, filters will except the ``None`` type and revert\n",
"to a wildcard filter essentially returning all results.\n",
"to a wildcard filter essentially returning all results. An empty list is not\n",
"``None``: it means \"in the empty set\" and matches nothing.\n",
"\n",
"The same goes for filter combinations which enables rapid reuse of filters in\n",
"requests with different parameters as shown below. This removes the need for\n",
"a number of \"if-then\" conditionals to test for the empty case.\n",
"a number of \"if-then\" conditionals to test for ``None``.\n",
"\n"
]
},
Expand Down
11 changes: 6 additions & 5 deletions redisvl/extensions/router/semantic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1093,11 +1093,12 @@ def _make_filter_queries(ids: list[str]) -> list[FilterQuery]:

for id in ids:
if not id:
# `Tag(...) == ""` renders as the match-all `*`, so an empty id
# would match every reference in the index. Callers take the
# first row of each query's results, which turns this into
# returning -- and, from delete_route_references, deleting -- an
# arbitrary reference the caller never named.
# `None` renders as the match-all `*` and would match every
# reference; `""` renders `@reference_id:{""}`, which this index
# cannot answer reliably without `INDEXEMPTY`. Callers take the
# first row of each query's results, so a match-all returns --
# and, from delete_route_references, deletes -- an arbitrary
# reference the caller never named.
raise ValueError(
"reference ids must be non-empty strings; received an empty id"
)
Expand Down
86 changes: 75 additions & 11 deletions redisvl/query/filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,29 @@ def wrapper(instance: Any, *args: list[Any], **kwargs: dict[str, Any]) -> Any:


class Tag(FilterField):
"""A Tag filter can be applied to Tag fields"""
"""A Tag filter can be applied to Tag fields

Note:
Empty values follow Redis, which has no syntax for an empty set of
tags. ``None`` means no constraint and renders ``*``. An empty
collection (``[]``, ``()``, ``set()``, or one holding only ``None``)
selects no tag, so ``==`` and ``%`` match no document: ``&`` with it
matches nothing, and ``|`` leaves the other side's matches unchanged.
``!=`` an empty collection excludes nothing and renders ``*``. ``""`` is
a tag of its own, rendered ``@field:{""}``. That needs DIALECT 2 or
later and ``INDEXEMPTY`` on the field; without ``INDEXEMPTY`` the
server rejects it in some query positions and silently returns results
in others, so do not use it on such a field. ``Text`` refuses ``""``
because its server-side failure happens even on a correctly indexed
field; this one only on a field indexed without ``INDEXEMPTY``.

.. code-block:: python

from redisvl.query.filter import Tag

allowed = (Tag("tenant") == "acme") & (Tag("groups") == user_groups)
# user_groups == [] -> matches no document
"""

OPERATORS: dict[FilterOperator, str] = {
FilterOperator.EQ: "==",
Expand All @@ -141,18 +163,20 @@ class Tag(FilterField):
escape_chars_re=re.compile(TokenEscaper.TAG_ESCAPED_CHARS)
)

# RediSearch has no empty tag set: `@f:{}` is a syntax error, and an empty
# collection of tags selects no tag at all. So it is rendered as a
# contradiction over this value, which no document can satisfy. The value
# is arbitrary; only the contradiction matters.
_NO_MATCH_TAG = "redisvl_no_match"

def _set_tag_value(
self, other: list[str] | set[str] | str, operator: FilterOperator
self, other: list[str] | set[str] | str | None, operator: FilterOperator
):
if isinstance(other, (list, set, tuple)):
try:
# "if val" clause removes non-truthy values from list
other = [str(val) for val in other if val]
other = [str(val) for val in other if val is not None]
except ValueError:
raise ValueError("All tags within collection must be strings")
# above to catch the "" case
elif not other:
other = []
elif isinstance(other, str):
other = [other]

Expand Down Expand Up @@ -222,15 +246,27 @@ def __mod__(self, other: list[str] | str) -> "FilterExpression":
def _formatted_tag_value(self) -> str:
# For LIKE operator, preserve wildcards (*) in the pattern
preserve_wildcards = self._operator == FilterOperator.LIKE
# An empty tag has no characters to escape, and RediSearch spells it
# as a quoted empty string.
return "|".join(
[self.escaper.escape(tag, preserve_wildcards) for tag in self._value]
[
self.escaper.escape(tag, preserve_wildcards) if tag else '""'
for tag in self._value
]
)

def __str__(self) -> str:
"""Return the Redis Query string for the Tag filter"""
if not self._value:
if self._value is None:
return "*"

if not self._value:
if self._operator == FilterOperator.NE:
return "*"
return "(@{0}:{{{1}}} -@{0}:{{{1}}})".format(
self._field, self._NO_MATCH_TAG
)

return self.OPERATOR_MAP[self._operator] % (
self._field,
self._formatted_tag_value,
Expand Down Expand Up @@ -724,6 +760,8 @@ class Text(FilterField):
therefore becomes an empty phrase, which ``==`` matches no document
against. ``%`` is the pattern operator and interpolates its value
untouched.

An empty string raises ``ValueError``; pass ``None`` for no constraint.
"""

OPERATORS: dict[FilterOperator, str] = {
Expand All @@ -744,6 +782,26 @@ class Text(FilterField):
# opts out here.
_RAW_VALUE_OPERATORS = frozenset({FilterOperator.LIKE})

def _set_value(
self,
val: Any,
val_type: type | tuple[type, ...],
operator: FilterOperator,
):
if isinstance(val, str) and not val:
# `@f:("")` is how RediSearch asks for an empty string, but after a
# TAG clause the server checks it against that tag field's
# `INDEXEMPTY` instead of this field's (measured on 8.4: `@t:{a}
# @x:("")` fails with `x` indexed empty, `@x:("") @t:{a}` does not).
# Rendering it would make a filter's meaning depend on operand
# order, so it is refused. `None` is how to ask for no constraint,
# and `is_missing()` finds an absent field.
raise ValueError(
f"{self.__class__.__name__} value must be a non-empty string; "
"pass None for no constraint"
)
super()._set_value(val, val_type, operator)

@check_operator_misuse
def __eq__(self, other: str) -> "FilterExpression":
"""Create a Text equality filter expression. These expressions yield
Expand Down Expand Up @@ -812,7 +870,7 @@ def __mod__(self, other: str) -> "FilterExpression":

def __str__(self) -> str:
"""Return the Redis Query string for the Text filter"""
if not self._value:
if self._value is None:
return "*"

value = self._value
Expand Down Expand Up @@ -862,6 +920,12 @@ class FilterExpression:
filter_expression=f,
)

Note:
A filter that can match no document, such as ``Tag("g") == []``, is
rendered as a clause that matches nothing, so it narrows an ``&`` and
adds nothing to a ``|``. ``*`` (from ``None``, or ``!=`` an empty
collection) constrains nothing and is elided from both operators.

Note:
Filter expressions are typically not called directly. Instead they are
built by combining filter statements using the & and | operators.
Expand Down Expand Up @@ -948,7 +1012,7 @@ def is_match_all_filter(filter_expression: str | FilterExpression | None) -> boo
def render_filter(filter_expression: str | FilterExpression | None) -> str | None:
"""Render a filter expression, or None when it selects every document.

A ``None``, empty, or wildcard (``*``) filter contributes no clause to a
A ``None``, empty-string, or wildcard (``*``) filter contributes no clause to a
query: ``*`` is only valid as an entire query, never as one operand of an
intersection.

Expand Down
Loading
Loading