Search Tutorials
--Ads--Azure AI Search for RAG
Create an Azure AI Search index with vector fields and run vector, hybrid and semantic-ranked queries.
Azure AI Search is Microsoft's managed search service and the most common retrieval layer for RAG on Azure. One index can combine full-text search, vector search, filters, facets and an optional semantic ranker that reranks results with a language model. This lesson creates an index with a vector field, uploads chunks with embeddings, and runs vector, hybrid and filtered queries from Python.
What you will learn
- How to define an Azure AI Search index with vector fields and an HNSW profile
- How to upload documents with embeddings
- How to run vector, hybrid (keyword + vector) and filtered queries
- Where the semantic ranker and integrated vectorisation fit
Prerequisites
- An Azure subscription with an Azure AI Search service, its endpoint and an admin key (or Microsoft Entra ID access)
- Hybrid Search with BM25 and Reciprocal Rank Fusion
The code follows the official azure-search-documents Python samples of November 2026 (REST API version 2026-10-01). It has not been executed against a live service for this tutorial. Check the samples for your SDK version; class names have changed between preview and GA releases in the past.
Installation
pip install azure-search-documents azure-identity sentence-transformers python-dotenv
Store AZURE_SEARCH_ENDPOINT and AZURE_SEARCH_KEY in a .env file or, better, use Microsoft Entra ID with DefaultAzureCredential and role assignments so that no key is needed.
Step 1: Define the index
import os
from azure.core.credentials import AzureKeyCredential
from azure.search.documents.indexes import SearchIndexClient
from azure.search.documents.indexes.models import (
HnswAlgorithmConfiguration, SearchableField, SearchField, SearchFieldDataType,
SearchIndex, SimpleField, VectorSearch, VectorSearchProfile,
)
from dotenv import load_dotenv
load_dotenv()
ENDPOINT = os.environ["AZURE_SEARCH_ENDPOINT"]
CREDENTIAL = AzureKeyCredential(os.environ["AZURE_SEARCH_KEY"])
INDEX = "rag-chunks"
fields = [
SimpleField(name="id", type=SearchFieldDataType.STRING, key=True),
SearchableField(name="content", type=SearchFieldDataType.STRING),
SimpleField(name="doc_id", type=SearchFieldDataType.STRING, filterable=True),
SimpleField(name="source", type=SearchFieldDataType.STRING),
SimpleField(name="tenant_id", type=SearchFieldDataType.STRING, filterable=True),
SimpleField(name="allowed_groups", type=SearchFieldDataType.Collection(SearchFieldDataType.STRING),
filterable=True),
SearchField(
name="content_vector",
type=SearchFieldDataType.Collection(SearchFieldDataType.SINGLE),
searchable=True,
vector_search_dimensions=384,
vector_search_profile_name="rag-vector-profile",
),
]
vector_search = VectorSearch(
algorithms=[HnswAlgorithmConfiguration(name="rag-hnsw")],
profiles=[VectorSearchProfile(name="rag-vector-profile", algorithm_configuration_name="rag-hnsw")],
)
index_client = SearchIndexClient(ENDPOINT, CREDENTIAL)
index_client.create_or_update_index(SearchIndex(name=INDEX, fields=fields, vector_search=vector_search))
print("index ready")
A vector field is a collection of single-precision floats with a fixed number of dimensions, linked to a vector profile that names the algorithm (HNSW here). content is a searchable text field for the keyword half of hybrid search, and the metadata fields are filterable so you can enforce permissions.
Step 2: Upload chunks
from azure.search.documents import SearchClient
from rag_helpers import embed
search_client = SearchClient(ENDPOINT, INDEX, CREDENTIAL)
chunks = [
{"id": "hr-leave-0", "doc_id": "hr-leave", "source": "leave-policy.md", "tenant_id": "acme",
"allowed_groups": ["staff"], "content": "Employees get 18 days of paid leave in their first year."},
{"id": "it-vpn-0", "doc_id": "it-vpn", "source": "vpn-guide.md", "tenant_id": "acme",
"allowed_groups": ["staff"], "content": "Error VPN-403 means your device certificate has expired."},
]
vectors = embed([c["content"] for c in chunks])
for chunk, vector in zip(chunks, vectors):
chunk["content_vector"] = vector.tolist()
for result in search_client.upload_documents(documents=chunks):
print(result.key, result.succeeded)
Document keys may only contain letters, digits, dashes, underscores and equals signs, so build them from safe identifiers. For large uploads, send batches of a few hundred documents.
Step 3: Vector, hybrid and filtered queries
from azure.search.documents.models import VectorizedQuery
def odata_literal(value: str) -> str:
return value.replace("'", "''") # OData escapes a quote by doubling it
def odata_groups_filter(tenant_id: str, groups: list[str]) -> str:
if any("," in g for g in groups):
raise ValueError("group names must not contain commas")
group_list = odata_literal(",".join(groups))
return (f"tenant_id eq '{odata_literal(tenant_id)}' and "
f"allowed_groups/any(g: search.in(g, '{group_list}', ','))")
def azure_search(question: str, tenant_id: str, groups: list[str], k: int = 5, hybrid: bool = True):
vector_query = VectorizedQuery(vector=embed(question, query=True)[0].tolist(),
k_nearest_neighbors=50, fields="content_vector")
results = search_client.search(
search_text=question if hybrid else None, # text + vector = hybrid (RRF fusion)
vector_queries=[vector_query],
filter=odata_groups_filter(tenant_id, groups),
select=["doc_id", "source", "content"],
top=k,
)
return [{"score": r["@search.score"], **{f: r[f] for f in ("doc_id", "source", "content")}}
for r in results]
for hit in azure_search("what does VPN-403 mean", "acme", ["staff"]):
print(f"{hit['score']:.4f} {hit['doc_id']} {hit['content']}")
0.0333 it-vpn Error VPN-403 means your device certificate has expired.
0.0161 hr-leave Employees get 18 days of paid leave in their first year.
When a query has both search_text and vector_queries, Azure AI Search runs both and merges them with Reciprocal Rank Fusion, so hybrid scores are small rank-based numbers. For vector-only queries, k_nearest_neighbors controls how many neighbours are found; for hybrid queries, top controls the final result count. Filters use OData syntax; search.in efficiently matches a field against a list of values.
Semantic ranker and integrated vectorisation
- Semantic ranker: an optional, separately billed feature that reranks the top results with a Microsoft language model and can return captions and answers. You define a semantic configuration on the index and pass
query_type="semantic"withsemantic_configuration_namein the search call. Check availability for your service tier and region. - Integrated vectorisation: Azure AI Search can chunk and embed documents during indexing (indexers and skillsets) and embed queries with a configured vectoriser, so you do not run your own embedding code.
- Agentic retrieval: newer Azure AI Search features plan sub-queries over knowledge sources. See Microsoft's RAG overview for Azure AI Search for the current options.
Common errors and troubleshooting
- "The vector field ... dimensions": the uploaded vector length does not equal
vector_search_dimensions. - Invalid document key: the key contains characters such as
#or/. - Filter errors: the field is not
filterable, or the OData string is malformed (unescaped quotes). - 403 Forbidden: wrong key, or the Entra ID identity lacks a search role on the service.
Key takeaways
- Define vector fields as
Collection(SINGLE)with dimensions and a vector profile backed by HNSW. - Query with
VectorizedQuery; addsearch_textfor hybrid search with RRF. - Enforce permissions with OData filters on filterable metadata fields.
- Consider the semantic ranker and integrated vectorisation to reduce custom code.
Frequently asked questions
Can I use Azure OpenAI embeddings instead?
Yes. Change vector_search_dimensions to the model's dimension and embed with Azure OpenAI; see RAG with Azure OpenAI.
Does Azure AI Search support document-level security?
Yes, through security filters as shown, and through newer built-in features for Entra ID-based permissions on some data sources. Check the current documentation for your sources.
Practice exercises
- Compare vector-only and hybrid results for ten questions that contain codes or names.
- Add a
departmentfacet and show result counts per department in your UI.
Related tutorials
- Vector Search with Elasticsearch and OpenSearch
- Deploying RAG on Azure
- Access Control and Document-Level Permissions