{
  "schema_version": 2,
  "id": "develop/ai/redisvl/concepts/queries",
  "title": "Query Types",
  "url": "https://redis.io/docs/latest/develop/ai/redisvl/0.25.1/concepts/queries/",
  "summary": "",
  "content": "\n\nRedisVL provides several query types, each optimized for different search patterns. Understanding when to use each helps you build efficient search applications.\n\n## Vector Queries\n\nVector queries find documents by semantic similarity. You provide a vector (typically an embedding of text or images), and Redis returns documents whose vectors are closest to yours.\n\n### VectorQuery\n\nThe most common query type. Returns the top K most similar documents using KNN (K-Nearest Neighbors) search.\n\n```python\nfrom redisvl.query import VectorQuery\n\nquery = VectorQuery(\n    vector=embedding,           # Your query embedding\n    vector_field_name=\"embedding\",\n    num_results=10\n)\nresults = index.query(query)\n```\n\nUse when you want to find the N most similar items regardless of how similar they actually are. Good for \"find me things like this\" searches.\n\n### VectorRangeQuery\n\nReturns all documents within a specified distance threshold. Unlike VectorQuery, this doesn’t limit results to a fixed K—it returns everything within the radius.\n\n```python\nfrom redisvl.query import VectorRangeQuery\n\nquery = VectorRangeQuery(\n    vector=embedding,\n    vector_field_name=\"embedding\",\n    distance_threshold=0.3      # Return all within this distance\n)\nresults = index.query(query)\n```\n\nUse when similarity threshold matters more than result count. Good for \"find everything similar enough\" searches, like deduplication or clustering.\n\n## Filter Queries\n\nFilter queries find documents by exact field matching without vector similarity.\n\n### FilterQuery\n\nSearches using filter expressions on indexed fields. Supports tag matching, numeric ranges, text search, and geographic filters.\n\n```python\nfrom redisvl.query import FilterQuery\nfrom redisvl.query.filter import Tag, Num\n\nquery = FilterQuery(\n    filter_expression=(Tag(\"category\") == \"electronics\") \u0026 (Num(\"price\") \u003c 100),\n    return_fields=[\"title\", \"price\"],\n    num_results=20\n)\nresults = index.query(query)\n```\n\nUse when you need precise filtering without semantic similarity—finding all products in a category, all users in a region, or all records within a date range.\n\n### CountQuery\n\nReturns only the count of matching documents, not the documents themselves. More efficient than FilterQuery when you only need the count.\n\n```python\nfrom redisvl.query import CountQuery\nfrom redisvl.query.filter import Tag\n\nquery = CountQuery(filter_expression=Tag(\"status\") == \"active\")\ncount = index.query(query)\n```\n\nUse for analytics, pagination totals, or checking if matches exist before running a full query.\n\n## Text Queries\n\nText queries perform full-text search with relevance scoring.\n\n### TextQuery\n\nSearches text fields using Redis’s full-text search capabilities. Supports multiple scoring algorithms (BM25, TF-IDF), stopword handling, and field weighting.\n\n```python\nfrom redisvl.query import TextQuery\n\nquery = TextQuery(\n    text=\"machine learning\",\n    text_field_name=\"content\",\n    text_scorer=\"BM25STD\",\n    num_results=10\n)\nresults = index.query(query)\n```\n\nUse when you need keyword-based search with relevance ranking—traditional search engine behavior where exact word matches matter.\n\n## Hybrid Queries\n\nHybrid queries combine multiple search strategies for better results than either alone.\n\n### HybridQuery\n\nCombines text search and vector search in a single query using Redis’s native hybrid search. Supports multiple fusion methods:\n\n- **RRF (Reciprocal Rank Fusion)**: Combines rankings from both searches. Good when you trust both signals equally.\n- **Linear**: Weighted combination of scores. Good when you want to tune the balance between text and semantic relevance.\n\n```python\nfrom redisvl.query import HybridQuery\n\nquery = HybridQuery(\n    text=\"machine learning frameworks\",\n    text_field_name=\"content\",\n    vector=embedding,\n    vector_field_name=\"embedding\",\n    combination_method=\"RRF\",\n    num_results=10\n)\nresults = index.query(query)\n```\n\nUse when neither pure keyword search nor pure semantic search gives good enough results. Common in RAG applications where you want both exact matches and semantic understanding.\n\n\nHybridQuery requires Redis \u003e= 8.4.0 and redis-py \u003e= 7.1.0.\n\n\n### AggregateHybridQuery\n\nSimilar to HybridQuery but uses Redis aggregation pipelines. Provides more control over score combination and result processing.\n\nUse when you need custom score normalization or complex result transformations that HybridQuery doesn’t support.\n\n## Multi-Vector Queries\n\n### MultiVectorQuery\n\nSearches across multiple vector fields simultaneously with configurable weights per field.\n\n```python\nfrom redisvl.query import MultiVectorQuery, Vector\n\nquery = MultiVectorQuery(\n    vectors=[\n        Vector(vector=text_embedding, field_name=\"text_vector\", weight=0.7),\n        Vector(vector=image_embedding, field_name=\"image_vector\", weight=0.3),\n    ],\n    num_results=10\n)\nresults = index.query(query)\n```\n\nUse for multimodal search—finding documents that match across text embeddings, image embeddings, and other vector representations. Each vector field can have different importance weights.\n\n## SQL Queries\n\n### SQLQuery\n\nTranslates SQL SELECT statements into Redis queries. Provides a familiar interface for developers coming from relational databases.\n\n```python\nfrom redisvl.query import SQLQuery\n\nquery = SQLQuery(\"\"\"\n    SELECT title, price, category\n    FROM products\n    WHERE category = 'electronics' AND price \u003c 100\n\"\"\")\nresults = index.query(query)\n```\n\n`SQLQuery` also accepts `sql_redis_options`, which are forwarded to the\nunderlying `sql-redis` executor. This is mainly useful for tuning schema\ncaching behavior.\n\n```python\nquery = SQLQuery(\n    \"\"\"\n    SELECT title, price, category\n    FROM products\n    WHERE category = 'electronics' AND price \u003c 100\n    \"\"\",\n    sql_redis_options={\"schema_cache_strategy\": \"lazy\"},\n)\n```\n\n- `\"lazy\"` (default) loads schemas only when a query touches an index, which\n  keeps startup and one-off queries cheaper.\n- `\"load_all\"` preloads all schemas up front, which can help repeated query\n  workloads that span many indexes.\n\nFor TEXT fields with `sql-redis \u003e= 0.4.0`:\n\n- `=` performs exact phrase or exact-term matching\n- `LIKE` performs prefix/suffix/contains matching using SQL `%` wildcards\n- `fuzzy(field, 'term')` performs typo-tolerant matching\n- `fulltext(field, 'query')` performs tokenized search\n\n```python\nquery = SQLQuery(\"SELECT * FROM products WHERE title = 'gaming laptop'\")\nquery = SQLQuery(\"SELECT * FROM products WHERE title LIKE 'lap%'\")\nquery = SQLQuery(\"SELECT * FROM products WHERE fuzzy(title, 'laptap')\")\nquery = SQLQuery(\"SELECT * FROM products WHERE fulltext(title, 'laptop OR tablet')\")\n```\n\nUse `=` when you want an exact phrase, `LIKE` for prefix/suffix/contains\npatterns, `fuzzy()` for typo-tolerant lookup, and `fulltext()` for tokenized\nsearch operators such as `OR`, optional terms, or proximity.\n\n**Aggregations and grouping:**\n\n```python\nquery = SQLQuery(\"\"\"\n    SELECT category, COUNT(*) as count, AVG(price) as avg_price\n    FROM products\n    GROUP BY category\n    ORDER BY count DESC\n\"\"\")\n```\n\n**Geographic queries** with `geo_distance()`:\n\n```python\n# Find stores within 50km of San Francisco\nquery = SQLQuery(\"\"\"\n    SELECT name, category\n    FROM stores\n    WHERE geo_distance(location, POINT(-122.4194, 37.7749), 'km') \u003c 50\n\"\"\")\n\n# Calculate distances\nquery = SQLQuery(\"\"\"\n    SELECT name, geo_distance(location, POINT(-122.4194, 37.7749)) AS distance\n    FROM stores\n\"\"\")\n```\n\n**Date queries** with ISO date literals and date functions:\n\n```python\n# Filter by date range\nquery = SQLQuery(\"\"\"\n    SELECT name FROM events\n    WHERE created_at BETWEEN '2024-01-01' AND '2024-03-31'\n\"\"\")\n\n# Extract date parts\nquery = SQLQuery(\"\"\"\n    SELECT YEAR(created_at) AS year, COUNT(*) AS count\n    FROM events\n    GROUP BY year\n\"\"\")\n```\n\n**Vector similarity search** with parameters:\n\n```python\nquery = SQLQuery(\"\"\"\n    SELECT title, vector_distance(embedding, :vec) AS score\n    FROM products\n    LIMIT 5\n\"\"\", params={\"vec\": embedding_bytes})\n```\n\n**Hybrid search (FT.HYBRID)** fuses a text query and a vector query server-side\nwith `hybrid_vector_search()`, composing `cosine_distance()` (vector leg) and\n`fulltext()` (text leg) with `rrf()` or `linear()` fusion. This is the SQL\nfront-end to the native `HybridQuery` (above):\n\n```python\nquery = SQLQuery(\"\"\"\n    SELECT title,\n           hybrid_vector_search(\n               cosine_distance(embedding, :vec),\n               fulltext(description, 'gaming laptop'),\n               rrf()\n           ) AS hybrid_score\n    FROM products\n    ORDER BY hybrid_score DESC\n    LIMIT 5\n\"\"\", params={\"vec\": embedding_bytes})\n```\n\nRequires Redis 8.4+ and `redis-py \u003e= 7.1.0`.\n\nUse when your team is more comfortable with SQL syntax, or when integrating with tools that generate SQL.\n\n\nSQLQuery requires the optional `sql-redis` package. Install with: `pip install redisvl[sql-redis]`\n\n\nFor comprehensive examples including geographic filtering, date functions, and vector search, see the [SQL to Redis Queries guide](https://redis.io/docs/latest/../user_guide/how_to_guides/sql_to_redis_queries).\n\n## Choosing the Right Query\n\n| Use Case                                   | Query Type       |\n|--------------------------------------------|------------------|\n| Semantic similarity search                 | VectorQuery      |\n| Find all items within similarity threshold | VectorRangeQuery |\n| Exact field matching                       | FilterQuery      |\n| Count matching records                     | CountQuery       |\n| Keyword search with relevance              | TextQuery        |\n| Combined keyword + semantic                | HybridQuery      |\n| Multimodal search                          | MultiVectorQuery |\n| SQL-familiar interface                     | SQLQuery         |\n\n## Common Patterns\n\n### Vector Search with Filters\n\nAll vector queries support filter expressions. Combine semantic search with metadata filtering:\n\n```python\nfrom redisvl.query import VectorQuery\nfrom redisvl.query.filter import Tag, Num\n\nquery = VectorQuery(\n    vector=embedding,\n    vector_field_name=\"embedding\",\n    filter_expression=(Tag(\"category\") == \"electronics\") \u0026 (Num(\"price\") \u003c 100),\n    num_results=10\n)\n```\n\n### Hybrid Search for RAG\n\nFor retrieval-augmented generation, hybrid search often outperforms pure vector search:\n\n```python\nfrom redisvl.query import HybridQuery\n\nquery = HybridQuery(\n    text=\"machine learning frameworks\",\n    text_field_name=\"content\",\n    vector=embedding,\n    vector_field_name=\"embedding\",\n    combination_method=\"RRF\",\n    num_results=5\n)\n```\n\n## Results and expiring documents\n\nRedisVL returns query results as a list of dictionaries, one per matched document. On Redis 8.8+ a document can occasionally come back with its field payload missing: the RediSearch worker pool now defaults to a nonzero number of background worker threads, and if a document — or one of its indexed fields — expires (via TTL or `HPEXPIRE`) at the exact moment a background search is reading it, the server returns the matched id with an empty field payload instead of dropping it from the result set. This is most likely in workloads that combine search with short TTLs, such as a semantic cache or chat history.\n\nRedisVL detects and **silently skips** such a document (logging at `WARNING` level) whenever the query type guarantees a field would be present on a healthy match:\n\n- **`VectorQuery` / `VectorRangeQuery`** with `return_score=True` (the default) — a healthy match always carries a `vector_distance`.\n- **`FilterQuery` on JSON storage** that returns the whole object — a healthy match always carries its JSON payload.\n\nFor a plain **`FilterQuery` / `TextQuery` on hash storage**, a race victim is indistinguishable from a legitimately sparse result (for example, a document matched via an `INDEXMISSING` field, or a query that requested only the `id`). RedisVL cannot safely tell those apart, so it returns the document as an id-only `{\"id\": ...}` dict rather than risk dropping a valid result. If you query hash storage directly this way, use `.get()` for optional fields rather than assuming every field is present.\n\n### Detecting incomplete results\n\n`SearchIndex.query()` returns a `SearchResults` object, which is a normal list of result dictionaries with two extra attributes so you can tell a race-shortened result set apart from one that genuinely had fewer matches:\n\n- `results.dropped_count` — how many matched documents were skipped because their field payload was missing (`0` in the normal case).\n- `results.complete` — `False` when any document was dropped.\n\n```python\nresults = index.query(query)\n\nif not results.complete:\n    # e.g. retry, reconcile against a CountQuery, or annotate the answer\n    logger.warning(\"Result set is incomplete: %d dropped\", results.dropped_count)\n```\n\n`SearchResults` behaves exactly like a `list` everywhere else, so existing code needs no changes. (Operations that build a new list — slicing, `sorted()`, concatenation — return a plain `list` without these attributes.)\n\nPractical consequences:\n\n- A query may return **fewer results than `num_results`** (or fewer than `page_size` when paginating) when some matched documents were expiring. Treat those limits as upper bounds, not guarantees; use `results.complete` to detect when it happened.\n- A `CountQuery` reports the server’s match count, which still includes the expiring document, so a count can legitimately exceed the number of documents a materializing query returns at the same instant.\n- The higher-level extensions build on this: the **semantic cache** drops an expiring hit (a benign cache miss), **message history** drops an expiring message from its formatted output, and the **semantic router** drops an expiring route candidate (which, in the rare case the best match is the one expiring, can shift the selected route). Message history’s `raw=True` mode returns the unprocessed hash entries and may therefore still surface an id-only record.\n\n**Learn more:** [Use Advanced Query Types](https://redis.io/docs/latest/../user_guide/how_to_guides/advanced_queries) demonstrates these query types in detail.\n",
  "tags": [],
  "last_updated": "2026-08-20T09:47:49+02:00"
}
