# Filter

```json metadata
{
  "schema_version": 2,
  "title": "Filter",
  "description": "",
  "categories": null,
  "tableOfContents": {"sections":[{"children":[{"id":"class-filterexpression_filternone-operatornone-leftnone-rightnone","title":"class FilterExpression(_filter=None, operator=None, left=None, right=None)"}],"id":"filterexpression","title":"FilterExpression"},{"children":[{"id":"class-tagfield","title":"class Tag(field)"}],"id":"tag","title":"Tag"},{"children":[{"id":"class-textfield","title":"class Text(field)"}],"id":"text","title":"Text"},{"children":[{"id":"class-numfield","title":"class Num(field)"}],"id":"num","title":"Num"},{"children":[{"id":"class-geofield","title":"class Geo(field)"}],"id":"geo","title":"Geo"},{"children":[{"id":"class-georadiuslongitude-latitude-radius1-unitkm","title":"class GeoRadius(longitude, latitude, radius=1, unit='km')"}],"id":"georadius","title":"GeoRadius"},{"children":[{"id":"class-timestampfield","title":"class Timestamp(field)"}],"id":"timestamp","title":"Timestamp"}]}

,
  "codeExamples": [{"id":"filter-api"}]
}
```



<a id="filter-api"></a>

## FilterExpression

### `class FilterExpression(_filter=None, operator=None, left=None, right=None)`

A FilterExpression is a logical combination of filters in RedisVL.

FilterExpressions can be combined using the & and | operators to create
complex expressions that evaluate to the Redis Query language.

This presents an interface by which users can create complex queries
without having to know the Redis Query language.

```python
from redisvl.query.filter import Tag, Num

brand_is_nike = Tag("brand") == "nike"
price_is_over_100 = Num("price") < 100
f = brand_is_nike & price_is_over_100

print(str(f))

>> (@brand:{nike} @price:[-inf (100)])
```

This can be combined with the VectorQuery class to create a query:

```python
from redisvl.query import VectorQuery

v = VectorQuery(
    vector=[0.1, 0.1, 0.5, ...],
    vector_field_name="product_embedding",
    return_fields=["product_id", "brand", "price"],
    filter_expression=f,
)
```

> [!NOTE]
> Filter expressions are typically not called directly. Instead they are
> built by combining filter statements using the & and | operators.

* **Parameters:**
  * **\_filter** (*str* *|* *None*)
  * **operator** (*FilterOperator* *|* *None*)
  * **left** ([FilterExpression](#filterexpression) *|* *None*)
  * **right** ([FilterExpression](#filterexpression) *|* *None*)

## Tag

### `class Tag(field)`

A Tag filter can be applied to Tag fields

* **Parameters:**
  **field** (*str*)

#### `__eq__(other)`

Create a Tag equality filter expression.

* **Parameters:**
  **other** (*Union* *[* *List* *[* *str* *]* *,* *str* *]*) – The tag(s) to filter on.
* **Return type:**
  [FilterExpression](#filterexpression)

```python
from redisvl.query.filter import Tag

f = Tag("brand") == "nike"
```

#### `__mod__(other)`

Create a Tag wildcard filter expression for pattern matching.

This enables wildcard pattern matching on tag fields using the `*`
character. Unlike the equality operator, wildcards are not escaped,
allowing patterns with wildcards in any position, such as prefix
(`"tech*"`), suffix (`"*tech"`), or middle (`"*tech*"`)
matches.

* **Parameters:**
  **other** (*Union* *[* *List* *[* *str* *]* *,* *str* *]*) – The tag pattern(s) to filter on.
  Use `*` for wildcard matching (e.g., `"tech*"`, `"*tech"`,
  or `"*tech*"`).
* **Return type:**
  [FilterExpression](#filterexpression)

```python
from redisvl.query.filter import Tag

f = Tag("category") % "tech*"               # Prefix match
f = Tag("category") % "*tech"               # Suffix match
f = Tag("category") % "*tech*"              # Contains match
f = Tag("category") % "elec*|*soft"         # Multiple wildcard patterns
f = Tag("category") % ["tech*", "*science"] # List of patterns
```

#### `__ne__(other)`

Create a Tag inequality filter expression.

* **Parameters:**
  **other** (*Union* *[* *List* *[* *str* *]* *,* *str* *]*) – The tag(s) to filter on.
* **Return type:**
  [FilterExpression](#filterexpression)

```python
from redisvl.query.filter import Tag
f = Tag("brand") != "nike"
```

#### `__str__()`

Return the Redis Query string for the Tag filter

* **Return type:**
  str

## Text

### `class Text(field)`

A Text is a FilterField representing a text field in a Redis index.

> [!NOTE]
> `==` and `!=` match the value as a quoted phrase. Any `"` in the
> value becomes a space first, so the value cannot close that phrase; a
> quote already separates tokens at index time, so this matches the same
> documents that escaping it never could. A value of nothing but quotes
> therefore becomes an empty phrase, which `==` matches no document
> against. `%` is the pattern operator and interpolates its value
> untouched.

* **Parameters:**
  **field** (*str*)

#### `__eq__(other)`

Create a Text equality filter expression. These expressions yield
filters that enforce an exact match on the supplied term(s).

* **Parameters:**
  **other** (*str*) – The text value to filter on.
* **Return type:**
  [FilterExpression](#filterexpression)

```python
from redisvl.query.filter import Text

f = Text("job") == "engineer"
```

#### `__mod__(other)`

Create a Text "LIKE" filter expression. A flexible expression that
yields filters that can use a variety of additional operators like
wildcards (\*), fuzzy matches (%%), or combinatorics (|) of the supplied
term(s).

* **Parameters:**
  **other** (*str*) – The text value to filter on.
* **Return type:**
  [FilterExpression](#filterexpression)

```python
from redisvl.query.filter import Text

f = Text("job") % "engine*"         # suffix wild card match
f = Text("job") % "%%engine%%"      # fuzzy match w/ Levenshtein Distance
f = Text("job") % "engineer|doctor" # contains either term in field
f = Text("job") % "engineer doctor" # contains both terms in field
```

> [!NOTE]
> The value is interpolated raw, which is what makes `*`, `%%` and
> `|` work. A value carrying a `)` therefore closes this clause and
> has its remainder parsed as query syntax, past any surrounding
> filter. Pass only patterns your own code composes; for a value you
> did not construct, use `==`, which matches it as a literal phrase.

#### `__ne__(other)`

Create a Text inequality filter expression. These expressions yield
negated filters on exact matches on the supplied term(s). Opposite of an
equality filter expression.

* **Parameters:**
  **other** (*str*) – The text value to filter on.
* **Return type:**
  [FilterExpression](#filterexpression)

```python
from redisvl.query.filter import Text

f = Text("job") != "engineer"
```

#### `__str__()`

Return the Redis Query string for the Text filter

* **Return type:**
  str

## Num

### `class Num(field)`

A Num is a FilterField representing a numeric field in a Redis index.

* **Parameters:**
  **field** (*str*)

#### `__eq__(other)`

Create a Numeric equality filter expression.

* **Parameters:**
  **other** (*Union* *[* *int* *,* *float* *]*) – The value to filter on.
* **Return type:**
  [FilterExpression](#filterexpression)

```python
from redisvl.query.filter import Num
f = Num("zipcode") == 90210
```

#### `__ge__(other)`

Create a Numeric greater than or equal to filter expression.

* **Parameters:**
  **other** (*Union* *[* *int* *,* *float* *]*) – The value to filter on.
* **Return type:**
  [FilterExpression](#filterexpression)

```python
from redisvl.query.filter import Num

f = Num("age") >= 18
```

#### `__gt__(other)`

Create a Numeric greater than filter expression.

* **Parameters:**
  **other** (*Union* *[* *int* *,* *float* *]*) – The value to filter on.
* **Return type:**
  [FilterExpression](#filterexpression)

```python
from redisvl.query.filter import Num

f = Num("age") > 18
```

#### `__le__(other)`

Create a Numeric less than or equal to filter expression.

* **Parameters:**
  **other** (*Union* *[* *int* *,* *float* *]*) – The value to filter on.
* **Return type:**
  [FilterExpression](#filterexpression)

```python
from redisvl.query.filter import Num

f = Num("age") <= 18
```

#### `__lt__(other)`

Create a Numeric less than filter expression.

* **Parameters:**
  **other** (*Union* *[* *int* *,* *float* *]*) – The value to filter on.
* **Return type:**
  [FilterExpression](#filterexpression)

```python
from redisvl.query.filter import Num

f = Num("age") < 18
```

#### `__ne__(other)`

Create a Numeric inequality filter expression.

* **Parameters:**
  **other** (*Union* *[* *int* *,* *float* *]*) – The value to filter on.
* **Return type:**
  [FilterExpression](#filterexpression)

```python
from redisvl.query.filter import Num

f = Num("zipcode") != 90210
```

#### `__str__()`

Return the Redis Query string for the Numeric filter

* **Return type:**
  str

#### `between(start, end, inclusive='both')`

Operator for searching values between two numeric values.

* **Parameters:**
  * **start** (*Union* *[* *int* *,* *float* *]*) – The lower bound of the range.
  * **end** (*Union* *[* *int* *,* *float* *]*) – The upper bound of the range.
  * **inclusive** (*str* *,* *optional*) – Which bounds to include: "both",
    "neither", "left" or "right". Defaults to "both".
* **Raises:**
  * **TypeError** – If either bound is not an `int`, a `float`, or
        another `numbers.Real`. numpy scalars qualify; `Decimal`
        and `str` do not.
  * **ValueError** – If either bound is NaN, or if `inclusive` is not one
        of the four accepted values.
* **Return type:**
  [FilterExpression](#filterexpression)

```python
from redisvl.query.filter import Num

f = Num("age").between(18, 65)
f = Num("age").between(18, 65, inclusive="neither")
```

## Geo

### `class Geo(field)`

A Geo is a FilterField representing a geographic (longitude, latitude)
field in a Redis index.

> [!NOTE]
> Redis indexes latitudes only within +/-85.05112878 degrees (EPSG:900913).
> A document or a query center nearer a pole than that is silently
> excluded: the query returns no error and no results, at any radius.

* **Parameters:**
  **field** (*str*)

#### `__eq__(other)`

Create a geographic filter within a specified GeoRadius.

* **Parameters:**
  **other** ([GeoRadius](#georadius)) – The geographic spec to filter on.
* **Return type:**
  [FilterExpression](#filterexpression)

```python
from redisvl.query.filter import Geo, GeoRadius

f = Geo("location") == GeoRadius(-122.4194, 37.7749, 1, unit="m")
```

#### `__ne__(other)`

Create a geographic filter outside of a specified GeoRadius.

* **Parameters:**
  **other** ([GeoRadius](#georadius)) – The geographic spec to filter on.
* **Return type:**
  [FilterExpression](#filterexpression)

```python
from redisvl.query.filter import Geo, GeoRadius

f = Geo("location") != GeoRadius(-122.4194, 37.7749, 1, unit="m")
```

#### `__str__()`

Return the Redis Query string for the Geo filter

* **Return type:**
  str

## GeoRadius

### `class GeoRadius(longitude, latitude, radius=1, unit='km')`

A GeoRadius is a GeoSpec representing a geographic radius.

Create a GeoRadius specification (GeoSpec)

* **Parameters:**
  * **longitude** (*float*) – The longitude of the center of the radius, in
    degrees, from -180 to 180.
  * **latitude** (*float*) – The latitude of the center of the radius, in
    degrees, from -90 to 90.
  * **radius** (*float* *,* *optional*) – The radius of the circle, in `unit`,
    greater than 0. Fractional radii are sent as given, so 0.5 with
    a unit of "km" is half a kilometre. Defaults to 1.
  * **unit** (*str* *,* *optional*) – The unit of the radius. Defaults to "km".
* **Raises:**
  * **TypeError** – If a coordinate or the radius is not an `int`, a
        `float`, or another `numbers.Real`. numpy scalars qualify;
        `Decimal` and `str` do not.
  * **ValueError** – If a coordinate is NaN, infinite, or outside its range,
        if the radius is NaN, infinite, or not greater than 0, or if
        the unit is not a string spelling one of "m", "km", "mi", or
        "ft".

#### `__init__(longitude, latitude, radius=1, unit='km')`

Create a GeoRadius specification (GeoSpec)

* **Parameters:**
  * **longitude** (*float*) – The longitude of the center of the radius, in
    degrees, from -180 to 180.
  * **latitude** (*float*) – The latitude of the center of the radius, in
    degrees, from -90 to 90.
  * **radius** (*float* *,* *optional*) – The radius of the circle, in `unit`,
    greater than 0. Fractional radii are sent as given, so 0.5 with
    a unit of "km" is half a kilometre. Defaults to 1.
  * **unit** (*str* *,* *optional*) – The unit of the radius. Defaults to "km".
* **Raises:**
  * **TypeError** – If a coordinate or the radius is not an `int`, a
        `float`, or another `numbers.Real`. numpy scalars qualify;
        `Decimal` and `str` do not.
  * **ValueError** – If a coordinate is NaN, infinite, or outside its range,
        if the radius is NaN, infinite, or not greater than 0, or if
        the unit is not a string spelling one of "m", "km", "mi", or
        "ft".

## Timestamp

### `class Timestamp(field)`

A timestamp filter for querying date/time fields in Redis.

This filter can handle various date and time formats, including:
- datetime objects (with or without timezone)
- date objects
- ISO-8601 formatted strings
- Unix timestamps (as integers or floats)

All timestamps are converted to Unix timestamps in UTC for consistency.
Bare date values and date-only ISO strings are anchored to the UTC calendar
day, not the host’s local day, and naive datetimes are read as UTC.

* **Parameters:**
  **field** (*str*)

#### `__eq__(other)`

Filter for timestamps equal to the specified value.
For date objects (without time), this matches the entire UTC calendar
day, from 00:00:00 to 23:59:59.999999 UTC.

* **Parameters:**
  **other** (*datetime* *|* *date* *|* *str* *|* *int* *|* *float*) – A datetime, date, ISO string, or Unix timestamp
* **Returns:**
  The filter object for method chaining
* **Return type:**
  self

#### `__ge__(other)`

Filter for timestamps greater than or equal to the specified value.

For a bare date (or date-only ISO string), this means from the *start* of
that UTC day, so the day itself is included.

* **Parameters:**
  **other** – A datetime, date, ISO string, or Unix timestamp
* **Returns:**
  The filter object for method chaining
* **Return type:**
  self

#### `__gt__(other)`

Filter for timestamps greater than the specified value.

For a bare date (or date-only ISO string), this means after the *end* of
that UTC day, so the day itself is excluded.

* **Parameters:**
  **other** – A datetime, date, ISO string, or Unix timestamp
* **Returns:**
  The filter object for method chaining
* **Return type:**
  self

#### `__le__(other)`

Filter for timestamps less than or equal to the specified value.

For a bare date (or date-only ISO string), this means through the *end* of
that UTC day, so the day itself is included.

* **Parameters:**
  **other** – A datetime, date, ISO string, or Unix timestamp
* **Returns:**
  The filter object for method chaining
* **Return type:**
  self

#### `__lt__(other)`

Filter for timestamps less than the specified value.

For a bare date (or date-only ISO string), this means before the *start*
of that UTC day, so the day itself is excluded.

* **Parameters:**
  **other** – A datetime, date, ISO string, or Unix timestamp
* **Returns:**
  The filter object for method chaining
* **Return type:**
  self

#### `__ne__(other)`

Filter for timestamps not equal to the specified value.
For date objects (without time), this excludes the entire UTC calendar
day, from 00:00:00 to 23:59:59.999999 UTC.

* **Parameters:**
  **other** (*datetime* *|* *date* *|* *str* *|* *int* *|* *float*) – A datetime, date, ISO string, or Unix timestamp
* **Returns:**
  The filter object for method chaining
* **Return type:**
  self

#### `between(start, end, inclusive='both')`

Filter for timestamps between start and end (inclusive).

Bare dates (and date-only ISO strings) span whole UTC calendar days:
start anchors to 00:00:00 of its day and end to 23:59:59.999999 of its
day, so both endpoint days are covered in full.

* **Parameters:**
  * **start** – A datetime, date, ISO string, or Unix timestamp
  * **end** – A datetime, date, ISO string, or Unix timestamp
  * **inclusive** (*str*) – Which endpoints to include – "both" (default), "left",
    "right", or "neither".
* **Returns:**
  The filter object for method chaining
* **Return type:**
  self

