Lesson 3 of 3 Azure Managed Redis for AI Solutions

Running Vector Search in Azure Managed Redis

This lesson explains RediSearch indexes, how to define a vector field, how to store and query vectors from Python, and how to build a semantic cache.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe the parts of an FT.CREATE vector field.
  • Explain how vectors are stored in hashes.
  • Describe a filtered KNN query.
  • Explain the design decisions of a semantic cache.

Search indexes in Redis

Ordinary Redis finds values only by key. The RediSearch module adds secondary indexes: an index watches all keys with a given prefix, such as doc:, and indexes chosen fields of the hashes or JSON documents stored under them. As soon as a matching key is written or deleted, the index is updated, so search results always reflect the current data. Field types include TEXT (full-text), TAG (exact-match categories), NUMERIC (ranges), GEO and VECTOR.

Because the index and the data are both in memory, searches return in about a millisecond, which makes Redis suitable for latency-critical retrieval and for caching in front of slower model calls.

Match the pairs

Search field types

Exam skills 2.3.2

Match each field in a RediSearch index with the field type it needs.

Log in to try this activity Interactive activities are free with an account.

Defining a vector index

FT.CREATE defines an index. A VECTOR field names an algorithm and its attributes: FLAT performs exact search over all vectors and suits small sets, while HNSW performs approximate search for larger sets, with optional M, EF_CONSTRUCTION and EF_RUNTIME parameters similar to pgvector's. Every vector field declares TYPE (such as FLOAT32), DIM and DISTANCE_METRIC (COSINE, L2 or IP).

FT.CREATE idx:docs ON HASH PREFIX 1 doc:
  SCHEMA tenant TAG
         category TAG
         content TEXT
         embedding VECTOR HNSW 6 TYPE FLOAT32 DIM 1536 DISTANCE_METRIC COSINE

The number after the algorithm (6 here) is the count of attribute arguments that follow. For hashes, vectors are stored as binary strings of packed floats; for JSON documents (ON JSON), they are stored as arrays of numbers and fields are addressed by JSON path.

Spot the bug

An index definition

Exam skills 2.3.2

Find the lines in this <code>FT.CREATE</code> command that do not match the data or the requirements.

Log in to try this activity Interactive activities are free with an account.

Storing and querying vectors from Python

In Python, an embedding is converted to bytes with NumPy before being written to a hash field. A query uses FT.SEARCH with a KNN clause and passes the query vector as a parameter; vector queries require query dialect 2. A filter expression before the KNN clause, such as a tenant tag, restricts the candidates, and the score field returns the distance.

import numpy as np
from redis.commands.search.query import Query

vec = np.array(embedding, dtype=np.float32).tobytes()
cache.hset("doc:1001", mapping={"tenant": "contoso", "category": "billing",
                                "content": "Invoices are issued on the first day...", "embedding": vec})

q_vec = np.array(question_embedding, dtype=np.float32).tobytes()
query = (Query("(@tenant:{contoso})=>[KNN 3 @embedding $vec AS score]")
         .sort_by("score").return_fields("content", "score").dialect(2))
for doc in cache.ft("idx:docs").search(query, query_params={"vec": q_vec}).docs:
    print(doc.score, doc.content[:60])

The client in this example must be created with decode_responses=False, or a separate binary-safe client used, because vectors are binary. With COSINE, the score is a cosine distance, so lower values are more similar. A range query with VECTOR_RANGE returns all vectors within a distance threshold instead of a fixed number, which suits semantic caching. Libraries such as RedisVL wrap these commands with higher-level abstractions.

True or false

Vectors from Python

Exam skills 2.3.2

Decide whether each statement about storing and querying vectors with redis-py is true.

Log in to try this activity Interactive activities are free with an account.

Semantic caching for language models

Calls to a large language model are slow and billed per token, and users often ask the same thing in different words. A semantic cache stores each answered prompt's embedding with the answer. For a new prompt, the application embeds it and searches the cache for a stored prompt within a similarity threshold; if one is found, it returns the cached answer without calling the model.

  1. Embed

    Embed the incoming prompt with the embedding model.

  2. Search

    Run a KNN or VECTOR_RANGE query, filtered by tenant and model version.

  3. Decide

    If the best distance is below the threshold, return the cached answer.

  4. Fill

    Otherwise call the model, then store the prompt embedding and answer with a TTL.

The threshold controls the trade-off: too loose and different questions receive the same answer, too strict and the cache rarely hits. Entries carry a TTL so that answers based on old data expire, and they are scoped by tenant, user permissions and model or prompt version, so that a cached answer is never shown to someone who could not have received it. An exact-match cache, keyed by a hash of the normalized prompt and model parameters, is a simpler complement for repeated identical requests.

Exact-match cache
LookupHash of the normalized prompt
Hits on paraphrasesNo
Cost per lookupOne GET
RiskLow
Choose when Identical requests repeat often
Semantic cache
LookupVector similarity of the prompt embedding
Hits on paraphrasesYes
Cost per lookupOne embedding call and one vector query
RiskA wrong answer if the threshold is too loose
Choose when Users ask the same thing in different words

The following diagram traces a question through a semantic cache for a support bot.

A semantic cache in Azure Managed Redis for the support bot. Each question is embedded and matched against cached prompt embeddings with a vector query filtered by tenant and model version. A match below the tested distance threshold returns the cached answer quickly; otherwise the chat model answers and the result is cached with a TTL of a few days.
An article update can also invalidate entries tagged with that article.
Select all that apply

A safe semantic cache

Exam skills 2.3.2 · 2.3.1

Identify the design choices a semantic cache for a multitenant assistant needs.

Log in to try this activity Interactive activities are free with an account.
Worked example

Reducing model cost for a support bot

A support bot calls a chat model for every question, and analysis shows that 40% of questions are paraphrases of about 300 common ones. Answers must reflect help articles that change weekly, and the bot serves several customer tenants with different products. Response time for common questions should be under 100 ms.

A semantic cache in Azure Managed Redis fits. Each cached entry is a hash with the prompt embedding, the answer, a tenant tag and a model-version tag, indexed with an HNSW vector field and TAG fields. Lookups filter on tenant and version and accept a match only below a tested distance threshold. Entries have a TTL of a few days, and an article update can also invalidate entries tagged with that article.

An exact-match cache would miss most paraphrases. Caching without a tenant filter could show one tenant's product answer to another. Fine-tuning the model would not reduce per-call cost or latency for repeated questions.

Check yourself

With DISTANCE_METRIC COSINE, does a lower or higher KNN score mean a closer match?

Show answer

Lower. The score is a cosine distance, so 0 means identical direction.

Exam Tips

Remember for the exam

  • FT.CREATE defines an index on a key prefix with a VECTOR field (FLAT or HNSW, TYPE, DIM, DISTANCE_METRIC).
  • Hash vectors are binary float32 bytes; KNN queries need DIALECT 2.
  • Put filters before the KNN clause; with COSINE, a lower score is more similar.
  • Semantic caches need a tested threshold, a TTL and scoping by tenant and model version.