Vector search

Use Redis 8 as a vector store for RAG, and as a semantic cache that can reuse an answer when a new question means the same thing.

Updated CompTech Team

Redis 8 can index vectors. A RAG pipeline can store chunk embeddings in a hash and retrieve the nearest ones with FT.SEARCH, and a chatbot can keep a semantic cache: if a new question is close enough to one already answered, return that answer and do not call the model. Both are real, and they are different indexes with different lifetimes. The retrieval design is the RAG lab. The comparison with a database built for this is the vector databases lab. This page is the Redis version.

Confirm the query engine

Upstream Redis 8 includes the query engine that provides FT.CREATE. The OpsTree image used in the other labs may be built without it. Check before you write a client.

oc exec -n cache cache-0 -- redis-cli COMMAND INFO FT.CREATE

A reply that names ft.create means the server has it. An error that the command is unknown means this image does not. For this lab, point kubernetesConfig.image at docker.io/library/redis:8.2 and keep the same PVC and ConfigMap. Do not assume Valkey has the same commands. Its search module is a separate install.

Vectors are floats produced by the embedding model from the RAG lab. The index dimension has to match that model. 768 is a placeholder below. Read the model card and put the real number in DIM. Changing the embedding model means dropping the index and writing the hashes again.

An index for passages

oc exec -n cache cache-0 -- redis-cli FT.CREATE doc:idx \
  ON HASH PREFIX 1 doc: \
  SCHEMA text TEXT source TAG \
  embedding VECTOR HNSW 6 TYPE FLOAT32 DIM 768 DISTANCE_METRIC COSINE

HNSW is the approximate index. FLAT is exact and is the right choice while you only have a few thousand chunks, because then you can see whether a miss is the index or the embedding. COSINE matches the distance most text embedding models expect. If the model card says inner product or L2, set DISTANCE_METRIC to IP or L2 instead. A mismatch still returns neighbours. They are the wrong neighbours.

Write one chunk. The vector is raw little-endian float32 bytes, which is awkward from redis-cli. A short Python client is the practical way. redis-py packs the list for you:

import numpy as np
import redis
r = redis.Redis(host="cache.cache.svc", port=6379, decode_responses=False)
vec = np.random.rand(768).astype(np.float32)
r.hset("doc:1", mapping={
    "text": "Reset the password from the account page.",
    "source": "handbook",
    "embedding": vec.tobytes(),
})
q = vec.tobytes()
print(r.execute_command(
    "FT.SEARCH", "doc:idx", "*=>[KNN 3 @embedding $v AS score]",
    "PARAMS", "2", "v", q, "RETURN", "2", "text", "score", "DIALECT", "2",
))

decode_responses=False matters. A client that decodes the vector as UTF-8 will corrupt it. Store text and source beside the vector so the language model can cite the passage without a second lookup. Filter with the tag when the user may only see one corpus: @source:{handbook}=>[KNN 3 @embedding $v AS score]. The filter is the access-control point. Do not retrieve first and hope the prompt ignores the other documents.

Hybrid search, keywords plus vectors, is FT.HYBRID on Redis 8.4 and later. On 8.2, run a text query and a KNN query and merge in the application. Part numbers and acronyms still need the keyword side. Embeddings miss them, which the RAG lab explains.

Trim what you index. Redis holds the vectors in memory. A million long vectors on the same instance as your sessions will evict the sessions or be evicted by them. For a corpus that has to grow past the memory you are willing to give Redis, use Milvus or pgvector. Redis fits a bounded corpus and a cache that must answer in the same process as the rest of the hot data.

A semantic cache

A semantic cache stores a question embedding, the question text, and the answer the model already gave. On the next question you search that index first.

oc exec -n cache cache-0 -- redis-cli FT.CREATE q:idx \
  ON HASH PREFIX 1 q: \
  SCHEMA q TEXT answer TEXT \
  embedding VECTOR HNSW 6 TYPE FLOAT32 DIM 768 DISTANCE_METRIC COSINE

The application:

  1. Embed the new question with the same model.
  2. KNN 1 against q:idx.
  3. If the distance is close enough, return the stored answer and increment a hit counter.
  4. If it is not, call the language model, then HSET the new triple with a TTL.

"Close enough" is a threshold you measure. Take twenty paraphrases that must hit and twenty unrelated questions that must miss. Put the cut between the two distances you observed. A threshold copied from a blog will return a confident answer to the wrong question, which is worse than no cache. Revisit it when you change the embedding model.

Give the cache a TTL (EXPIRE q:<id> 86400 or a hash field you sweep). A cached answer goes stale when the handbook changes. On any document update, drop the matching q: keys or flush the whole q: prefix. A semantic cache of RAG answers without an invalidation path will serve yesterday's policy with today's confidence.

Do not cache when the answer depends on the user. "What is my balance" must not be reused for the next person because the wording matched. Key the cache by audience, or skip the cache for any prompt that included personal data.

Operate it

Persistence from the previous lab covers the hashes. Rebuilding from the source documents is still the real recovery: keep the chunking job, and treat Redis as a copy you can refill. A restore of a vector index from an old RDB after you have changed the embedding model will search garbage. Drop doc:idx and reindex.

Watch memory. INFO memory and the used-memory graph in the monitoring lab are how you see the index crowding out the cache. Set maxmemory and a policy only if you understand that an eviction in the middle of a vector index removes answers. A dedicated Redis for vectors, separate from sessions, is the cleaner layout once both are in production.

What's next

Security and monitoring is the last lab in the Redis series: ACLs, TLS, Prometheus and Grafana. The language model that reads these chunks is served as in Running models.