Guilds AI / Blog

,

Redis Vector Database: How It Works and When to Use It

Laptop illustrating Redis vector search, document embeddings and similarity indexing.

Redis can act as a vector database by storing numerical embeddings, indexing them and retrieving records that are close to a query vector. It is a useful option for applications that already use Redis or need frequent updates to searchable data. You can use it for semantic search, retrieval-augmented generation (RAG), recommendations and semantic caching. Its memory requirements and retrieval accuracy still need to be evaluated against the workload.

What is the Redis vector database?

Redis is a general-purpose data store with vector search capabilities. The Redis Query Engine lets you index vector fields alongside searchable text, numeric values and tags in hash or JSON records. A query can find the nearest vectors within a filtered set of documents, rather than retrieving similar vectors across the entire collection.

An embedding is an array of numbers produced by a model. For a document retrieval application, the application generates an embedding for each text passage and stores it in Redis with its content and metadata. It then embeds the user’s question with a compatible model and asks Redis to find the nearest passages.

The embedding model produces the vectors; Redis stores and searches them. A high similarity score does not establish that a document contains the correct answer. Our comparison of vector search and keyword search explains when lexical matches or hybrid retrieval may be more appropriate.

Redis 8 incorporates search functionality that previously required Redis Stack or a compatible Search module in many installations. Redis also offers a native Vector Sets data type, using commands such as VADD and VSIM. Vector Sets can be useful for simpler similarity lookups, while Query Engine indexes support a broader combination of searchable fields and filtering. Confirm the supported commands and data types in your specific deployment.

Choose a Redis vector index

The index algorithm determines how Redis finds nearby vectors. Its current documentation describes three index types for the Query Engine.

IndexApproachChoose it when
FLATExact distance comparisonsThe dataset is small or you need an exact nearest-neighbor baseline.
HNSWApproximate graph-based retrievalYou need to search larger collections with a configurable accuracy and latency trade-off.
SVS-VAMANAGraph-based retrieval with compression optionsYour Redis version and hardware support it and reducing memory use is important.

FLAT is useful for establishing ground truth when testing approximate indexes. HNSW adds graph connections and search parameters that influence recall, memory and latency. Increasing the number of candidates explored during a query can improve recall, but it may increase response time. SVS-VAMANA support was introduced in Redis 8.2; available compression features depend on the deployment.

Choose a distance metric that is appropriate for your embedding model. Redis supports cosine distance, Euclidean distance (L2) and inner-product distance. Smaller distance values indicate closer vectors under the chosen metric. Keep the vector dimensions, data type and encoding consistent between ingestion and queries.

How to use Redis for vector search in Python

This small Python example isolates the database behavior from embedding generation. It uses three-dimensional fictional vectors representing two help articles and searches only records in the support category. In a real application, replace them with vectors from an embedding model and set the index dimensions to that model’s output.

Use a development Redis instance with Query Engine vector search enabled and install the Python redis client with pip install redis. This example assumes a local instance on port 6379. For a remote deployment, use its authentication and TLS settings rather than exposing a local unauthenticated server.

import struct
from uuid import uuid4
from redis import Redis

r = Redis(host="localhost", port=6379)
run_id = uuid4().hex
prefix = f"demo:{run_id}:"
index = f"demo_idx_{run_id}"

def vector(values):
    return struct.pack("=3f", *values)

r.execute_command(
    "FT.CREATE", index, "ON", "HASH", "PREFIX", 1, prefix,
    "SCHEMA", "text", "TEXT", "category", "TAG",
    "embedding", "VECTOR", "FLAT", 6,
    "TYPE", "FLOAT32", "DIM", 3, "DISTANCE_METRIC", "COSINE"
)

r.hset(prefix + "1", mapping={
    "text": "Reset your account password",
    "category": "support",
    "embedding": vector([1.0, 0.0, 0.0])
})
r.hset(prefix + "2", mapping={
    "text": "Update the billing address",
    "category": "support",
    "embedding": vector([0.0, 1.0, 0.0])
})

result = r.execute_command(
    "FT.SEARCH", index,
    "(@category:{support})=>[KNN 2 @embedding $q AS distance]",
    "PARAMS", 2, "q", vector([0.9, 0.1, 0.0]),
    "SORTBY", "distance", "ASC",
    "RETURN", 2, "text", "distance", "DIALECT", 2
)
print(result)

The first document should rank ahead of the second because the query vector is closer to its vector under cosine distance. The example uses a unique index and key prefix to avoid overwriting existing records. It is an illustrative command sequence reviewed against Redis documentation, not an executed integration test. If a newly created index is not ready, check its status using FT.INFO before rerunning the search. Remove the demo index and its two demo keys when you finish.

For production, use consistent identifiers instead of random prefixes, validate vector dimensions before writing and handle failures when indexing records. A vector field stores the binary representation in a Redis hash; a JSON document can store an array of numeric values instead. The query parameter still needs the compatible vector representation.

Using Redis vector search for RAG

In a RAG application, Redis is the retrieval layer. Store the text passage, vector, document ID, version and access metadata. When a question arrives, embed it, restrict the candidate set to authorized and current documents, retrieve relevant passages and pass the selected text to the language model. Keep source identifiers so the application can display evidence for its response.

A useful retrieval pipeline does not require every result to reach the model. Reject stale or irrelevant matches, and handle questions with no suitable documents instead of forcing an answer. For a more complete architecture, see our guide to building RAG agents.

Semantic caching is a separate use case: a service searches embeddings of previous questions to find reusable answers. A close match is insufficient on its own; scope cached answers by tenant, permissions, model and source version, and expire them appropriately. Our AI agent caching guide covers cache invalidation and stale responses.

Memory requirements and operating costs

Estimate memory before committing to a vector index. A FLOAT32 vector uses four bytes per dimension. For 500,000 vectors of 768 dimensions, raw vector values alone occupy 1,536,000,000 bytes, or approximately 1.54 GB (1.43 GiB). This excludes records, metadata, index structures, fragmentation, replication and other operational overhead.

Vector countDimensionsRaw FLOAT32 values
100,000384153.6 MB
500,0007681.54 GB
1,000,0001,5366.14 GB

Actual memory consumption can exceed this estimate. Use a representative sample with the intended index and document structure, then measure memory and query latency. Compression or smaller embedding dimensions may reduce storage requirements, but benchmark recall before adopting them.

A local Redis installation and a managed Redis service have different cost structures. Infrastructure, replicas, persistence, backups, embedding generation and maintenance can all contribute to total cost. Avoid choosing a capacity tier solely from raw vector bytes. Confirm persistence and eviction behavior as well: search data should not disappear unexpectedly just because the cache is under pressure.

When to use Redis instead of a dedicated vector database

SituationPractical choice
Existing Redis application with rapidly changing searchable recordsEvaluate Redis first to avoid adding a separate retrieval system.
Small corpus requiring exact similarityStart with a FLAT index and measure results.
Relational source data and frequent SQL joinsEvaluate vector support in the existing relational database.
Large vector corpus with tight memory constraintsCompare compressed indexes and specialized vector stores using your own data.

Run the same test questions against each candidate. Measure retrieval recall, relevance, filtered-query latency, ingestion throughput, memory and recovery behavior. A faster database is not necessarily a better choice if it returns the wrong documents. Our LLM frameworks guide explains how retrieval components fit into the wider application stack.

Redis is particularly worth evaluating when vector lookup and application data already belong in the same system. A dedicated vector database may be more appropriate when its storage architecture or specialized retrieval capabilities better meet your scale, durability and cost requirements. Choose using measured workload behavior rather than a generic performance claim.

Frequently asked questions

Is Redis a vector database? Yes. Supported Redis deployments can store embeddings, index them and perform nearest-neighbor searches. Redis also provides general-purpose data storage and caching features.

Does Redis generate embeddings? Typically the application uses an embedding model or integration to generate the vectors. Redis indexes and searches the resulting values.

Can Redis perform hybrid search? Yes. The Query Engine can combine vector search with structured filters. Redis 8.4 also introduced FT.HYBRID for fusing lexical and vector rankings. Check the commands supported by your version.

Is Redis vector search free? You can run a compatible self-hosted deployment, subject to its licensing terms. Hardware, hosting, embedding generation and maintenance can still incur costs. Managed services have separate pricing.

Should I use FLAT or HNSW? Start with FLAT for an exact baseline. Consider HNSW when the exact approach becomes too slow for your dataset, and measure recall and latency before switching.