content/develop/ai/redisvl/api/query.md
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 with extended functionality for ease-of-use.
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.
NOTELearn more about vector queries in Redis: https://redis.io/docs/latest/develop/ai/search-and-query/vectors/#knn-vector-search
dialect(dialect)Add a dialect field to the query.
expander(expander)Add a expander field to the 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"
language(language)Analyze the query as being in the specified language.
limit_fields(*fields)Limit the search to specific TEXT fields only.
from the defined schema.
limit_ids(*ids)Limit the results to a specific set of pre-known document ids of any length.
no_content()Set the query to only return ids and not the document content.
no_stopwords()Prevent the query from being filtered for stopwords. Only useful in very big queries that you are certain contain no stopwords.
paging(offset, num)Set the paging for the query (defaults to 0..10).
query_string()Return the query string of this query only.
return_fields(*fields, skip_decode=None)Set the fields to return with search results.
scorer(scorer)Use a different scoring function to evaluate document relevance. Default is TFIDF.
Since Redis 8.0 default was changed to BM25STD.
set_batch_size(batch_size)Set the batch size for the query.
set_ef_runtime(ef_runtime)Set the EF_RUNTIME parameter for the query.
set_epsilon(epsilon)Set the epsilon parameter for the query.
set_filter(filter_expression=None)Set the filter expression for the query.
set_hybrid_policy(hybrid_policy)Set the hybrid policy for the query.
set_search_buffer_capacity(search_buffer_capacity)Set the SEARCH_BUFFER_CAPACITY parameter for the query.
set_search_window_size(search_window_size)Set the SEARCH_WINDOW_SIZE parameter for the query.
set_use_search_history(use_search_history)Set the USE_SEARCH_HISTORY parameter for the query.
slop(slop)Allow a maximum of N intervening non matched terms between phrase terms (0 means exact phrase).
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.
Examples>> 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")])
NOTEWhen 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
verbatim()Set the query to be verbatim, i.e. use no query expansion or stemming.
with_payloads()Ask the engine to return document payloads.
with_scores()Ask the engine to return document search scores.
property batch_size: int | NoneReturn the batch size for the query.
property ef_runtime: int | NoneReturn the EF_RUNTIME parameter for the query.
property epsilon: float | NoneReturn the epsilon parameter for the query.
property filter: str | [FilterExpression]({{< relref "filter/#filterexpression" >}}) The filter expression for the query.
property hybrid_policy: str | NoneReturn the hybrid policy for the query.
property params: Dict[str, Any]Return the parameters for the query.
property query: BaseQueryReturn self as the query object.
property search_buffer_capacity: int | NoneReturn the SEARCH_BUFFER_CAPACITY parameter for the query.
property search_window_size: int | NoneReturn the SEARCH_WINDOW_SIZE parameter for the query.
property use_search_history: str | NoneReturn the USE_SEARCH_HISTORY parameter for the query.
NOTERuntime 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 searchesuse_search_history: Whether to use search buffer (OFF/ON/AUTO)search_buffer_capacity: Tuning parameter for 2-level compressionExample with HNSW runtime parameters:
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
)
Example with SVS-VAMANA runtime parameters:
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
)
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.
NOTELearn more about vector range queries: https://redis.io/docs/interact/search-and-query/search/vectors/#range-query
dialect(dialect)Add a dialect field to the query.
expander(expander)Add a expander field to the 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"
language(language)Analyze the query as being in the specified language.
limit_fields(*fields)Limit the search to specific TEXT fields only.
from the defined schema.
limit_ids(*ids)Limit the results to a specific set of pre-known document ids of any length.
no_content()Set the query to only return ids and not the document content.
no_stopwords()Prevent the query from being filtered for stopwords. Only useful in very big queries that you are certain contain no stopwords.
paging(offset, num)Set the paging for the query (defaults to 0..10).
query_string()Return the query string of this query only.
return_fields(*fields, skip_decode=None)Set the fields to return with search results.
scorer(scorer)Use a different scoring function to evaluate document relevance. Default is TFIDF.
Since Redis 8.0 default was changed to BM25STD.
set_batch_size(batch_size)Set the batch size for the query.
set_distance_threshold(distance_threshold)Set the distance threshold for the query.
set_epsilon(epsilon)Set the epsilon parameter for the range query.
set_filter(filter_expression=None)Set the filter expression for the query.
set_hybrid_policy(hybrid_policy)Set the hybrid policy for the query.
set_search_buffer_capacity(search_buffer_capacity)Set the SEARCH_BUFFER_CAPACITY parameter for the range query.
set_search_window_size(search_window_size)Set the SEARCH_WINDOW_SIZE parameter for the range query.
set_use_search_history(use_search_history)Set the USE_SEARCH_HISTORY parameter for the range query.
slop(slop)Allow a maximum of N intervening non matched terms between phrase terms (0 means exact phrase).
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.
Examples>> 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")])
NOTEWhen 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
verbatim()Set the query to be verbatim, i.e. use no query expansion or stemming.
with_payloads()Ask the engine to return document payloads.
with_scores()Ask the engine to return document search scores.
property batch_size: int | NoneReturn the batch size for the query.
property distance_threshold: floatReturn the distance threshold for the query.
property epsilon: float | NoneReturn the epsilon for the query.
property filter: str | [FilterExpression]({{< relref "filter/#filterexpression" >}}) The filter expression for the query.
property hybrid_policy: str | NoneReturn the hybrid policy for the query.
property params: Dict[str, Any]Return the parameters for the query.
property query: BaseQueryReturn self as the query object.
property search_buffer_capacity: int | NoneReturn the SEARCH_BUFFER_CAPACITY parameter for the query.
property search_window_size: int | NoneReturn the SEARCH_WINDOW_SIZE parameter for the query.
property use_search_history: str | NoneReturn the USE_SEARCH_HISTORY parameter for the query.
NOTERuntime 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 windowuse_search_history: Whether to use search buffer (OFF/ON/AUTO)search_buffer_capacity: Tuning parameter for 2-level compressionExample:
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
)
class HybridQuery(*args, **kwargs)Bases: AggregateHybridQuery
Backward compatibility wrapper for AggregateHybridQuery.
DeprecatedDeprecated 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.
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]({{< relref "filter/#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.
NOTEAggregateHybridQuery 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.
add_scores()If set, includes the score as an ordinary field of the row.
apply(**kwexpr)Specify one or more projection expressions to add to each result
Parametersdialect(dialect)Add a dialect field to the aggregate command.
filter(expressions)Specify filter for post-query results using predicates relating to values in the result set.
Parametersgroup_by(fields, *reducers)Specify by which fields to group the aggregation.
Parameterslimit(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.
ParametersExample 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.
load(*fields)Indicate the fields to be returned in the response. These fields are returned in addition to any others implicitly specified.
ParametersOtherwise, fields should be given in the format of @field.
scorer(scorer)Use a different scoring function to evaluate document relevance. Default is TFIDF.
set_text_weights(weights)Set or update the text weights for the query.
sort_by(*fields, **kwargs)Indicate how the results should be sorted. This can also be used for top-N style queries
ParametersExample 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)
with_schema()If set, the schema property will contain a list of [field, type] entries in the result object.
property params: Dict[str, Any]Return the parameters for the aggregation.
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.
NOTEThe stopwords parameter in 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.
NOTERuntime 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 or VectorRangeQuery instead of AggregateHybridQuery.
Example with VectorQuery (supports runtime parameters):
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
)
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.
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)
A query for running a full text search, along with an optional filter expression.
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/
filter_expression (Union [ str , [FilterExpression]({{< relref "filter/#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:
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.
dialect(dialect)Add a dialect field to the query.
expander(expander)Add a expander field to the 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"
language(language)Analyze the query as being in the specified language.
limit_fields(*fields)Limit the search to specific TEXT fields only.
from the defined schema.
limit_ids(*ids)Limit the results to a specific set of pre-known document ids of any length.
no_content()Set the query to only return ids and not the document content.
no_stopwords()Prevent the query from being filtered for stopwords. Only useful in very big queries that you are certain contain no stopwords.
paging(offset, num)Set the paging for the query (defaults to 0..10).
query_string()Return the query string of this query only.
return_fields(*fields, skip_decode=None)Set the fields to return with search results.
scorer(scorer)Use a different scoring function to evaluate document relevance. Default is TFIDF.
Since Redis 8.0 default was changed to BM25STD.
set_field_weights(field_weights)Set or update the field weights for the query.
set_filter(filter_expression=None)Set the filter expression for the query.
set_text_weights(weights)Set or update the text weights for the query.
slop(slop)Allow a maximum of N intervening non matched terms between phrase terms (0 means exact phrase).
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.
Examples>> 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")])
NOTEWhen 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
verbatim()Set the query to be verbatim, i.e. use no query expansion or stemming.
with_payloads()Ask the engine to return document payloads.
with_scores()Ask the engine to return document search scores.
property field_weights: Dict[str, float]Get the field weights for the query.
property filter: str | [FilterExpression]({{< relref "filter/#filterexpression" >}}) The filter expression for the query.
property params: Dict[str, Any]Return the query parameters.
property query: BaseQueryReturn self as the query object.
property text_field_name: str | Dict[str, float]Get the text field name(s) - for backward compatibility.
property text_weights: Dict[str, float]Get the text weights.
NOTEThe stopwords parameter in 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.
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.
dialect(dialect)Add a dialect field to the query.
expander(expander)Add a expander field to the 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"
language(language)Analyze the query as being in the specified language.
limit_fields(*fields)Limit the search to specific TEXT fields only.
from the defined schema.
limit_ids(*ids)Limit the results to a specific set of pre-known document ids of any length.
no_content()Set the query to only return ids and not the document content.
no_stopwords()Prevent the query from being filtered for stopwords. Only useful in very big queries that you are certain contain no stopwords.
paging(offset, num)Set the paging for the query (defaults to 0..10).
query_string()Return the query string of this query only.
return_fields(*fields, skip_decode=None)Set the fields to return with search results.
scorer(scorer)Use a different scoring function to evaluate document relevance. Default is TFIDF.
Since Redis 8.0 default was changed to BM25STD.
set_filter(filter_expression=None)Set the filter expression for the query.
slop(slop)Allow a maximum of N intervening non matched terms between phrase terms (0 means exact phrase).
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.
Examples>> 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")])
NOTEWhen 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
verbatim()Set the query to be verbatim, i.e. use no query expansion or stemming.
with_payloads()Ask the engine to return document payloads.
with_scores()Ask the engine to return document search scores.
property filter: str | [FilterExpression]({{< relref "filter/#filterexpression" >}}) The filter expression for the query.
property params: Dict[str, Any]Return the query parameters.
property query: BaseQueryReturn self as the query object.
class CountQuery(filter_expression=None, dialect=2, params=None)Bases: BaseQuery
A query for a simple count operation provided some filter expression.
from redisvl.query import CountQuery
from redisvl.query.filter import Tag
t = Tag("brand") == "Nike"
query = CountQuery(filter_expression=t)
count = index.query(query)
dialect(dialect)Add a dialect field to the query.
expander(expander)Add a expander field to the 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"
language(language)Analyze the query as being in the specified language.
limit_fields(*fields)Limit the search to specific TEXT fields only.
from the defined schema.
limit_ids(*ids)Limit the results to a specific set of pre-known document ids of any length.
no_content()Set the query to only return ids and not the document content.
no_stopwords()Prevent the query from being filtered for stopwords. Only useful in very big queries that you are certain contain no stopwords.
paging(offset, num)Set the paging for the query (defaults to 0..10).
query_string()Return the query string of this query only.
return_fields(*fields, skip_decode=None)Set the fields to return with search results.
scorer(scorer)Use a different scoring function to evaluate document relevance. Default is TFIDF.
Since Redis 8.0 default was changed to BM25STD.
set_filter(filter_expression=None)Set the filter expression for the query.
slop(slop)Allow a maximum of N intervening non matched terms between phrase terms (0 means exact phrase).
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.
Examples>> 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")])
NOTEWhen 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
verbatim()Set the query to be verbatim, i.e. use no query expansion or stemming.
with_payloads()Ask the engine to return document payloads.
with_scores()Ask the engine to return document search scores.
property filter: str | [FilterExpression]({{< relref "filter/#filterexpression" >}}) The filter expression for the query.
property params: Dict[str, Any]Return the query parameters.
property query: BaseQueryReturn self as the query object.
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.
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)
Instantiates a MultiVectorQuery object.
add_scores()If set, includes the score as an ordinary field of the row.
apply(**kwexpr)Specify one or more projection expressions to add to each result
Parametersdialect(dialect)Add a dialect field to the aggregate command.
filter(expressions)Specify filter for post-query results using predicates relating to values in the result set.
Parametersgroup_by(fields, *reducers)Specify by which fields to group the aggregation.
Parameterslimit(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.
ParametersExample 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.
load(*fields)Indicate the fields to be returned in the response. These fields are returned in addition to any others implicitly specified.
ParametersOtherwise, fields should be given in the format of @field.
scorer(scorer)Use a different scoring function to evaluate document relevance. Default is TFIDF.
sort_by(*fields, **kwargs)Indicate how the results should be sorted. This can also be used for top-N style queries
ParametersExample 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)
with_schema()If set, the schema property will contain a list of [field, type] entries in the result object.
property params: Dict[str, Any]Return the parameters for the aggregation.