Vector Search with Azure Managed Redis
30-second answer
Azure Managed Redis does vector search through the RediSearch module, which you must select when you create the cache (with Redis 7.4) along with the Enterprise or Non-clustered clustering policy. You store embeddings as FLOAT32 bytes in hashes, create an index with FT.CREATE ... SCHEMA ... VECTOR HNSW (or FLAT) TYPE FLOAT32 DIM 1536 DISTANCE_METRIC COSINE, and query with FT.SEARCH using =>[KNN 3 @embedding $vec] and DIALECT 2. A common use is a semantic cache that returns a saved answer when a new question means the same thing.
Exam objective: 2.3.2 Implement vector indexing to enable similarity search. (Skills measured as of October 7, 2026)
Simulations
Feel it before you read it. No account needed, nothing leaves this page.
Open <strong>Azure Managed Redis</strong> and select <strong>+ Create</strong>.
👆 Click the glowing item in the portal to continue
Read the steps as text
- Open Azure Managed Redis and select + Create.
- Pick a performance tier and size. Then go straight to Advanced: some choices there can’t change later.
- For vector search tick RediSearch and use the Enterprise clustering policy. OSS clustering doesn’t support it.
- Review and Create.
- Managed Redis listens on port 10000 over TLS. Open a terminal and connect with redis-cli.
- Cache-aside: miss → read the database → SET with a TTL → next read is a hit. When the product changes, DEL the key.
- Hit rate climbs as the cache warms up. Every hit is a database read, or an LLM call, you didn’t pay for.
🧪 Simulation for learning. Screens are simplified versions of the Azure portal; names, prices and IDs are examples. Nothing here touches real Azure.
🖱️ Drag to rotate · scroll or pinch to zoom
Azure Managed Redis
Azure Managed Redis keeps hot data in memory. Cache-aside: check Redis, and on a miss read the database and store the result with a TTL. When data changes, invalidate the key. Redis can also hold a vector index for fast similarity search, for example a semantic cache of answers.
🤔 What happens if…
Read this tour as text
- Text becomes a vector. An embedding model turns text into a list of numbers, a vector (1,536 numbers for
text-embedding-3-small). Texts that mean similar things get vectors that sit close together, so "refund" lands near "money back". - Cosmos DB: items, partitions, RUs. In Azure Cosmos DB for NoSQL, JSON items live in containers, spread across logical partitions by the partition key. Every operation costs Request Units (RUs). A point read by id and partition key costs about 1 RU. A query that scans every partition costs far more.
- Indexing and consistency. By default Cosmos DB indexes every property, so writes cost more RUs. An indexing policy can exclude paths you never filter on, such as the big
embeddingarray. Consistency levels trade freshness for speed and cost: Strong, Bounded staleness, Session (default), Consistent prefix, Eventual. - Vector search in Cosmos DB. A vector embedding policy tells Cosmos DB where the vectors are, their dimensions and distance function. A vector index makes search fast:
diskANNorquantizedFlatfor large sets, orflatfor exact search on small vectors (up to 505 dimensions). ThenORDER BY VectorDistance(c.embedding, @q)returns the closest items. - Change feed. The change feed is an ordered log of inserts and updates in a container (deletes only show up in the *all versions and deletes* mode). A change feed processor reads it with a lease container that remembers how far each worker got, so a new product can be embedded the moment it’s saved.
- PostgreSQL with pgvector. In Azure Database for PostgreSQL, the pgvector extension adds a
vector(1536)column type. Without an index, every search compares against every row (a sequential scan). An HNSW or IVFFlat index finds near neighbours fast, trading a little recall for a lot of speed. - RAG with a metadata filter. Retrieval-augmented generation (RAG): embed the question, fetch the closest chunks (
ORDER BY embedding <=> $1 LIMIT 5), filter by metadata such astenant_idorlang, then send those chunks to the model as context. The answer is grounded in your own data. - Azure Managed Redis. Azure Managed Redis keeps hot data in memory. Cache-aside: check Redis, and on a miss read the database and store the result with a TTL. When data changes, invalidate the key. Redis can also hold a vector index for fast similarity search, for example a semantic cache of answers.
Make a slow product lookup fast with the cache-aside pattern, watch keys expire, then turn the same cache into a vector store for support articles with RediSearch.
🎓 Education-only simulation. Your lab is saved in this browser, so you can leave and continue later.
😟 THE PROBLEM
Users ask the same question 50 ways and you pay the LLM every time.
😊 THE SOLUTION
A Redis vector index finds similar past questions and reuses the answer.
- Repeat LLM calls✓ Semantic cache
- Exact-match keys only✓ KNN vector search
- Slow vector store✓ In-memory HNSW
Start with a question
Two customers ask 'How do I reset my password?' and 'I forgot my password, what now?'. Should your app pay the model twice?
A normal cache only helps if the question is typed exactly the same way. People don’t do that. A good receptionist hears both questions and knows they mean the same thing, so she hands over the same printed sheet.
Vector search in Azure Managed Redis gives your app that skill. Each question becomes an embedding, Redis finds the stored question with the closest meaning in about a millisecond, and if it’s close enough you reuse the saved answer. That’s a semantic cache, and the same index can power fast retrieval for RAG too.
Explain it like I’m 10
The technical explanation
Step 1: create the cache with RediSearch
Vector search lives in the RediSearch module. On the Advanced tab when you create the cache:
- With Redis 7.4 (the default version), tick RediSearch under modules. You can’t add or change modules after creation. With Redis 8.2 (preview) on the in-memory tiers, all modules are already included.
- Choose the Enterprise or Non-clustered clustering policy. RediSearch doesn’t support the OSS clustering policy, and you can’t switch from OSS or Enterprise later.
Get this wrong and the only fix is a new cache, so it’s a favourite exam trap.
Step 2: store embeddings as bytes
Each document or cached prompt is a hash with normal fields plus the embedding as raw FLOAT32 bytes:
import numpy as np
def to_bytes(vec) -> bytes:
return np.asarray(vec, dtype=np.float32).tobytes() # 1536 x 4 bytes
r.hset("doc:1001", mapping={
"content": "To reset your password, open Settings > Security...",
"tenant": "contoso",
"embedding": to_bytes(embed("To reset your password, open Settings > Security...")),
})
For this, create the Redis client with decode_responses=False, because the embedding is binary.
Step 3: create the vector index
FT.CREATE idx:docs ON HASH PREFIX 1 doc:
SCHEMA
content TEXT
tenant TAG
embedding VECTOR HNSW 6 TYPE FLOAT32 DIM 1536 DISTANCE_METRIC COSINE
ON HASH PREFIX 1 doc:indexes every hash whose key starts withdoc:, including ones you add later.HNSW 6means six attribute arguments follow (three name-value pairs).DIMmust match your embedding model exactly.DISTANCE_METRICcan beCOSINE,L2orIP.TAGfields such astenantgive you exact-match filters.
| Algorithm | How it searches | Use it when |
|---|---|---|
| FLAT | Compares against every vector (exact) | Small sets, up to tens of thousands, or when you need perfect recall |
| HNSW | Walks a graph (approximate), tuned with M, EF_CONSTRUCTION, EF_RUNTIME | Larger sets where speed matters more than the last bit of recall |
Step 4: query with KNN
FT.SEARCH idx:docs "(@tenant:{contoso})=>[KNN 3 @embedding $vec AS score]"
PARAMS 2 vec <1536 float32 bytes>
SORTBY score
RETURN 2 content score
DIALECT 2
In Python:
from redis.commands.search.query import Query
q = (
Query("(@tenant:{contoso})=>[KNN 3 @embedding $vec AS score]")
.sort_by("score")
.return_fields("content", "score")
.dialect(2)
)
results = r.ft("idx:docs").search(q, query_params={"vec": to_bytes(embed(question))})
for doc in results.docs:
print(doc.score, doc.content)
The part before => is a pre-filter (here, only this tenant’s docs; * means all). score is the cosine distance, so lower means closer. DIALECT 2 is required for this KNN-with-parameters syntax.
-
1 Embed
Turn the new prompt into a 1536-number vector.
-
2 KNN 1
FT.SEARCH finds the closest cached prompt for this tenant and model.
-
3 Compare
If the distance is under the threshold (say 0.1), return the saved answer.
-
4 Miss
Otherwise call the model, then HSET the prompt, vector and answer with a TTL.
A semantic cache in a few lines
THRESHOLD = 0.10 # cosine distance; tune it on real questions
def answer(question: str, tenant: str) -> str:
vec = to_bytes(embed(question))
q = (Query(f"(@tenant:{{{tenant}}})=>[KNN 1 @embedding $vec AS score]")
.return_fields("response", "score").dialect(2))
hits = r.ft("idx:cache").search(q, query_params={"vec": vec}).docs
if hits and float(hits[0].score) < THRESHOLD:
return hits[0].response # semantic hit
text = call_model(question) # miss
key = f"cache:{tenant}:{uuid4()}"
r.hset(key, mapping={"prompt": question, "response": text, "tenant": tenant, "embedding": vec})
r.expire(key, 86400) # cached answers age out after a day
return text
Microsoft’s tutorial shows the same idea with RedisVL’s SemanticCache class, and Azure API Management can do it at the gateway with the llm-semantic-cache-lookup and llm-semantic-cache-store policies backed by Azure Managed Redis. Semantic caching is a pattern you build, not a switch on the cache.
Architect level Tuning a semantic cache so it doesn't hand out wrong answers
The threshold is the hard part. Too loose, and “cancel my order” gets the cached answer for “cancel my subscription”. Too strict, and you never hit. Start strict, log every hit with its distance, and loosen slowly. Partition the cache with TAG filters by tenant, user (for personal data), model deployment and prompt version, so a new system prompt doesn’t serve answers written under the old one. Give entries a TTL so facts like prices don’t live forever, and skip caching for prompts that include personal details or time-sensitive data.
Real-world business scenario
Litware Bank (fictional)
- The problem
- The bank's help assistant answered about 40,000 questions a day, and around a third were rewordings of the same 200 FAQs. Each one was a full model call, which pushed up token costs and made busy-hour replies slow.
- What they used
- Azure Managed Redis (Balanced tier, RediSearch, Enterprise clustering) holding a semantic cache: prompt embeddings in an HNSW index with tenant and prompt-version TAG filters, a strict distance threshold and a 24-hour TTL.
- Why that choice
- Reworded questions now match a cached answer in a few milliseconds, while new or personal questions still go to the model. Version tags stop old answers surviving a prompt change.
- The result
- A large share of FAQ traffic is served from the cache, and replies to common questions became near-instant.
When to use it and when not to
✓ Use it when…
- You want a semantic cache in front of a language model to save tokens and time.
- You need millisecond vector lookups over a working set that fits in memory.
- You already use Azure Managed Redis for caching and want vectors in the same place.
✕ Think twice when…
- Very large document collections that would be costly to keep in RAM. pgvector or Azure AI Search fit better.
- Answers that depend on personal or fast-changing data. Don't serve them from a shared semantic cache.
- A cache already created with the OSS clustering policy or without RediSearch. You'll need a new cache.
↔ Alternatives to consider
- pgvector on Azure Database for PostgreSQL when vectors belong with relational data and filters.
- Azure Cosmos DB for NoSQL vector search for document apps at global scale.
- Azure API Management semantic caching to add caching at the gateway without app changes.
Test yourself with exercises
5 original practice questions in the AI-200 style. Pick your answers, then check them. You will see why each option is right or wrong. Score 75% or more and this topic is marked complete.
Interview preparation
Say your answer out loud first, then open the model answer. Interviewers care more about your reasoning than the exact words.
Beginner What do you need to do vector search in Azure Managed Redis?
Model answer
A cache with the RediSearch module, which on Redis 7.4 you pick on the Advanced tab when creating it, and the Enterprise or Non-clustered clustering policy. Then I store each document's embedding as bytes in a hash, create an index with FT.CREATE that declares a VECTOR field, and query with FT.SEARCH using KNN.
Interviewer follows up
Can you add RediSearch to an existing cache later?
You
Not with Redis 7.4. Modules are chosen at creation and can't be added afterwards, so you'd create a new cache. Redis 8.2 (preview) includes the modules on the in-memory tiers.
Intermediate Why does your KNN query fail with a syntax error even though the index exists?
Model answer
Usually because DIALECT 2 is missing. Vector KNN syntax with $parameters needs query dialect 2. The other common one is sending the vector as a JSON string instead of raw FLOAT32 bytes.
Experienced developer How does a semantic cache decide whether to reuse an answer?
Model answer
It embeds the new prompt, runs a KNN 1 search over cached prompts, and compares the returned cosine distance with a threshold, say 0.1. Below the threshold it returns the stored response; above it, it calls the model and stores the new prompt, embedding and response with a TTL. I also filter by tenant, model and prompt version so one customer never gets another's answer and old prompts don't leak into a new release.
Architecture & design When would you use Redis for vectors rather than PostgreSQL with pgvector?
Model answer
Redis when I need very low latency and the data is a working set that fits in memory, like a semantic cache or a session-level memory for an agent. pgvector when the vectors belong with relational business data, need joins and transactions, or are too big to keep in RAM affordably.
Quick revision
Key points
- RediSearch must be selected at cache creation (Redis 7.4) and needs Enterprise or Non-clustered clustering, not OSS.
- Store vectors as raw FLOAT32 bytes, for example numpy.astype(np.float32).tobytes().
- FT.CREATE idx ON HASH PREFIX 1 doc: SCHEMA ... embedding VECTOR HNSW 6 TYPE FLOAT32 DIM 1536 DISTANCE_METRIC COSINE
- FT.SEARCH idx "*=>[KNN 3 @embedding $vec AS score]" PARAMS 2 vec <bytes> SORTBY score DIALECT 2
- FLAT is exact and fine for small sets; HNSW is approximate and fast for large ones.
- A semantic cache reuses a response when the cosine distance is under a threshold.
Important terminology
- RediSearch
- The Redis module that adds secondary indexes, full-text search and vector similarity search. In Azure Managed Redis on Redis 7.4 it's chosen at creation.
- FT.CREATE
- The RediSearch command that defines an index over keys with a prefix, listing fields such as TEXT, TAG, NUMERIC and VECTOR.
- FT.SEARCH
- The RediSearch command that queries an index. Vector queries use KNN syntax and need DIALECT 2.
- HNSW vs FLAT
- Vector index algorithms in Redis. FLAT compares against every vector (exact); HNSW uses a graph for fast approximate search.
- KNN
- K-nearest neighbours. KNN 3 returns the 3 vectors closest to the query vector.
- Semantic cache
- A cache keyed by meaning. It stores prompts, their embeddings and responses, and reuses a response when a new prompt is close enough.
Common mistakes
- Creating the cache without RediSearch, or with the OSS clustering policy, then trying to run FT.CREATE.
- Leaving out DIALECT 2 on a KNN query.
- Declaring DIM 1536 but sending vectors from a model with different dimensions.
Exam tips
- "Vector index in Azure Managed Redis" = RediSearch module, chosen at creation.
- "Exact search over a small set" = FLAT; "fast approximate search at scale" = HNSW.
- "Return the 5 nearest vectors" = FT.SEARCH with KNN 5 and DIALECT 2.
Five quick revision questions
-
1.Which command creates a vector index?Show
FT.CREATE
-
2.Which data type do vectors use in the index definition here?Show
FLOAT32
-
3.Which clustering policy can't be used with RediSearch?Show
OSS
-
4.In COSINE distance results, is a lower score closer or further?Show
Closer.
-
5.Which query dialect does KNN need?Show
DIALECT 2
Official references
Finished this lesson? Tick it off. Your progress is saved in this browser.
Next up: Azure Service Bus Queues: Send, Receive and Settle Messages
Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges.