Filter

Overview

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.

[code example]

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

[code example]

#### `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)

[code example]

#### `__ne__(other)`

Create a Tag inequality filter expression.

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

[code example]

#### `__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.

* **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)

[code example]

#### `__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)

[code example]

#### `__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)

[code example]

#### `__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** (*int*) – The value to filter on.
* **Return type:**
  [FilterExpression](#filterexpression)

[code example]

#### `__ge__(other)`

Create a Numeric greater than or equal to filter expression.

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

[code example]

#### `__gt__(other)`

Create a Numeric greater than filter expression.

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

[code example]

#### `__le__(other)`

Create a Numeric less than or equal to filter expression.

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

[code example]

#### `__lt__(other)`

Create a Numeric less than filter expression.

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

[code example]

#### `__ne__(other)`

Create a Numeric inequality filter expression.

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

[code example]

#### `__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** (*int*)
  * **end** (*int*)
  * **inclusive** (*str*)
* **Return type:**
  [FilterExpression](#filterexpression)

Geo

`class Geo(field)`

A Geo is a FilterField representing a geographic (lat/lon) field in a
Redis index.

* **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)

[code example]

#### `__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)

[code example]

#### `__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.
  * **latitude** (*float*) – The latitude of the center of the radius.
  * **radius** (*int* *,* *optional*) – The radius of the circle. Defaults to 1.
  * **unit** (*str* *,* *optional*) – The unit of the radius. Defaults to "km".
* **Raises:**
  **ValueError** – If the unit is not 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.
  * **latitude** (*float*) – The latitude of the center of the radius.
  * **radius** (*int* *,* *optional*) – The radius of the circle. Defaults to 1.
  * **unit** (*str* *,* *optional*) – The unit of the radius. Defaults to "km".
* **Raises:**
  **ValueError** – If the unit is not one of "m", "km", "mi", or "ft".

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)])

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,
)

from redisvl.query.filter import Tag

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

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

from redisvl.query.filter import Text

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

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

from redisvl.query.filter import Text

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

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

from redisvl.query.filter import Num

f = Num("age") >= 18

from redisvl.query.filter import Num

f = Num("age") > 18

from redisvl.query.filter import Num

f = Num("age") <= 18

from redisvl.query.filter import Num

f = Num("age") < 18

from redisvl.query.filter import Num

f = Num("zipcode") != 90210

from redisvl.query.filter import Geo, GeoRadius

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

from redisvl.query.filter import Geo, GeoRadius

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


RedisVL API

Filter

LLM Cache

LLM Message History

LLM Session Manager

Query

Rerankers

Schema

Search Index Classes

Semantic Router

Threshold Optimizers

Vector

Vectorizers

Content

Reference documentation for the RedisVL API.

* [Schema](schema/)
  * [IndexSchema](schema/#indexschema)
  * [Index-Level Stopwords Configuration](schema/#index-level-stopwords-configuration)
  * [Defining Fields](schema/#defining-fields)
  * [Basic Field Types](schema/#basic-field-types)
  * [Vector Field Types](schema/#vector-field-types)
  * [SVS-VAMANA Configuration Utilities](schema/#svs-vamana-configuration-utilities)
  * [Vector Algorithm Comparison](schema/#vector-algorithm-comparison)
* [Search Index Classes](searchindex/)
  * [SearchIndex](searchindex/#searchindex)
  * [AsyncSearchIndex](searchindex/#asyncsearchindex)
* [Vector](vector/)
  * [Vector](vector/#id1)
* [Query](query/)
  * [VectorQuery](query/#vectorquery)
  * [VectorRangeQuery](query/#vectorrangequery)
  * [HybridQuery](query/#hybridquery)
  * [TextQuery](query/#textquery)
  * [FilterQuery](query/#filterquery)
  * [CountQuery](query/#countquery)
  * [MultiVectorQuery](query/#multivectorquery)
* [Filter](filter/)
  * [FilterExpression](filter/#filterexpression)
  * [Tag](filter/#tag)
  * [Text](filter/#text)
  * [Num](filter/#num)
  * [Geo](filter/#geo)
  * [GeoRadius](filter/#georadius)
* [Vectorizers](vectorizer/)
  * [HFTextVectorizer](vectorizer/#hftextvectorizer)
  * [OpenAITextVectorizer](vectorizer/#openaitextvectorizer)
  * [AzureOpenAITextVectorizer](vectorizer/#azureopenaitextvectorizer)
  * [VertexAITextVectorizer](vectorizer/#vertexaitextvectorizer)
  * [CohereTextVectorizer](vectorizer/#coheretextvectorizer)
  * [BedrockTextVectorizer](vectorizer/#bedrocktextvectorizer)
  * [CustomTextVectorizer](vectorizer/#customtextvectorizer)
  * [VoyageAITextVectorizer](vectorizer/#voyageaitextvectorizer)
* [Rerankers](reranker/)
  * [CohereReranker](reranker/#coherereranker)
  * [HFCrossEncoderReranker](reranker/#hfcrossencoderreranker)
  * [VoyageAIReranker](reranker/#voyageaireranker)
* [LLM Cache](cache/)
  * [SemanticCache](cache/#semanticcache)
* [Embeddings Cache](cache/#embeddings-cache)
  * [EmbeddingsCache](cache/#embeddingscache)
* [LLM Message History](message_history/)
  * [SemanticMessageHistory](message_history/#semanticmessagehistory)
  * [MessageHistory](message_history/#messagehistory)
* [Semantic Router](router/)
  * [Semantic Router](router/#semantic-router-api)
  * [Routing Config](router/#routing-config)
  * [Route](router/#route)
  * [Route Match](router/#route-match)
  * [Distance Aggregation Method](router/#distance-aggregation-method)


LLM Message History

SemanticMessageHistory

`class SemanticMessageHistory(name, session_tag=None, prefix=None, vectorizer=None, distance_threshold=0.3, redis_client=None, redis_url='redis://localhost:6379', connection_kwargs={}, overwrite=False, **kwargs)`

Bases: `BaseMessageHistory`

Initialize message history with index

Semantic Message History stores the current and previous user text prompts
and LLM responses to allow for enriching future prompts with session
context. Message history is stored in individual user or LLM prompts and
responses.

* **Parameters:**
  * **name** (*str*) – The name of the message history index.
  * **session_tag** (*Optional* *[* *str* *]*) – Tag to be added to entries to link to a specific
    conversation session. Defaults to instance ULID.
  * **prefix** (*Optional* *[* *str* *]*) – Prefix for the keys for this message data.
    Defaults to None and will be replaced with the index name.
  * **vectorizer** (*Optional* *[* *BaseVectorizer* *]*) – The vectorizer used to create embeddings.
  * **distance_threshold** (*float*) – The maximum semantic distance to be
    included in the context. Defaults to 0.3.
  * **redis_client** (*Optional* *[* *Redis* *]*) – A Redis client instance. Defaults to
    None.
  * **redis_url** (*str* *,* *optional*) – The redis url. Defaults to redis://localhost:6379.
  * **connection_kwargs** (*Dict* *[* *str* *,* *Any* *]*) – The connection arguments
    for the redis client. Defaults to empty {}.
  * **overwrite** (*bool*) – Whether or not to force overwrite the schema for
    the semantic message index. Defaults to false.

The proposed schema will support a single vector embedding constructed
from either the prompt or response in a single string.

#### `add_message(message, session_tag=None)`

Insert a single prompt or response into the message history.
A timestamp is associated with it so that it can be later sorted
in sequential ordering after retrieval.

* **Parameters:**
  * **message** (*Dict* *[* *str* *,**str* *]*) – The user prompt or LLM response.
  * **session_tag** (*Optional* *[* *str* *]*) – Tag to be added to entry to link to a specific
    conversation session. Defaults to instance ULID.
* **Return type:**
  None

#### `add_messages(messages, session_tag=None)`

Insert a list of prompts and responses into the session memory.
A timestamp is associated with each so that they can be later sorted
in sequential ordering after retrieval.

* **Parameters:**
  * **messages** (*List* *[* *Dict* *[* *str* *,* *str* *]* *]*) – The list of user prompts and LLM responses.
  * **session_tag** (*Optional* *[* *str* *]*) – Tag to be added to entries to link to a specific
    conversation session. Defaults to instance ULID.
* **Return type:**
  None

#### `clear()`

Clears the message history.

* **Return type:**
  None

#### `delete()`

Clear all message keys and remove the search index.

* **Return type:**
  None

#### `drop(id=None)`

Remove a specific exchange from the message history.

* **Parameters:**
  **id** (*Optional* *[* *str* *]*) – The id of the message entry to delete.
  If None then the last entry is deleted.
* **Return type:**
  None

#### `get_recent(top_k=5, as_text=False, raw=False, session_tag=None, role=None)`

Retrieve the recent message history in sequential order.

* **Parameters:**
  * **top_k** (*int*) – The number of previous exchanges to return. Default is 5.
  * **as_text** (*bool*) – Whether to return the conversation as a single string,
    or list of alternating prompts and responses.
  * **raw** (*bool*) – Whether to return the full Redis hash entry or just the
    prompt and response
  * **session_tag** (*Optional* *[* *str* *]*) – Tag of the entries linked to a specific
    conversation session. Defaults to instance ULID.
  * **role** (*Optional* *[* *Union* *[* *str* *,* *List* *[* *str* *]* *]* *]*) – Filter messages by role(s).
    Can be a single role string ("system", "user", "llm", "tool") or
    a list of roles. If None, all roles are returned.
* **Returns:**
  A single string transcription of the session
  : or list of strings if as_text is false.
* **Return type:**
  Union[str, List[str]]
* **Raises:**
  **ValueError** – if top_k is not an integer greater than or equal to 0,
      or if role contains invalid values.

#### `get_relevant(prompt, as_text=False, top_k=5, fall_back=False, session_tag=None, raw=False, distance_threshold=None, role=None)`

Searches the message history for information semantically related to
the specified prompt.

This method uses vector similarity search with a text prompt as input.
It checks for semantically similar prompts and responses and gets
the top k most relevant previous prompts or responses to include as
context to the next LLM call.

* **Parameters:**
  * **prompt** (*str*) – The message text to search for in message history
  * **as_text** (*bool*) – Whether to return the prompts and responses as text
  * **JSON.** (*or as*)
  * **top_k** (*int*) – The number of previous messages to return. Default is 5.
  * **session_tag** (*Optional* *[* *str* *]*) – Tag of the entries linked to a specific
    conversation session. Defaults to instance ULID.
  * **distance_threshold** (*Optional* *[* *float* *]*) – The threshold for semantic
    vector distance.
  * **fall_back** (*bool*) – Whether to drop back to recent conversation history
    if no relevant context is found.
  * **raw** (*bool*) – Whether to return the full Redis hash entry or just the
    message.
  * **role** (*Optional* *[* *Union* *[* *str* *,* *List* *[* *str* *]* *]* *]*) – Filter messages by role(s).
    Can be a single role string ("system", "user", "llm", "tool") or
    a list of roles. If None, all roles are returned.
* **Returns:**
  Either a list of strings, or a
  list of prompts and responses in JSON containing the most relevant.
* **Return type:**
  Union[List[str], List[Dict[str,str]]

Raises ValueError: if top_k is not an integer greater or equal to 0,
: or if role contains invalid values.

#### `store(prompt, response, session_tag=None)`

Insert a prompt:response pair into the message history. A timestamp
is associated with each message so that they can be later sorted
in sequential ordering after retrieval.

* **Parameters:**
  * **prompt** (*str*) – The user prompt to the LLM.
  * **response** (*str*) – The corresponding LLM response.
  * **session_tag** (*Optional* *[* *str* *]*) – Tag to be added to entries to link to a specific
    conversation session. Defaults to instance ULID.
* **Return type:**
  None

#### `property messages: List[str] | List[Dict[str, str]]`

Returns the full message history.

MessageHistory

`class MessageHistory(name, session_tag=None, prefix=None, redis_client=None, redis_url='redis://localhost:6379', connection_kwargs={}, **kwargs)`

Bases: `BaseMessageHistory`

Initialize message history

Message History stores the current and previous user text prompts and
LLM responses to allow for enriching future prompts with session
context. Message history is stored in individual user or LLM prompts and
responses.

* **Parameters:**
  * **name** (*str*) – The name of the message history index.
  * **session_tag** (*Optional* *[* *str* *]*) – Tag to be added to entries to link to a specific
    conversation session. Defaults to instance ULID.
  * **prefix** (*Optional* *[* *str* *]*) – Prefix for the keys for this conversation data.
    Defaults to None and will be replaced with the index name.
  * **redis_client** (*Optional* *[* *Redis* *]*) – A Redis client instance. Defaults to
    None.
  * **redis_url** (*str* *,* *optional*) – The redis url. Defaults to redis://localhost:6379.
  * **connection_kwargs** (*Dict* *[* *str* *,* *Any* *]*) – The connection arguments
    for the redis client. Defaults to empty {}.

#### `add_message(message, session_tag=None)`

Insert a single prompt or response into the message history.
A timestamp is associated with it so that it can be later sorted
in sequential ordering after retrieval.

* **Parameters:**
  * **message** (*Dict* *[* *str* *,**str* *]*) – The user prompt or LLM response.
  * **session_tag** (*Optional* *[* *str* *]*) – Tag to be added to entries to link to a specific
    conversation session. Defaults to instance ULID.
* **Return type:**
  None

#### `add_messages(messages, session_tag=None)`

Insert a list of prompts and responses into the message history.
A timestamp is associated with each so that they can be later sorted
in sequential ordering after retrieval.

* **Parameters:**
  * **messages** (*List* *[* *Dict* *[* *str* *,* *str* *]* *]*) – The list of user prompts and LLM responses.
  * **session_tag** (*Optional* *[* *str* *]*) – Tag to be added to entries to link to a specific
    conversation session. Defaults to instance ULID.
* **Return type:**
  None

#### `clear()`

Clears the conversation message history.

* **Return type:**
  None

#### `delete()`

Clear all conversation keys and remove the search index.

* **Return type:**
  None

#### `drop(id=None)`

Remove a specific exchange from the conversation history.

* **Parameters:**
  **id** (*Optional* *[* *str* *]*) – The id of the message entry to delete.
  If None then the last entry is deleted.
* **Return type:**
  None

#### `get_recent(top_k=5, as_text=False, raw=False, session_tag=None, role=None)`

Retrieve the recent message history in sequential order.

* **Parameters:**
  * **top_k** (*int*) – The number of previous messages to return. Default is 5.
  * **as_text** (*bool*) – Whether to return the conversation as a single string,
    or list of alternating prompts and responses.
  * **raw** (*bool*) – Whether to return the full Redis hash entry or just the
    prompt and response.
  * **session_tag** (*Optional* *[* *str* *]*) – Tag of the entries linked to a specific
    conversation session. Defaults to instance ULID.
  * **role** (*Optional* *[* *Union* *[* *str* *,* *List* *[* *str* *]* *]* *]*) – Filter messages by role(s).
    Can be a single role string ("system", "user", "llm", "tool") or
    a list of roles. If None, all roles are returned.
* **Returns:**
  A single string transcription of the messages
  : or list of strings if as_text is false.
* **Return type:**
  Union[str, List[str]]
* **Raises:**
  **ValueError** – if top_k is not an integer greater than or equal to 0,
      or if role contains invalid values.

#### `store(prompt, response, session_tag=None)`

Insert a prompt:response pair into the message history. A timestamp
is associated with each exchange so that they can be later sorted
in sequential ordering after retrieval.

* **Parameters:**
  * **prompt** (*str*) – The user prompt to the LLM.
  * **response** (*str*) – The corresponding LLM response.
  * **session_tag** (*Optional* *[* *str* *]*) – Tag to be added to entries to link to a specific
    conversation session. Defaults to instance ULID.
* **Return type:**
  None

#### `property messages: List[str] | List[Dict[str, str]]`

Returns the full message history.


Query

Overview

Query classes in RedisVL provide a structured way to define simple or complex
queries for different use cases. Each query class wraps the `redis-py` Query module
[https://github.com/redis/redis-py/blob/master/redis/commands/search/query.py](https://github.com/redis/redis-py/blob/master/redis/commands/search/query.py) with extended functionality for ease-of-use.

VectorQuery

`class VectorQuery(vector, vector_field_name, return_fields=None, filter_expression=None, dtype='float32', num_results=10, return_score=True, dialect=2, sort_by=None, in_order=False, hybrid_policy=None, batch_size=None, ef_runtime=None, epsilon=None, search_window_size=None, use_search_history=None, search_buffer_capacity=None, normalize_vector_distance=False)`

Bases: `BaseVectorQuery`, `BaseQuery`

A query for running a vector search along with an optional filter
expression.

* **Parameters:**
  * **vector** (*List* *[* *float* *]*) – The vector to perform the vector search with.
  * **vector_field_name** (*str*) – The name of the vector field to search
    against in the database.
  * **return_fields** (*List* *[* *str* *]*) – The declared fields to return with search
    results.
  * **filter_expression** (*Union* *[* *str* *,* [*FilterExpression*]() *]* *,* *optional*) – A filter to apply
    along with the vector search. Defaults to None.
  * **dtype** (*str* *,* *optional*) – The dtype of the vector. Defaults to
    "float32".
  * **num_results** (*int* *,* *optional*) – The top k results to return from the
    vector search. Defaults to 10.
  * **return_score** (*bool* *,* *optional*) – Whether to return the vector
    distance. Defaults to True.
  * **dialect** (*int* *,* *optional*) – The RediSearch query dialect.
    Defaults to 2.
  * **sort_by** (*Optional* *[* *SortSpec* *]*) – The field(s) to order the results by. Can be:
    - str: single field name
    - Tuple[str, str]: (field_name, "ASC"|"DESC")
    - List: list of fields or tuples
    Note: Only the first field is used for Redis sorting.
    Defaults to None. Results will be ordered by vector distance.
  * **in_order** (*bool*) – Requires the terms in the field to have
    the same order as the terms in the query filter, regardless of
    the offsets between them. Defaults to False.
  * **hybrid_policy** (*Optional* *[* *str* *]*) – Controls how filters are applied during vector search.
    Options are "BATCHES" (paginates through small batches of nearest neighbors) or
    "ADHOC_BF" (computes scores for all vectors passing the filter).
    "BATCHES" mode is typically faster for queries with selective filters.
    "ADHOC_BF" mode is better when filters match a large portion of the dataset.
    Defaults to None, which lets Redis auto-select the optimal policy.
  * **batch_size** (*Optional* *[* *int* *]*) – When hybrid_policy is "BATCHES", controls the number
    of vectors to fetch in each batch. Larger values may improve performance
    at the cost of memory usage. Only applies when hybrid_policy="BATCHES".
    Defaults to None, which lets Redis auto-select an appropriate batch size.
  * **ef_runtime** (*Optional* *[* *int* *]*) – Controls the size of the dynamic candidate list for HNSW
    algorithm at query time. Higher values improve recall at the expense of
    slower search performance. Defaults to None, which uses the index-defined value.
  * **epsilon** (*Optional* *[* *float* *]*) – The range search approximation factor for HNSW and SVS-VAMANA
    indexes. Sets boundaries for candidates within radius \* (1 + epsilon). Higher values
    allow more extensive search and more accurate results at the expense of run time.
    Defaults to None, which uses the index-defined value (typically 0.01).
  * **search_window_size** (*Optional* *[* *int* *]*) – The size of the search window for SVS-VAMANA KNN searches.
    Increasing this value generally yields more accurate but slower search results.
    Defaults to None, which uses the index-defined value (typically 10).
  * **use_search_history** (*Optional* *[* *str* *]*) – For SVS-VAMANA indexes, controls whether to use the
    search buffer or entire search history. Options are "OFF", "ON", or "AUTO".
    "AUTO" is always evaluated internally as "ON". Using the entire history may yield
    a slightly better graph at the cost of more search time.
    Defaults to None, which uses the index-defined value (typically "AUTO").
  * **search_buffer_capacity** (*Optional* *[* *int* *]*) – Tuning parameter for SVS-VAMANA indexes using
    two-level compression (LVQ<X>x<Y> or LeanVec types). Determines the number of vector
    candidates to collect in the first level of search before the re-ranking level.
    Defaults to None, which uses the index-defined value (typically SEARCH_WINDOW_SIZE).
  * **normalize_vector_distance** (*bool*) – Redis supports 3 distance metrics: L2 (euclidean),
    IP (inner product), and COSINE. By default, L2 distance returns an unbounded value.
    COSINE distance returns a value between 0 and 2. IP returns a value determined by
    the magnitude of the vector. Setting this flag to true converts COSINE and L2 distance
    to a similarity score between 0 and 1. Note: setting this flag to true for IP will
    throw a warning since by definition COSINE similarity is normalized IP.
* **Raises:**
  **TypeError** – If filter_expression is not of type redisvl.query.FilterExpression

#### `NOTE`
Learn more about vector queries in Redis: [https://redis.io/docs/latest/develop/ai/search-and-query/vectors/#knn-vector-search](https://redis.io/docs/latest/develop/ai/search-and-query/vectors/#knn-vector-search)

#### `dialect(dialect)`

Add a dialect field to the query.

- **dialect** - dialect version to execute the query under

* **Parameters:**
  **dialect** (*int*)
* **Return type:**
  *Query*

#### `expander(expander)`

Add a expander field to the query.

- **expander** - the name of the expander

* **Parameters:**
  **expander** (*str*)
* **Return type:**
  *Query*

#### `in_order()`

Match only documents where the query terms appear in
the same order in the document.
i.e. for the query "hello world", we do not match "world hello"

* **Return type:**
  *Query*

#### `language(language)`

Analyze the query as being in the specified language.

* **Parameters:**
  **language** (*str*) – The language (e.g. chinese or english)
* **Return type:**
  *Query*

#### `limit_fields(*fields)`

Limit the search to specific TEXT fields only.

- **fields**: A list of strings, case sensitive field names

from the defined schema.

* **Parameters:**
  **fields** (*List* *[* *str* *]*)
* **Return type:**
  *Query*

#### `limit_ids(*ids)`

Limit the results to a specific set of pre-known document
ids of any length.

* **Return type:**
  *Query*

#### `no_content()`

Set the query to only return ids and not the document content.

* **Return type:**
  *Query*

#### `no_stopwords()`

Prevent the query from being filtered for stopwords.
Only useful in very big queries that you are certain contain
no stopwords.

* **Return type:**
  *Query*

#### `paging(offset, num)`

Set the paging for the query (defaults to 0..10).

- **offset**: Paging offset for the results. Defaults to 0
- **num**: How many results do we want

* **Parameters:**
  * **offset** (*int*)
  * **num** (*int*)
* **Return type:**
  *Query*

#### `query_string()`

Return the query string of this query only.

* **Return type:**
  str

#### `return_fields(*fields, skip_decode=None)`

Set the fields to return with search results.

* **Parameters:**
  * **\*fields** – Variable number of field names to return.
  * **skip_decode** (*str* *|* *List* *[* *str* *]*  *|* *None*) – Optional field name or list of field names that should not be
    decoded. Useful for binary data like embeddings.
* **Returns:**
  Returns the query object for method chaining.
* **Return type:**
  self
* **Raises:**
  **TypeError** – If skip_decode is not a string, list, or None.

#### `scorer(scorer)`

Use a different scoring function to evaluate document relevance.
Default is TFIDF.

Since Redis 8.0 default was changed to BM25STD.

* **Parameters:**
  **scorer** (*str*) – The scoring function to use
  (e.g. TFIDF.DOCNORM or BM25)
* **Return type:**
  *Query*

#### `set_batch_size(batch_size)`

Set the batch size for the query.

* **Parameters:**
  **batch_size** (*int*) – The batch size to use when hybrid_policy is "BATCHES".
* **Raises:**
  * **TypeError** – If batch_size is not an integer
  * **ValueError** – If batch_size is not positive

#### `set_ef_runtime(ef_runtime)`

Set the EF_RUNTIME parameter for the query.

* **Parameters:**
  **ef_runtime** (*int*) – The EF_RUNTIME value to use for HNSW algorithm.
  Higher values improve recall at the expense of slower search.
* **Raises:**
  * **TypeError** – If ef_runtime is not an integer
  * **ValueError** – If ef_runtime is not positive

#### `set_epsilon(epsilon)`

Set the epsilon parameter for the query.

* **Parameters:**
  **epsilon** (*float*) – The range search approximation factor for HNSW and SVS-VAMANA
  indexes. Sets boundaries for candidates within radius \* (1 + epsilon).
  Higher values allow more extensive search and more accurate results at the
  expense of run time.
* **Raises:**
  * **TypeError** – If epsilon is not a float or int
  * **ValueError** – If epsilon is negative

#### `set_filter(filter_expression=None)`

Set the filter expression for the query.

* **Parameters:**
  **filter_expression** (*Optional* *[* *Union* *[* *str* *,* [*FilterExpression*]() *]* *]* *,* *optional*) – The filter
  expression or query string to use on the query.
* **Raises:**
  **TypeError** – If filter_expression is not a valid FilterExpression or string.

#### `set_hybrid_policy(hybrid_policy)`

Set the hybrid policy for the query.

* **Parameters:**
  **hybrid_policy** (*str*) – The hybrid policy to use. Options are "BATCHES"
  or "ADHOC_BF".
* **Raises:**
  **ValueError** – If hybrid_policy is not one of the valid options

#### `set_search_buffer_capacity(search_buffer_capacity)`

Set the SEARCH_BUFFER_CAPACITY parameter for the query.

* **Parameters:**
  **search_buffer_capacity** (*int*) – Tuning parameter for SVS-VAMANA indexes using
  two-level compression. Determines the number of vector candidates to collect
  in the first level of search before the re-ranking level.
* **Raises:**
  * **TypeError** – If search_buffer_capacity is not an integer
  * **ValueError** – If search_buffer_capacity is not positive

#### `set_search_window_size(search_window_size)`

Set the SEARCH_WINDOW_SIZE parameter for the query.

* **Parameters:**
  **search_window_size** (*int*) – The size of the search window for SVS-VAMANA KNN searches.
  Increasing this value generally yields more accurate but slower search results.
* **Raises:**
  * **TypeError** – If search_window_size is not an integer
  * **ValueError** – If search_window_size is not positive

#### `set_use_search_history(use_search_history)`

Set the USE_SEARCH_HISTORY parameter for the query.

* **Parameters:**
  **use_search_history** (*str*) – For SVS-VAMANA indexes, controls whether to use the
  search buffer or entire search history. Options are "OFF", "ON", or "AUTO".
* **Raises:**
  * **TypeError** – If use_search_history is not a string
  * **ValueError** – If use_search_history is not one of "OFF", "ON", or "AUTO"

#### `slop(slop)`

Allow a maximum of N intervening non matched terms between
phrase terms (0 means exact phrase).

* **Parameters:**
  **slop** (*int*)
* **Return type:**
  *Query*

#### `sort_by(sort_spec=None, asc=True)`

Set the sort order for query results.

This method supports sorting by single or multiple fields. Note that Redis Search
natively supports only a single SORTBY field. When multiple fields are specified,
only the FIRST field is used for the Redis SORTBY clause.

* **Parameters:**
  * **sort_spec** (*str* *|* *Tuple* *[* *str* *,* *str* *]*  *|* *List* *[* *str* *|* *Tuple* *[* *str* *,* *str* *]* *]*  *|* *None*) – Sort specification in various formats:
    - str: single field name
    - Tuple[str, str]: (field_name, "ASC"|"DESC")
    - List: list of field names or tuples
  * **asc** (*bool*) – Default sort direction when not specified (only used when sort_spec is a string).
    Defaults to True (ascending).
* **Returns:**
  Returns the query object for method chaining.
* **Return type:**
  self
* **Raises:**
  * **TypeError** – If sort_spec is not a valid type.
  * **ValueError** – If direction is not "ASC" or "DESC".

`Examples`

[code example]

#### `NOTE`
When multiple fields are specified, only the first field is used for sorting
in Redis. Future versions may support multi-field sorting through post-query
sorting in Python.

#### `timeout(timeout)`

overrides the timeout parameter of the module

* **Parameters:**
  **timeout** (*float*)
* **Return type:**
  *Query*

#### `verbatim()`

Set the query to be verbatim, i.e. use no query expansion
or stemming.

* **Return type:**
  *Query*

#### `with_payloads()`

Ask the engine to return document payloads.

* **Return type:**
  *Query*

#### `with_scores()`

Ask the engine to return document search scores.

* **Return type:**
  *Query*

#### `property batch_size: int | None`

Return the batch size for the query.

* **Returns:**
  The batch size for the query.
* **Return type:**
  Optional[int]

#### `property ef_runtime: int | None`

Return the EF_RUNTIME parameter for the query.

* **Returns:**
  The EF_RUNTIME value for the query.
* **Return type:**
  Optional[int]

#### `property epsilon: float | None`

Return the epsilon parameter for the query.

* **Returns:**
  The epsilon value for the query.
* **Return type:**
  Optional[float]

#### `property filter: str | `[`FilterExpression`]()` `

The filter expression for the query.

#### `property hybrid_policy: str | None`

Return the hybrid policy for the query.

* **Returns:**
  The hybrid policy for the query.
* **Return type:**
  Optional[str]

#### `property params: Dict[str, Any]`

Return the parameters for the query.

* **Returns:**
  The parameters for the query.
* **Return type:**
  Dict[str, Any]

#### `property query: BaseQuery`

Return self as the query object.

#### `property search_buffer_capacity: int | None`

Return the SEARCH_BUFFER_CAPACITY parameter for the query.

* **Returns:**
  The SEARCH_BUFFER_CAPACITY value for the query.
* **Return type:**
  Optional[int]

#### `property search_window_size: int | None`

Return the SEARCH_WINDOW_SIZE parameter for the query.

* **Returns:**
  The SEARCH_WINDOW_SIZE value for the query.
* **Return type:**
  Optional[int]

#### `property use_search_history: str | None`

Return the USE_SEARCH_HISTORY parameter for the query.

* **Returns:**
  The USE_SEARCH_HISTORY value for the query.
* **Return type:**
  Optional[str]

#### `NOTE`
**Runtime Parameters for Performance Tuning**

VectorQuery supports runtime parameters for HNSW and SVS-VAMANA indexes that can be adjusted at query time without rebuilding the index:

**HNSW Parameters:**

- `ef_runtime`: Controls search accuracy (higher = better recall, slower search)

**SVS-VAMANA Parameters:**

- `search_window_size`: Size of search window for KNN searches
- `use_search_history`: Whether to use search buffer (OFF/ON/AUTO)
- `search_buffer_capacity`: Tuning parameter for 2-level compression

Example with HNSW runtime parameters:

[code example]

Example with SVS-VAMANA runtime parameters:

[code example]

VectorRangeQuery

`class VectorRangeQuery(vector, vector_field_name, return_fields=None, filter_expression=None, dtype='float32', distance_threshold=0.2, epsilon=None, search_window_size=None, use_search_history=None, search_buffer_capacity=None, num_results=10, return_score=True, dialect=2, sort_by=None, in_order=False, hybrid_policy=None, batch_size=None, normalize_vector_distance=False)`

Bases: `BaseVectorQuery`, `BaseQuery`

A query for running a filtered vector search based on semantic
distance threshold.

* **Parameters:**
  * **vector** (*List* *[* *float* *]*) – The vector to perform the range query with.
  * **vector_field_name** (*str*) – The name of the vector field to search
    against in the database.
  * **return_fields** (*List* *[* *str* *]*) – The declared fields to return with search
    results.
  * **filter_expression** (*Union* *[* *str* *,* [*FilterExpression*]() *]* *,* *optional*) – A filter to apply
    along with the range query. Defaults to None.
  * **dtype** (*str* *,* *optional*) – The dtype of the vector. Defaults to
    "float32".
  * **distance_threshold** (*float*) – The threshold for vector distance.
    A smaller threshold indicates a stricter semantic search.
    Defaults to 0.2.
  * **epsilon** (*Optional* *[* *float* *]*) – The relative factor for vector range queries,
    setting boundaries for candidates within radius \* (1 + epsilon).
    This controls how extensive the search is beyond the specified radius.
    Higher values increase recall at the expense of performance.
    Defaults to None, which uses the index-defined epsilon (typically 0.01).
  * **search_window_size** (*Optional* *[* *int* *]*) – The size of the search window for SVS-VAMANA range searches.
    Increasing this value generally yields more accurate but slower search results.
    Defaults to None, which uses the index-defined value (typically 10).
  * **use_search_history** (*Optional* *[* *str* *]*) – For SVS-VAMANA indexes, controls whether to use the
    search buffer or entire search history. Options are "OFF", "ON", or "AUTO".
    "AUTO" is always evaluated internally as "ON". Using the entire history may yield
    a slightly better graph at the cost of more search time.
    Defaults to None, which uses the index-defined value (typically "AUTO").
  * **search_buffer_capacity** (*Optional* *[* *int* *]*) – Tuning parameter for SVS-VAMANA indexes using
    two-level compression (LVQ<X>x<Y> or LeanVec types). Determines the number of vector
    candidates to collect in the first level of search before the re-ranking level.
    Defaults to None, which uses the index-defined value (typically SEARCH_WINDOW_SIZE).
  * **num_results** (*int*) – The MAX number of results to return.
    Defaults to 10.
  * **return_score** (*bool* *,* *optional*) – Whether to return the vector
    distance. Defaults to True.
  * **dialect** (*int* *,* *optional*) – The RediSearch query dialect.
    Defaults to 2.
  * **sort_by** (*Optional* *[* *SortSpec* *]*) – The field(s) to order the results by. Can be:
    - str: single field name
    - Tuple[str, str]: (field_name, "ASC"|"DESC")
    - List: list of fields or tuples
    Note: Only the first field is used for Redis sorting.
    Defaults to None. Results will be ordered by vector distance.
  * **in_order** (*bool*) – Requires the terms in the field to have
    the same order as the terms in the query filter, regardless of
    the offsets between them. Defaults to False.
  * **hybrid_policy** (*Optional* *[* *str* *]*) – Controls how filters are applied during vector search.
    Options are "BATCHES" (paginates through small batches of nearest neighbors) or
    "ADHOC_BF" (computes scores for all vectors passing the filter).
    "BATCHES" mode is typically faster for queries with selective filters.
    "ADHOC_BF" mode is better when filters match a large portion of the dataset.
    Defaults to None, which lets Redis auto-select the optimal policy.
  * **batch_size** (*Optional* *[* *int* *]*) – When hybrid_policy is "BATCHES", controls the number
    of vectors to fetch in each batch. Larger values may improve performance
    at the cost of memory usage. Only applies when hybrid_policy="BATCHES".
    Defaults to None, which lets Redis auto-select an appropriate batch size.
  * **normalize_vector_distance** (*bool*) – Redis supports 3 distance metrics: L2 (euclidean),
    IP (inner product), and COSINE. By default, L2 distance returns an unbounded value.
    COSINE distance returns a value between 0 and 2. IP returns a value determined by
    the magnitude of the vector. Setting this flag to true converts COSINE and L2 distance
    to a similarity score between 0 and 1. Note: setting this flag to true for IP will
    throw a warning since by definition COSINE similarity is normalized IP.
* **Raises:**
  **TypeError** – If filter_expression is not of type redisvl.query.FilterExpression

#### `NOTE`
Learn more about vector range queries: [https://redis.io/docs/interact/search-and-query/search/vectors/#range-query](https://redis.io/docs/interact/search-and-query/search/vectors/#range-query)

#### `dialect(dialect)`

Add a dialect field to the query.

- **dialect** - dialect version to execute the query under

* **Parameters:**
  **dialect** (*int*)
* **Return type:**
  *Query*

#### `expander(expander)`

Add a expander field to the query.

- **expander** - the name of the expander

* **Parameters:**
  **expander** (*str*)
* **Return type:**
  *Query*

#### `in_order()`

Match only documents where the query terms appear in
the same order in the document.
i.e. for the query "hello world", we do not match "world hello"

* **Return type:**
  *Query*

#### `language(language)`

Analyze the query as being in the specified language.

* **Parameters:**
  **language** (*str*) – The language (e.g. chinese or english)
* **Return type:**
  *Query*

#### `limit_fields(*fields)`

Limit the search to specific TEXT fields only.

- **fields**: A list of strings, case sensitive field names

from the defined schema.

* **Parameters:**
  **fields** (*List* *[* *str* *]*)
* **Return type:**
  *Query*

#### `limit_ids(*ids)`

Limit the results to a specific set of pre-known document
ids of any length.

* **Return type:**
  *Query*

#### `no_content()`

Set the query to only return ids and not the document content.

* **Return type:**
  *Query*

#### `no_stopwords()`

Prevent the query from being filtered for stopwords.
Only useful in very big queries that you are certain contain
no stopwords.

* **Return type:**
  *Query*

#### `paging(offset, num)`

Set the paging for the query (defaults to 0..10).

- **offset**: Paging offset for the results. Defaults to 0
- **num**: How many results do we want

* **Parameters:**
  * **offset** (*int*)
  * **num** (*int*)
* **Return type:**
  *Query*

#### `query_string()`

Return the query string of this query only.

* **Return type:**
  str

#### `return_fields(*fields, skip_decode=None)`

Set the fields to return with search results.

* **Parameters:**
  * **\*fields** – Variable number of field names to return.
  * **skip_decode** (*str* *|* *List* *[* *str* *]*  *|* *None*) – Optional field name or list of field names that should not be
    decoded. Useful for binary data like embeddings.
* **Returns:**
  Returns the query object for method chaining.
* **Return type:**
  self
* **Raises:**
  **TypeError** – If skip_decode is not a string, list, or None.

#### `scorer(scorer)`

Use a different scoring function to evaluate document relevance.
Default is TFIDF.

Since Redis 8.0 default was changed to BM25STD.

* **Parameters:**
  **scorer** (*str*) – The scoring function to use
  (e.g. TFIDF.DOCNORM or BM25)
* **Return type:**
  *Query*

#### `set_batch_size(batch_size)`

Set the batch size for the query.

* **Parameters:**
  **batch_size** (*int*) – The batch size to use when hybrid_policy is "BATCHES".
* **Raises:**
  * **TypeError** – If batch_size is not an integer
  * **ValueError** – If batch_size is not positive

#### `set_distance_threshold(distance_threshold)`

Set the distance threshold for the query.

* **Parameters:**
  **distance_threshold** (*float*) – Vector distance threshold.
* **Raises:**
  * **TypeError** – If distance_threshold is not a float or int
  * **ValueError** – If distance_threshold is negative

#### `set_epsilon(epsilon)`

Set the epsilon parameter for the range query.

* **Parameters:**
  **epsilon** (*float*) – The relative factor for vector range queries,
  setting boundaries for candidates within radius \* (1 + epsilon).
* **Raises:**
  * **TypeError** – If epsilon is not a float or int
  * **ValueError** – If epsilon is negative

#### `set_filter(filter_expression=None)`

Set the filter expression for the query.

* **Parameters:**
  **filter_expression** (*Optional* *[* *Union* *[* *str* *,* [*FilterExpression*]() *]* *]* *,* *optional*) – The filter
  expression or query string to use on the query.
* **Raises:**
  **TypeError** – If filter_expression is not a valid FilterExpression or string.

#### `set_hybrid_policy(hybrid_policy)`

Set the hybrid policy for the query.

* **Parameters:**
  **hybrid_policy** (*str*) – The hybrid policy to use. Options are "BATCHES"
  or "ADHOC_BF".
* **Raises:**
  **ValueError** – If hybrid_policy is not one of the valid options

#### `set_search_buffer_capacity(search_buffer_capacity)`

Set the SEARCH_BUFFER_CAPACITY parameter for the range query.

* **Parameters:**
  **search_buffer_capacity** (*int*) – Tuning parameter for SVS-VAMANA indexes using
  two-level compression.
* **Raises:**
  * **TypeError** – If search_buffer_capacity is not an integer
  * **ValueError** – If search_buffer_capacity is not positive

#### `set_search_window_size(search_window_size)`

Set the SEARCH_WINDOW_SIZE parameter for the range query.

* **Parameters:**
  **search_window_size** (*int*) – The size of the search window for SVS-VAMANA range searches.
* **Raises:**
  * **TypeError** – If search_window_size is not an integer
  * **ValueError** – If search_window_size is not positive

#### `set_use_search_history(use_search_history)`

Set the USE_SEARCH_HISTORY parameter for the range query.

* **Parameters:**
  **use_search_history** (*str*) – Controls whether to use the search buffer or entire history.
  Must be one of "OFF", "ON", or "AUTO".
* **Raises:**
  * **TypeError** – If use_search_history is not a string
  * **ValueError** – If use_search_history is not one of the valid options

#### `slop(slop)`

Allow a maximum of N intervening non matched terms between
phrase terms (0 means exact phrase).

* **Parameters:**
  **slop** (*int*)
* **Return type:**
  *Query*

#### `sort_by(sort_spec=None, asc=True)`

Set the sort order for query results.

This method supports sorting by single or multiple fields. Note that Redis Search
natively supports only a single SORTBY field. When multiple fields are specified,
only the FIRST field is used for the Redis SORTBY clause.

* **Parameters:**
  * **sort_spec** (*str* *|* *Tuple* *[* *str* *,* *str* *]*  *|* *List* *[* *str* *|* *Tuple* *[* *str* *,* *str* *]* *]*  *|* *None*) – Sort specification in various formats:
    - str: single field name
    - Tuple[str, str]: (field_name, "ASC"|"DESC")
    - List: list of field names or tuples
  * **asc** (*bool*) – Default sort direction when not specified (only used when sort_spec is a string).
    Defaults to True (ascending).
* **Returns:**
  Returns the query object for method chaining.
* **Return type:**
  self
* **Raises:**
  * **TypeError** – If sort_spec is not a valid type.
  * **ValueError** – If direction is not "ASC" or "DESC".

`Examples`

[code example]

#### `NOTE`
When multiple fields are specified, only the first field is used for sorting
in Redis. Future versions may support multi-field sorting through post-query
sorting in Python.

#### `timeout(timeout)`

overrides the timeout parameter of the module

* **Parameters:**
  **timeout** (*float*)
* **Return type:**
  *Query*

#### `verbatim()`

Set the query to be verbatim, i.e. use no query expansion
or stemming.

* **Return type:**
  *Query*

#### `with_payloads()`

Ask the engine to return document payloads.

* **Return type:**
  *Query*

#### `with_scores()`

Ask the engine to return document search scores.

* **Return type:**
  *Query*

#### `property batch_size: int | None`

Return the batch size for the query.

* **Returns:**
  The batch size for the query.
* **Return type:**
  Optional[int]

#### `property distance_threshold: float`

Return the distance threshold for the query.

* **Returns:**
  The distance threshold for the query.
* **Return type:**
  float

#### `property epsilon: float | None`

Return the epsilon for the query.

* **Returns:**
  The epsilon for the query, or None if not set.
* **Return type:**
  Optional[float]

#### `property filter: str | `[`FilterExpression`]()` `

The filter expression for the query.

#### `property hybrid_policy: str | None`

Return the hybrid policy for the query.

* **Returns:**
  The hybrid policy for the query.
* **Return type:**
  Optional[str]

#### `property params: Dict[str, Any]`

Return the parameters for the query.

* **Returns:**
  The parameters for the query.
* **Return type:**
  Dict[str, Any]

#### `property query: BaseQuery`

Return self as the query object.

#### `property search_buffer_capacity: int | None`

Return the SEARCH_BUFFER_CAPACITY parameter for the query.

* **Returns:**
  The SEARCH_BUFFER_CAPACITY value for the query.
* **Return type:**
  Optional[int]

#### `property search_window_size: int | None`

Return the SEARCH_WINDOW_SIZE parameter for the query.

* **Returns:**
  The SEARCH_WINDOW_SIZE value for the query.
* **Return type:**
  Optional[int]

#### `property use_search_history: str | None`

Return the USE_SEARCH_HISTORY parameter for the query.

* **Returns:**
  The USE_SEARCH_HISTORY value for the query.
* **Return type:**
  Optional[str]

#### `NOTE`
**Runtime Parameters for Range Queries**

VectorRangeQuery supports runtime parameters for controlling range search behavior:

**HNSW & SVS-VAMANA Parameters:**

- `epsilon`: Range search approximation factor (default: 0.01)

**SVS-VAMANA Parameters:**

- `search_window_size`: Size of search window
- `use_search_history`: Whether to use search buffer (OFF/ON/AUTO)
- `search_buffer_capacity`: Tuning parameter for 2-level compression

Example:

[code example]

HybridQuery

`class HybridQuery(*args, **kwargs)`

Bases: `AggregateHybridQuery`

Backward compatibility wrapper for AggregateHybridQuery.

#### `Deprecated`
Deprecated since version HybridQuery: is a backward compatibility wrapper around AggregateHybridQuery
and will eventually be replaced with a new hybrid query implementation.
To maintain current functionality please use AggregateHybridQuery directly.",

Instantiates a AggregateHybridQuery object.

* **Parameters:**
  * **text** (*str*) – The text to search for.
  * **text_field_name** (*str*) – The text field name to search in.
  * **vector** (*Union* *[* *bytes* *,* *List* *[* *float* *]* *]*) – The vector to perform vector similarity search.
  * **vector_field_name** (*str*) – The vector field name to search in.
  * **text_scorer** (*str* *,* *optional*) – The text scorer to use. Options are {TFIDF, TFIDF.DOCNORM,
    BM25, DISMAX, DOCSCORE, BM25STD}. Defaults to "BM25STD".
  * **filter_expression** (*Optional* *[*[*FilterExpression*]() *]* *,* *optional*) – The filter expression to use.
    Defaults to None.
  * **alpha** (*float* *,* *optional*) – The weight of the vector similarity. Documents will be scored
    as: hybrid_score = (alpha) \* vector_score + (1-alpha) \* text_score.
    Defaults to 0.7.
  * **dtype** (*str* *,* *optional*) – The data type of the vector. Defaults to "float32".
  * **num_results** (*int* *,* *optional*) – The number of results to return. Defaults to 10.
  * **return_fields** (*Optional* *[* *List* *[* *str* *]* *]* *,* *optional*) – The fields to return. Defaults to None.
  * **stopwords** (*Optional* *[* *Union* *[* *str* *,* *Set* *[* *str* *]* *]* *]* *,* *optional*) –

    The stopwords to remove from the
    provided text prior to searchuse. 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.

    Note: This parameter controls query-time stopword filtering (client-side).
    For index-level stopwords configuration (server-side), see IndexInfo.stopwords.
    Using query-time stopwords with index-level STOPWORDS 0 is counterproductive.
  * **dialect** (*int* *,* *optional*) – The Redis dialect version. Defaults to 2.
  * **text_weights** (*Optional* *[* *Dict* *[* *str* *,* *float* *]* *]*) – The importance weighting of individual words
    within the query text. Defaults to None, as no modifications will be made to the
    text_scorer score.

#### `NOTE`
AggregateHybridQuery uses FT.AGGREGATE commands which do NOT support runtime
parameters. For runtime parameter support (ef_runtime, search_window_size, etc.),
use VectorQuery or VectorRangeQuery which use FT.SEARCH commands.

* **Raises:**
  * **ValueError** – If the text string is empty, or if the text string becomes empty after
        stopwords are removed.
  * **TypeError** – If the stopwords are not a set, list, or tuple of strings.

#### `add_scores()`

If set, includes the score as an ordinary field of the row.

* **Return type:**
  *AggregateRequest*

#### `apply(**kwexpr)`

Specify one or more projection expressions to add to each result

`Parameters`

- **kwexpr**: One or more key-value pairs for a projection. The key is
  : the alias for the projection, and the value is the projection
    expression itself, for example apply(square_root="sqrt(@foo)")

* **Return type:**
  *AggregateRequest*

#### `dialect(dialect)`

Add a dialect field to the aggregate command.

- **dialect** - dialect version to execute the query under

* **Parameters:**
  **dialect** (*int*)
* **Return type:**
  *AggregateRequest*

#### `filter(expressions)`

Specify filter for post-query results using predicates relating to
values in the result set.

`Parameters`

- **fields**: Fields to group by. This can either be a single string,
  : or a list of strings.

* **Parameters:**
  **expressions** (*str* *|* *List* *[* *str* *]*)
* **Return type:**
  *AggregateRequest*

#### `group_by(fields, *reducers)`

Specify by which fields to group the aggregation.

`Parameters`

- **fields**: Fields to group by. This can either be a single string,
  : or a list of strings. both cases, the field should be specified as
    @field.
- **reducers**: One or more reducers. Reducers may be found in the
  : aggregation module.

* **Parameters:**
  * **fields** (*List* *[* *str* *]*)
  * **reducers** (*Reducer* *|* *List* *[* *Reducer* *]*)
* **Return type:**
  *AggregateRequest*

#### `limit(offset, num)`

Sets the limit for the most recent group or query.

If no group has been defined yet (via group_by()) then this sets
the limit for the initial pool of results from the query. Otherwise,
this limits the number of items operated on from the previous group.

Setting a limit on the initial search results may be useful when
attempting to execute an aggregation on a sample of a large data set.

`Parameters`

- **offset**: Result offset from which to begin paging
- **num**: Number of results to return

Example of sorting the initial results:

``
AggregateRequest("@sale_amount:[10000, inf]")            .limit(0, 10)            .group_by("@state", r.count())
``

Will only group by the states found in the first 10 results of the
query @sale_amount:[10000, inf]. On the other hand,

``
AggregateRequest("@sale_amount:[10000, inf]")            .limit(0, 1000)            .group_by("@state", r.count()            .limit(0, 10)
``

Will group all the results matching the query, but only return the
first 10 groups.

If you only wish to return a *top-N* style query, consider using
sort_by() instead.

* **Parameters:**
  * **offset** (*int*)
  * **num** (*int*)
* **Return type:**
  *AggregateRequest*

#### `load(*fields)`

Indicate the fields to be returned in the response. These fields are
returned in addition to any others implicitly specified.

`Parameters`

- **fields**: If fields not specified, all the fields will be loaded.

Otherwise, fields should be given in the format of @field.

* **Parameters:**
  **fields** (*str*)
* **Return type:**
  *AggregateRequest*

#### `scorer(scorer)`

Use a different scoring function to evaluate document relevance.
Default is TFIDF.

* **Parameters:**
  **scorer** (*str*) – The scoring function to use
  (e.g. TFIDF.DOCNORM or BM25)
* **Return type:**
  *AggregateRequest*

#### `set_text_weights(weights)`

Set or update the text weights for the query.

* **Parameters:**
  * **text_weights** – Dictionary of word:weight mappings
  * **weights** (*Dict* *[* *str* *,* *float* *]*)

#### `sort_by(*fields, **kwargs)`

Indicate how the results should be sorted. This can also be used for
*top-N* style queries

`Parameters`

- **fields**: The fields by which to sort. This can be either a single
  : field or a list of fields. If you wish to specify order, you can
    use the Asc or Desc wrapper classes.
- **max**: Maximum number of results to return. This can be
  : used instead of LIMIT and is also faster.

Example of sorting by foo ascending and bar descending:

``
sort_by(Asc("@foo"), Desc("@bar"))
``

Return the top 10 customers:

``
AggregateRequest()            .group_by("@customer", r.sum("@paid").alias(FIELDNAME))            .sort_by(Desc("@paid"), max=10)
``

* **Parameters:**
  **fields** (*str*)
* **Return type:**
  *AggregateRequest*

#### `with_schema()`

If set, the schema property will contain a list of [field, type]
entries in the result object.

* **Return type:**
  *AggregateRequest*

#### `property params: Dict[str, Any]`

Return the parameters for the aggregation.

* **Returns:**
  The parameters for the aggregation.
* **Return type:**
  Dict[str, Any]

#### `property stopwords: Set[str]`

Return the stopwords used in the query.
:returns: The stopwords used in the query.
:rtype: Set[str]

#### `property text_weights: Dict[str, float]`

Get the text weights.

* **Returns:**
  weight mappings.
* **Return type:**
  Dictionary of word

#### `NOTE`
The `stopwords` parameter in [HybridQuery](#hybridquery) (and `AggregateHybridQuery`) controls query-time stopword filtering (client-side).
For index-level stopwords configuration (server-side), see `redisvl.schema.IndexInfo.stopwords`.
Using query-time stopwords with index-level `STOPWORDS 0` is counterproductive.

#### `NOTE`
**Runtime Parameters for Hybrid Queries**

**Important:** AggregateHybridQuery uses FT.AGGREGATE commands which do NOT support runtime parameters.
Runtime parameters (`ef_runtime`, `search_window_size`, `use_search_history`, `search_buffer_capacity`)
are only supported with FT.SEARCH commands.

For runtime parameter support, use [VectorQuery](#vectorquery) or [VectorRangeQuery](#vectorrangequery) instead of AggregateHybridQuery.

Example with VectorQuery (supports runtime parameters):

[code example]

TextQuery

`class TextQuery(text, text_field_name, text_scorer='BM25STD', filter_expression=None, return_fields=None, num_results=10, return_score=True, dialect=2, sort_by=None, in_order=False, params=None, stopwords='english', text_weights=None)`

Bases: `BaseQuery`

TextQuery is a query for running a full text search, along with an optional filter expression.

[code example]

A query for running a full text search, along with an optional filter expression.

* **Parameters:**
  * **text** (*str*) – The text string to perform the text search with.
  * **text_field_name** (*Union* *[* *str* *,* *Dict* *[* *str* *,* *float* *]* *]*) – The name of the document field to perform
    text search on, or a dictionary mapping field names to their weights.
  * **text_scorer** (*str* *,* *optional*) – The text scoring algorithm to use.
    Defaults to BM25STD. Options are {TFIDF, BM25STD, BM25, TFIDF.DOCNORM, DISMAX, DOCSCORE}.
    See [https://redis.io/docs/latest/develop/interact/search-and-query/advanced-concepts/scoring/](https://redis.io/docs/latest/develop/interact/search-and-query/advanced-concepts/scoring/)
  * **filter_expression** (*Union* *[* *str* *,* [*FilterExpression*]() *]* *,* *optional*) – A filter to apply
    along with the text search. Defaults to None.
  * **return_fields** (*List* *[* *str* *]*) – The declared fields to return with search
    results.
  * **num_results** (*int* *,* *optional*) – The top k results to return from the
    search. Defaults to 10.
  * **return_score** (*bool* *,* *optional*) – Whether to return the text score.
    Defaults to True.
  * **dialect** (*int* *,* *optional*) – The RediSearch query dialect.
    Defaults to 2.
  * **sort_by** (*Optional* *[* *SortSpec* *]*) – The field(s) to order the results by. Can be:
    - str: single field name
    - Tuple[str, str]: (field_name, "ASC"|"DESC")
    - List: list of fields or tuples
    Note: Only the first field is used for Redis sorting.
    Defaults to None. Results will be ordered by text score.
  * **in_order** (*bool*) – Requires the terms in the field to have
    the same order as the terms in the query filter, regardless of
    the offsets between them. Defaults to False.
  * **params** (*Optional* *[* *Dict* *[* *str* *,* *Any* *]* *]* *,* *optional*) – The parameters for the query.
    Defaults to None.
  * **stopwords** (*Optional* *[* *Union* *[* *str* *,* *Set* *[* *str* *]* *]*) –

    The set of stop words to remove
    from the query text (client-side filtering). If a language like ‘english’ or ‘spanish’ is provided
    a default set of stopwords for that language will be used. Users may specify
    their own stop words by providing a List or Set of words. if set to None,
    then no words will be removed. Defaults to ‘english’.

    Note: This parameter controls query-time stopword filtering (client-side).
    For index-level stopwords configuration (server-side), see IndexInfo.stopwords.
    Using query-time stopwords with index-level STOPWORDS 0 is counterproductive.
  * **text_weights** (*Optional* *[* *Dict* *[* *str* *,* *float* *]* *]*) – The importance weighting of individual words
    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.
  * **TypeError** – If stopwords is not a valid iterable set of strings.

#### `dialect(dialect)`

Add a dialect field to the query.

- **dialect** - dialect version to execute the query under

* **Parameters:**
  **dialect** (*int*)
* **Return type:**
  *Query*

#### `expander(expander)`

Add a expander field to the query.

- **expander** - the name of the expander

* **Parameters:**
  **expander** (*str*)
* **Return type:**
  *Query*

#### `in_order()`

Match only documents where the query terms appear in
the same order in the document.
i.e. for the query "hello world", we do not match "world hello"

* **Return type:**
  *Query*

#### `language(language)`

Analyze the query as being in the specified language.

* **Parameters:**
  **language** (*str*) – The language (e.g. chinese or english)
* **Return type:**
  *Query*

#### `limit_fields(*fields)`

Limit the search to specific TEXT fields only.

- **fields**: A list of strings, case sensitive field names

from the defined schema.

* **Parameters:**
  **fields** (*List* *[* *str* *]*)
* **Return type:**
  *Query*

#### `limit_ids(*ids)`

Limit the results to a specific set of pre-known document
ids of any length.

* **Return type:**
  *Query*

#### `no_content()`

Set the query to only return ids and not the document content.

* **Return type:**
  *Query*

#### `no_stopwords()`

Prevent the query from being filtered for stopwords.
Only useful in very big queries that you are certain contain
no stopwords.

* **Return type:**
  *Query*

#### `paging(offset, num)`

Set the paging for the query (defaults to 0..10).

- **offset**: Paging offset for the results. Defaults to 0
- **num**: How many results do we want

* **Parameters:**
  * **offset** (*int*)
  * **num** (*int*)
* **Return type:**
  *Query*

#### `query_string()`

Return the query string of this query only.

* **Return type:**
  str

#### `return_fields(*fields, skip_decode=None)`

Set the fields to return with search results.

* **Parameters:**
  * **\*fields** – Variable number of field names to return.
  * **skip_decode** (*str* *|* *List* *[* *str* *]*  *|* *None*) – Optional field name or list of field names that should not be
    decoded. Useful for binary data like embeddings.
* **Returns:**
  Returns the query object for method chaining.
* **Return type:**
  self
* **Raises:**
  **TypeError** – If skip_decode is not a string, list, or None.

#### `scorer(scorer)`

Use a different scoring function to evaluate document relevance.
Default is TFIDF.

Since Redis 8.0 default was changed to BM25STD.

* **Parameters:**
  **scorer** (*str*) – The scoring function to use
  (e.g. TFIDF.DOCNORM or BM25)
* **Return type:**
  *Query*

#### `set_field_weights(field_weights)`

Set or update the field weights for the query.

* **Parameters:**
  **field_weights** (*str* *|* *Dict* *[* *str* *,* *float* *]*) – Either a single field name or dictionary of field:weight mappings

#### `set_filter(filter_expression=None)`

Set the filter expression for the query.

* **Parameters:**
  **filter_expression** (*Optional* *[* *Union* *[* *str* *,* [*FilterExpression*]() *]* *]* *,* *optional*) – The filter
  expression or query string to use on the query.
* **Raises:**
  **TypeError** – If filter_expression is not a valid FilterExpression or string.

#### `set_text_weights(weights)`

Set or update the text weights for the query.

* **Parameters:**
  * **text_weights** – Dictionary of word:weight mappings
  * **weights** (*Dict* *[* *str* *,* *float* *]*)

#### `slop(slop)`

Allow a maximum of N intervening non matched terms between
phrase terms (0 means exact phrase).

* **Parameters:**
  **slop** (*int*)
* **Return type:**
  *Query*

#### `sort_by(sort_spec=None, asc=True)`

Set the sort order for query results.

This method supports sorting by single or multiple fields. Note that Redis Search
natively supports only a single SORTBY field. When multiple fields are specified,
only the FIRST field is used for the Redis SORTBY clause.

* **Parameters:**
  * **sort_spec** (*str* *|* *Tuple* *[* *str* *,* *str* *]*  *|* *List* *[* *str* *|* *Tuple* *[* *str* *,* *str* *]* *]*  *|* *None*) – Sort specification in various formats:
    - str: single field name
    - Tuple[str, str]: (field_name, "ASC"|"DESC")
    - List: list of field names or tuples
  * **asc** (*bool*) – Default sort direction when not specified (only used when sort_spec is a string).
    Defaults to True (ascending).
* **Returns:**
  Returns the query object for method chaining.
* **Return type:**
  self
* **Raises:**
  * **TypeError** – If sort_spec is not a valid type.
  * **ValueError** – If direction is not "ASC" or "DESC".

`Examples`

[code example]

#### `NOTE`
When multiple fields are specified, only the first field is used for sorting
in Redis. Future versions may support multi-field sorting through post-query
sorting in Python.

#### `timeout(timeout)`

overrides the timeout parameter of the module

* **Parameters:**
  **timeout** (*float*)
* **Return type:**
  *Query*

#### `verbatim()`

Set the query to be verbatim, i.e. use no query expansion
or stemming.

* **Return type:**
  *Query*

#### `with_payloads()`

Ask the engine to return document payloads.

* **Return type:**
  *Query*

#### `with_scores()`

Ask the engine to return document search scores.

* **Return type:**
  *Query*

#### `property field_weights: Dict[str, float]`

Get the field weights for the query.

* **Returns:**
  Dictionary mapping field names to their weights

#### `property filter: str | `[`FilterExpression`]()` `

The filter expression for the query.

#### `property params: Dict[str, Any]`

Return the query parameters.

#### `property query: BaseQuery`

Return self as the query object.

#### `property text_field_name: str | Dict[str, float]`

Get the text field name(s) - for backward compatibility.

* **Returns:**
  Either a single field name string (if only one field with weight 1.0)
  or a dictionary of field:weight mappings.

#### `property text_weights: Dict[str, float]`

Get the text weights.

* **Returns:**
  weight mappings.
* **Return type:**
  Dictionary of word

#### `NOTE`
The `stopwords` parameter in [TextQuery](#textquery) controls query-time stopword filtering (client-side).
For index-level stopwords configuration (server-side), see `redisvl.schema.IndexInfo.stopwords`.
Using query-time stopwords with index-level `STOPWORDS 0` is counterproductive.

FilterQuery

`class FilterQuery(filter_expression=None, return_fields=None, num_results=10, dialect=2, sort_by=None, in_order=False, params=None)`

Bases: `BaseQuery`

A query for running a filtered search with a filter expression.

* **Parameters:**
  * **filter_expression** (*Optional* *[* *Union* *[* *str* *,* [*FilterExpression*]() *]* *]*) – The optional filter
    expression to query with. Defaults to ‘\*’.
  * **return_fields** (*Optional* *[* *List* *[* *str* *]* *]* *,* *optional*) – The fields to return.
  * **num_results** (*Optional* *[* *int* *]* *,* *optional*) – The number of results to return. Defaults to 10.
  * **dialect** (*int* *,* *optional*) – The query dialect. Defaults to 2.
  * **sort_by** (*Optional* *[* *SortSpec* *]* *,* *optional*) – The field(s) to order the results by. Can be:
    - str: single field name (e.g., "price")
    - Tuple[str, str]: (field_name, "ASC"|"DESC") (e.g., ("price", "DESC"))
    - List: list of fields or tuples (e.g., ["price", ("rating", "DESC")])
    Note: Redis Search only supports single-field sorting, so only the first field is used.
    Defaults to None.
  * **in_order** (*bool* *,* *optional*) – Requires the terms in the field to have the same order as the
    terms in the query filter. Defaults to False.
  * **params** (*Optional* *[* *Dict* *[* *str* *,* *Any* *]* *]* *,* *optional*) – The parameters for the query. Defaults to None.
* **Raises:**
  **TypeError** – If filter_expression is not of type redisvl.query.FilterExpression

#### `dialect(dialect)`

Add a dialect field to the query.

- **dialect** - dialect version to execute the query under

* **Parameters:**
  **dialect** (*int*)
* **Return type:**
  *Query*

#### `expander(expander)`

Add a expander field to the query.

- **expander** - the name of the expander

* **Parameters:**
  **expander** (*str*)
* **Return type:**
  *Query*

#### `in_order()`

Match only documents where the query terms appear in
the same order in the document.
i.e. for the query "hello world", we do not match "world hello"

* **Return type:**
  *Query*

#### `language(language)`

Analyze the query as being in the specified language.

* **Parameters:**
  **language** (*str*) – The language (e.g. chinese or english)
* **Return type:**
  *Query*

#### `limit_fields(*fields)`

Limit the search to specific TEXT fields only.

- **fields**: A list of strings, case sensitive field names

from the defined schema.

* **Parameters:**
  **fields** (*List* *[* *str* *]*)
* **Return type:**
  *Query*

#### `limit_ids(*ids)`

Limit the results to a specific set of pre-known document
ids of any length.

* **Return type:**
  *Query*

#### `no_content()`

Set the query to only return ids and not the document content.

* **Return type:**
  *Query*

#### `no_stopwords()`

Prevent the query from being filtered for stopwords.
Only useful in very big queries that you are certain contain
no stopwords.

* **Return type:**
  *Query*

#### `paging(offset, num)`

Set the paging for the query (defaults to 0..10).

- **offset**: Paging offset for the results. Defaults to 0
- **num**: How many results do we want

* **Parameters:**
  * **offset** (*int*)
  * **num** (*int*)
* **Return type:**
  *Query*

#### `query_string()`

Return the query string of this query only.

* **Return type:**
  str

#### `return_fields(*fields, skip_decode=None)`

Set the fields to return with search results.

* **Parameters:**
  * **\*fields** – Variable number of field names to return.
  * **skip_decode** (*str* *|* *List* *[* *str* *]*  *|* *None*) – Optional field name or list of field names that should not be
    decoded. Useful for binary data like embeddings.
* **Returns:**
  Returns the query object for method chaining.
* **Return type:**
  self
* **Raises:**
  **TypeError** – If skip_decode is not a string, list, or None.

#### `scorer(scorer)`

Use a different scoring function to evaluate document relevance.
Default is TFIDF.

Since Redis 8.0 default was changed to BM25STD.

* **Parameters:**
  **scorer** (*str*) – The scoring function to use
  (e.g. TFIDF.DOCNORM or BM25)
* **Return type:**
  *Query*

#### `set_filter(filter_expression=None)`

Set the filter expression for the query.

* **Parameters:**
  **filter_expression** (*Optional* *[* *Union* *[* *str* *,* [*FilterExpression*]() *]* *]* *,* *optional*) – The filter
  expression or query string to use on the query.
* **Raises:**
  **TypeError** – If filter_expression is not a valid FilterExpression or string.

#### `slop(slop)`

Allow a maximum of N intervening non matched terms between
phrase terms (0 means exact phrase).

* **Parameters:**
  **slop** (*int*)
* **Return type:**
  *Query*

#### `sort_by(sort_spec=None, asc=True)`

Set the sort order for query results.

This method supports sorting by single or multiple fields. Note that Redis Search
natively supports only a single SORTBY field. When multiple fields are specified,
only the FIRST field is used for the Redis SORTBY clause.

* **Parameters:**
  * **sort_spec** (*str* *|* *Tuple* *[* *str* *,* *str* *]*  *|* *List* *[* *str* *|* *Tuple* *[* *str* *,* *str* *]* *]*  *|* *None*) – Sort specification in various formats:
    - str: single field name
    - Tuple[str, str]: (field_name, "ASC"|"DESC")
    - List: list of field names or tuples
  * **asc** (*bool*) – Default sort direction when not specified (only used when sort_spec is a string).
    Defaults to True (ascending).
* **Returns:**
  Returns the query object for method chaining.
* **Return type:**
  self
* **Raises:**
  * **TypeError** – If sort_spec is not a valid type.
  * **ValueError** – If direction is not "ASC" or "DESC".

`Examples`

[code example]

#### `NOTE`
When multiple fields are specified, only the first field is used for sorting
in Redis. Future versions may support multi-field sorting through post-query
sorting in Python.

#### `timeout(timeout)`

overrides the timeout parameter of the module

* **Parameters:**
  **timeout** (*float*)
* **Return type:**
  *Query*

#### `verbatim()`

Set the query to be verbatim, i.e. use no query expansion
or stemming.

* **Return type:**
  *Query*

#### `with_payloads()`

Ask the engine to return document payloads.

* **Return type:**
  *Query*

#### `with_scores()`

Ask the engine to return document search scores.

* **Return type:**
  *Query*

#### `property filter: str | `[`FilterExpression`]()` `

The filter expression for the query.

#### `property params: Dict[str, Any]`

Return the query parameters.

#### `property query: BaseQuery`

Return self as the query object.

CountQuery

`class CountQuery(filter_expression=None, dialect=2, params=None)`

Bases: `BaseQuery`

A query for a simple count operation provided some filter expression.

* **Parameters:**
  * **filter_expression** (*Optional* *[* *Union* *[* *str* *,* [*FilterExpression*]() *]* *]*) – The filter expression to
    query with. Defaults to None.
  * **params** (*Optional* *[* *Dict* *[* *str* *,* *Any* *]* *]* *,* *optional*) – The parameters for the query. Defaults to None.
  * **dialect** (*int*)
* **Raises:**
  **TypeError** – If filter_expression is not of type redisvl.query.FilterExpression

[code example]

#### `dialect(dialect)`

Add a dialect field to the query.

- **dialect** - dialect version to execute the query under

* **Parameters:**
  **dialect** (*int*)
* **Return type:**
  *Query*

#### `expander(expander)`

Add a expander field to the query.

- **expander** - the name of the expander

* **Parameters:**
  **expander** (*str*)
* **Return type:**
  *Query*

#### `in_order()`

Match only documents where the query terms appear in
the same order in the document.
i.e. for the query "hello world", we do not match "world hello"

* **Return type:**
  *Query*

#### `language(language)`

Analyze the query as being in the specified language.

* **Parameters:**
  **language** (*str*) – The language (e.g. chinese or english)
* **Return type:**
  *Query*

#### `limit_fields(*fields)`

Limit the search to specific TEXT fields only.

- **fields**: A list of strings, case sensitive field names

from the defined schema.

* **Parameters:**
  **fields** (*List* *[* *str* *]*)
* **Return type:**
  *Query*

#### `limit_ids(*ids)`

Limit the results to a specific set of pre-known document
ids of any length.

* **Return type:**
  *Query*

#### `no_content()`

Set the query to only return ids and not the document content.

* **Return type:**
  *Query*

#### `no_stopwords()`

Prevent the query from being filtered for stopwords.
Only useful in very big queries that you are certain contain
no stopwords.

* **Return type:**
  *Query*

#### `paging(offset, num)`

Set the paging for the query (defaults to 0..10).

- **offset**: Paging offset for the results. Defaults to 0
- **num**: How many results do we want

* **Parameters:**
  * **offset** (*int*)
  * **num** (*int*)
* **Return type:**
  *Query*

#### `query_string()`

Return the query string of this query only.

* **Return type:**
  str

#### `return_fields(*fields, skip_decode=None)`

Set the fields to return with search results.

* **Parameters:**
  * **\*fields** – Variable number of field names to return.
  * **skip_decode** (*str* *|* *List* *[* *str* *]*  *|* *None*) – Optional field name or list of field names that should not be
    decoded. Useful for binary data like embeddings.
* **Returns:**
  Returns the query object for method chaining.
* **Return type:**
  self
* **Raises:**
  **TypeError** – If skip_decode is not a string, list, or None.

#### `scorer(scorer)`

Use a different scoring function to evaluate document relevance.
Default is TFIDF.

Since Redis 8.0 default was changed to BM25STD.

* **Parameters:**
  **scorer** (*str*) – The scoring function to use
  (e.g. TFIDF.DOCNORM or BM25)
* **Return type:**
  *Query*

#### `set_filter(filter_expression=None)`

Set the filter expression for the query.

* **Parameters:**
  **filter_expression** (*Optional* *[* *Union* *[* *str* *,* [*FilterExpression*]() *]* *]* *,* *optional*) – The filter
  expression or query string to use on the query.
* **Raises:**
  **TypeError** – If filter_expression is not a valid FilterExpression or string.

#### `slop(slop)`

Allow a maximum of N intervening non matched terms between
phrase terms (0 means exact phrase).

* **Parameters:**
  **slop** (*int*)
* **Return type:**
  *Query*

#### `sort_by(sort_spec=None, asc=True)`

Set the sort order for query results.

This method supports sorting by single or multiple fields. Note that Redis Search
natively supports only a single SORTBY field. When multiple fields are specified,
only the FIRST field is used for the Redis SORTBY clause.

* **Parameters:**
  * **sort_spec** (*str* *|* *Tuple* *[* *str* *,* *str* *]*  *|* *List* *[* *str* *|* *Tuple* *[* *str* *,* *str* *]* *]*  *|* *None*) – Sort specification in various formats:
    - str: single field name
    - Tuple[str, str]: (field_name, "ASC"|"DESC")
    - List: list of field names or tuples
  * **asc** (*bool*) – Default sort direction when not specified (only used when sort_spec is a string).
    Defaults to True (ascending).
* **Returns:**
  Returns the query object for method chaining.
* **Return type:**
  self
* **Raises:**
  * **TypeError** – If sort_spec is not a valid type.
  * **ValueError** – If direction is not "ASC" or "DESC".

`Examples`

MultiVectorQuery

`class MultiVectorQuery(vectors, return_fields=None, filter_expression=None, num_results=10, dialect=2)`

Bases: `AggregationQuery`

MultiVectorQuery allows for search over multiple vector fields in a document simultaneously.
The final score will be a weighted combination of the individual vector similarity scores
following the formula:

score = (w_1 \* score_1 + w_2 \* score_2 + w_3 \* score_3 + … )

Vectors may be of different size and datatype, but must be indexed using the ‘cosine’ distance_metric.

[code example]

Instantiates a MultiVectorQuery object.

* **Parameters:**
  * **vectors** (*Union* *[*[*Vector*]() *,* *List* *[*[*Vector*]() *]* *]*) – The Vectors to perform vector similarity search.
  * **return_fields** (*Optional* *[* *List* *[* *str* *]* *]* *,* *optional*) – The fields to return. Defaults to None.
  * **filter_expression** (*Optional* *[* *Union* *[* *str* *,* [*FilterExpression*]() *]* *]*) – The filter expression to use.
    Defaults to None.
  * **num_results** (*int* *,* *optional*) – The number of results to return. Defaults to 10.
  * **dialect** (*int* *,* *optional*) – The Redis dialect version. Defaults to 2.

#### `add_scores()`

If set, includes the score as an ordinary field of the row.

* **Return type:**
  *AggregateRequest*

#### `apply(**kwexpr)`

Specify one or more projection expressions to add to each result

`Parameters`

`Parameters`

`Parameters`

`Parameters`

`Parameters`

- **fields**: If fields not specified, all the fields will be loaded.

Otherwise, fields should be given in the format of @field.

* **Parameters:**
  **fields** (*str*)
* **Return type:**
  *AggregateRequest*

#### `scorer(scorer)`

Use a different scoring function to evaluate document relevance.
Default is TFIDF.

* **Parameters:**
  **scorer** (*str*) – The scoring function to use
  (e.g. TFIDF.DOCNORM or BM25)
* **Return type:**
  *AggregateRequest*

#### `sort_by(*fields, **kwargs)`

Indicate how the results should be sorted. This can also be used for
*top-N* style queries

`Parameters`

>> query.sort_by("price")  # Single field, ascending
>> query.sort_by(("price", "DESC"))  # Single field, descending
>> query.sort_by(["price", "rating"])  # Multiple fields (only first used)
>> query.sort_by([("price", "DESC"), ("rating", "ASC")])

from redisvl.query import VectorQuery

query = VectorQuery(
    vector=[0.1, 0.2, 0.3],
    vector_field_name="embedding",
    num_results=10,
    ef_runtime=150  # Higher for better recall
)

query = VectorQuery(
    vector=[0.1, 0.2, 0.3],
    vector_field_name="embedding",
    num_results=10,
    search_window_size=20,
    use_search_history='ON',
    search_buffer_capacity=30
)

from redisvl.query import VectorRangeQuery

query = VectorRangeQuery(
    vector=[0.1, 0.2, 0.3],
    vector_field_name="embedding",
    distance_threshold=0.3,
    epsilon=0.05,              # Approximation factor
    search_window_size=20,     # SVS-VAMANA only
    use_search_history='AUTO'  # SVS-VAMANA only
)

from redisvl.query import VectorQuery

query = VectorQuery(
    vector=[0.1, 0.2, 0.3],
    vector_field_name="embedding",
    return_fields=["description"],
    num_results=10,
    ef_runtime=150  # Runtime parameters work with VectorQuery
)

from redisvl.query import TextQuery
from redisvl.index import SearchIndex

index = SearchIndex.from_yaml(index.yaml)

query = TextQuery(
    text="example text",
    text_field_name="text_field",
    text_scorer="BM25STD",
    filter_expression=None,
    num_results=10,
    return_fields=["field1", "field2"],
    stopwords="english",
    dialect=2,
)

results = index.query(query)

from redisvl.query import CountQuery
from redisvl.query.filter import Tag

t = Tag("brand") == "Nike"
query = CountQuery(filter_expression=t)

count = index.query(query)

from redisvl.query import MultiVectorQuery, Vector
from redisvl.index import SearchIndex

index = SearchIndex.from_yaml("path/to/index.yaml")

vector_1 = Vector(
    vector=[0.1, 0.2, 0.3],
    field_name="text_vector",
    dtype="float32",
    weight=0.7,
)
vector_2 = Vector(
    vector=[0.5, 0.5],
    field_name="image_vector",
    dtype="bfloat16",
    weight=0.2,
)
vector_3 = Vector(
    vector=[0.1, 0.2, 0.3],
    field_name="text_vector",
    dtype="float64",
    weight=0.5,
)

query = MultiVectorQuery(
    vectors=[vector_1, vector_2, vector_3],
    filter_expression=None,
    num_results=10,
    return_fields=["field1", "field2"],
    dialect=2,
)

results = index.query(query)


Rerankers

CohereReranker

`class CohereReranker(model='rerank-english-v3.0', rank_by=None, limit=5, return_score=True, api_config=None)`

Bases: `BaseReranker`

The CohereReranker class uses Cohere’s API to rerank documents based on an
input query.

This reranker is designed to interact with Cohere’s /rerank API,
requiring an API key for authentication. The key can be provided
directly in the api_config dictionary or through the COHERE_API_KEY
environment variable. User must obtain an API key from Cohere’s website
([https://dashboard.cohere.com/](https://dashboard.cohere.com/)). Additionally, the cohere python
client must be installed with pip install cohere.

[code example]

Initialize the CohereReranker with specified model, ranking criteria,
and API configuration.

* **Parameters:**
  * **model** (*str*) – The identifier for the Cohere model used for reranking.
    Defaults to ‘rerank-english-v3.0’.
  * **rank_by** (*Optional* *[* *List* *[* *str* *]* *]*) – Optional list of keys specifying the
    attributes in the documents that should be considered for
    ranking. None means ranking will rely on the model’s default
    behavior.
  * **limit** (*int*) – The maximum number of results to return after
    reranking. Must be a positive integer.
  * **return_score** (*bool*) – Whether to return scores alongside the
    reranked results.
  * **api_config** (*Optional* *[* *Dict* *]* *,* *optional*) – Dictionary containing the API key.
    Defaults to None.
* **Raises:**
  * **ImportError** – If the cohere library is not installed.
  * **ValueError** – If the API key is not provided.

#### `async arank(query, docs, **kwargs)`

Rerank documents based on the provided query using the Cohere rerank API.

This method processes the user’s query and the provided documents to
rerank them in a manner that is potentially more relevant to the
query’s context.

* **Parameters:**
  * **query** (*str*) – The user’s search query.
  * **docs** (*Union* *[* *List* *[* *Dict* *[* *str* *,* *Any* *]* *]* *,* *List* *[* *str* *]* *]*) – The list of documents
    to be ranked, either as dictionaries or strings.
* **Returns:**
  The reranked list of documents and optionally associated scores.
* **Return type:**
  Union[Tuple[Union[List[Dict[str, Any]], List[str]], float], List[Dict[str, Any]]]

#### `model_post_init(context, /)`

This function is meant to behave like a BaseModel method to initialise private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

* **Parameters:**
  * **self** (*BaseModel*) – The BaseModel instance.
  * **context** (*Any*) – The context.
* **Return type:**
  None

#### `rank(query, docs, **kwargs)`

Rerank documents based on the provided query using the Cohere rerank API.

This method processes the user’s query and the provided documents to
rerank them in a manner that is potentially more relevant to the
query’s context.

* **Parameters:**
  * **query** (*str*) – The user’s search query.
  * **docs** (*Union* *[* *List* *[* *Dict* *[* *str* *,* *Any* *]* *]* *,* *List* *[* *str* *]* *]*) – The list of documents
    to be ranked, either as dictionaries or strings.
* **Returns:**
  The reranked list of documents and optionally associated scores.
* **Return type:**
  Union[Tuple[Union[List[Dict[str, Any]], List[str]], float], List[Dict[str, Any]]]

#### `model_config: ClassVar[ConfigDict] = {}`

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

HFCrossEncoderReranker

`class HFCrossEncoderReranker(model='cross-encoder/ms-marco-MiniLM-L-6-v2', limit=3, return_score=True, *, rank_by=None)`

Bases: `BaseReranker`

The HFCrossEncoderReranker class uses a cross-encoder models from Hugging Face
to rerank documents based on an input query.

This reranker loads a cross-encoder model using the CrossEncoder class
from the sentence_transformers library. It requires the
sentence_transformers library to be installed.

[code example]

Initialize the HFCrossEncoderReranker with a specified model and ranking criteria.

* **Parameters:**
  * **model** (*str*) – The name or path of the cross-encoder model to use for reranking.
    Defaults to ‘cross-encoder/ms-marco-MiniLM-L-6-v2’.
  * **limit** (*int*) – The maximum number of results to return after reranking. Must be a positive integer.
  * **return_score** (*bool*) – Whether to return scores alongside the reranked results.
  * **rank_by** (*List* *[* *str* *]*  *|* *None*)

#### `async arank(query, docs, **kwargs)`

Asynchronously rerank documents based on the provided query using the loaded cross-encoder model.

This method processes the user’s query and the provided documents to rerank them
in a manner that is potentially more relevant to the query’s context.

* **Parameters:**
  * **query** (*str*) – The user’s search query.
  * **docs** (*Union* *[* *List* *[* *Dict* *[* *str* *,* *Any* *]* *]* *,* *List* *[* *str* *]* *]*) – The list of documents to be ranked,
    either as dictionaries or strings.
* **Returns:**
  The reranked list of documents and optionally associated scores.
* **Return type:**
  Union[Tuple[List[Dict[str, Any]], List[float]], List[Dict[str, Any]]]

#### `model_post_init(context, /)`

This function is meant to behave like a BaseModel method to initialise private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

* **Parameters:**
  * **self** (*BaseModel*) – The BaseModel instance.
  * **context** (*Any*) – The context.
* **Return type:**
  None

#### `rank(query, docs, **kwargs)`

Rerank documents based on the provided query using the loaded cross-encoder model.

This method processes the user’s query and the provided documents to rerank them
in a manner that is potentially more relevant to the query’s context.

* **Parameters:**
  * **query** (*str*) – The user’s search query.
  * **docs** (*Union* *[* *List* *[* *Dict* *[* *str* *,* *Any* *]* *]* *,* *List* *[* *str* *]* *]*) – The list of documents to be ranked,
    either as dictionaries or strings.
* **Returns:**
  The reranked list of documents and optionally associated scores.
* **Return type:**
  Union[Tuple[List[Dict[str, Any]], List[float]], List[Dict[str, Any]]]

#### `model_config: ClassVar[ConfigDict] = {}`

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

VoyageAIReranker

`class VoyageAIReranker(model, rank_by=None, limit=5, return_score=True, api_config=None)`

Bases: `BaseReranker`

The VoyageAIReranker class uses VoyageAI’s API to rerank documents based on an
input query.

This reranker is designed to interact with VoyageAI’s /rerank API,
requiring an API key for authentication. The key can be provided
directly in the api_config dictionary or through the VOYAGE_API_KEY
environment variable. User must obtain an API key from VoyageAI’s website
([https://dash.voyageai.com/](https://dash.voyageai.com/)). Additionally, the voyageai python
client must be installed with pip install voyageai.

[code example]

Initialize the VoyageAIReranker with specified model, ranking criteria,
and API configuration.

* **Parameters:**
  * **model** (*str*) – The identifier for the VoyageAI model used for reranking.
  * **rank_by** (*Optional* *[* *List* *[* *str* *]* *]*) – Optional list of keys specifying the
    attributes in the documents that should be considered for
    ranking. None means ranking will rely on the model’s default
    behavior.
  * **limit** (*int*) – The maximum number of results to return after
    reranking. Must be a positive integer.
  * **return_score** (*bool*) – Whether to return scores alongside the
    reranked results.
  * **api_config** (*Optional* *[* *Dict* *]* *,* *optional*) – Dictionary containing the API key.
    Defaults to None.
* **Raises:**
  * **ImportError** – If the voyageai library is not installed.
  * **ValueError** – If the API key is not provided.

#### `async arank(query, docs, **kwargs)`

Rerank documents based on the provided query using the VoyageAI rerank API.

This method processes the user’s query and the provided documents to
rerank them in a manner that is potentially more relevant to the
query’s context.

* **Parameters:**
  * **query** (*str*) – The user’s search query.
  * **docs** (*Union* *[* *List* *[* *Dict* *[* *str* *,* *Any* *]* *]* *,* *List* *[* *str* *]* *]*) – The list of documents
    to be ranked, either as dictionaries or strings.
* **Returns:**
  The reranked list of documents and optionally associated scores.
* **Return type:**
  Union[Tuple[Union[List[Dict[str, Any]], List[str]], float], List[Dict[str, Any]]]

#### `model_post_init(context, /)`

This function is meant to behave like a BaseModel method to initialise private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

* **Parameters:**
  * **self** (*BaseModel*) – The BaseModel instance.
  * **context** (*Any*) – The context.
* **Return type:**
  None

#### `rank(query, docs, **kwargs)`

Rerank documents based on the provided query using the VoyageAI rerank API.

This method processes the user’s query and the provided documents to
rerank them in a manner that is potentially more relevant to the
query’s context.

* **Parameters:**
  * **query** (*str*) – The user’s search query.
  * **docs** (*Union* *[* *List* *[* *Dict* *[* *str* *,* *Any* *]* *]* *,* *List* *[* *str* *]* *]*) – The list of documents
    to be ranked, either as dictionaries or strings.
* **Returns:**
  The reranked list of documents and optionally associated scores.
* **Return type:**
  Union[Tuple[Union[List[Dict[str, Any]], List[str]], float], List[Dict[str, Any]]]

#### `model_config: ClassVar[ConfigDict] = {}`

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

from redisvl.utils.rerank import CohereReranker

# set up the Cohere reranker with some configuration
reranker = CohereReranker(rank_by=["content"], limit=2)
# rerank raw search results based on user input/query
results = reranker.rank(
    query="your input query text here",
    docs=[
        {"content": "document 1"},
        {"content": "document 2"},
        {"content": "document 3"}
    ]
)

from redisvl.utils.rerank import HFCrossEncoderReranker

# set up the HFCrossEncoderReranker with a specific model
reranker = HFCrossEncoderReranker(model_name="cross-encoder/ms-marco-MiniLM-L-6-v2", limit=3)
# rerank raw search results based on user input/query
results = reranker.rank(
    query="your input query text here",
    docs=[
        {"content": "document 1"},
        {"content": "document 2"},
        {"content": "document 3"}
    ]
)

from redisvl.utils.rerank import VoyageAIReranker

# set up the VoyageAI reranker with some configuration
reranker = VoyageAIReranker(rank_by=["content"], limit=2)
# rerank raw search results based on user input/query
results = reranker.rank(
    query="your input query text here",
    docs=[
        {"content": "document 1"},
        {"content": "document 2"},
        {"content": "document 3"}
    ]
)