Your profile

One profile for every MSDEVBUILD site. Only you can see it, and the site owner if you write in.

Lesson 19 of 28
❮Prev Next❯

Vector Search with Azure Managed Redis

Module 2: Data for AI ⏱ 11 min read Updated

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    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.

    Simulate it » No Azure account needed

    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.

    Azure portal: Create Azure Managed Redis and try commands Create a cache with the RediSearch module for vector indexes.
    </> Embed

    Embed this simulation

    Free for trainers, teachers and bloggers. Paste this into your page:

    Loading the portal…

    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
    1. Open Azure Managed Redis and select + Create.
    2. Pick a performance tier and size. Then go straight to Advanced: some choices there can’t change later.
    3. For vector search tick RediSearch and use the Enterprise clustering policy. OSS clustering doesn’t support it.
    4. Review and Create.
    5. Managed Redis listens on port 10000 over TLS. Open a terminal and connect with redis-cli.
    6. Cache-aside: miss → read the database → SET with a TTL → next read is a hit. When the product changes, DEL the key.
    7. 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.

    😟 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
    🛠️ Solved with: Redis vector index

    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 with doc:, including ones you add later.
    • HNSW 6 means six attribute arguments follow (three name-value pairs).
    • DIM must match your embedding model exactly. DISTANCE_METRIC can be COSINE, L2 or IP.
    • TAG fields such as tenant give you exact-match filters.
    AlgorithmHow it searchesUse it when
    FLATCompares against every vector (exact)Small sets, up to tens of thousands, or when you need perfect recall
    HNSWWalks a graph (approximate), tuned with M, EF_CONSTRUCTION, EF_RUNTIMELarger 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. 1 Embed

      Turn the new prompt into a 1536-number vector.

    2. 2 KNN 1

      FT.SEARCH finds the closest cached prompt for this tenant and model.

    3. 3 Compare

      If the distance is under the threshold (say 0.1), return the saved answer.

    4. 4 Miss

      Otherwise call the model, then HSET the prompt, vector and answer with a TTL.

    Semantic cache with Azure Managed Redis

    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

    Banking

    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.
    Ready for more?The full lesson adds the technical explanation, when to use it, interview questions and revision notes.

    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.

    Question 1

    Question 1 of 5

    You plan to create an Azure Managed Redis instance that runs Redis 7.4 and will be used for vector similarity search. Which configuration must you select when you create the instance?

    Question 2

    Question 2 of 5

    You need to create a RediSearch index over hashes whose keys start with doc: and that contain a 1,536-dimension embedding field. The index must use approximate nearest neighbor search with cosine distance. Which schema definition should you use for the embedding field?

    Question 3

    Question 3 of 5

    A developer runs FT.SEARCH idx:docs "*=>[KNN 3 @embedding $vec AS score]" PARAMS 2 vec <bytes> SORTBY score. The command returns a syntax error. The index exists and the vector is valid. What should the developer add to the command?

    Question 4

    Question 4 of 5

    A chatbot uses Azure Managed Redis as a semantic cache. For each new prompt, the application runs a KNN 1 search over cached prompts by using the COSINE metric. When should the application return the cached response?

    Question 5

    Question 5 of 5 · Select 2

    You are storing documents and embeddings in Azure Managed Redis for vector search by using redis-py. Each tenant must search only its own documents. Which TWO actions should you take?

    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. 1.Which command creates a vector index?Show

      FT.CREATE

    2. 2.Which data type do vectors use in the index definition here?Show

      FLOAT32

    3. 3.Which clustering policy can't be used with RediSearch?Show

      OSS

    4. 4.In COSINE distance results, is a lower score closer or further?Show

      Closer.

    5. 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

    Studying with a friend? Send them this lesson

    It's free and needs no sign-up. Their progress saves in their own browser.

    Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges. Play ❯

    Install MSDEVBUILD Azure

    Free · no account · works offline

    Save the whole course for offline ›

    Hi, I’m your Nimbus

    Your study buddy. Pick what we do next.

    MSDEVBUILD · Multi-Stack Dev Build

    Sign in to MSDEVBUILD

    One account for Azure certifications and the blog: sign in here and you are signed in on both. Your XP, streak, practice deck and certificate stay in sync on every device. Optional: everything works without an account.