opción
HogarHogar Skill Gestión de bases de datos azure-search-documents-py

azure-search-documents-py

microsoft/skills microsoft/skills

Realiza búsquedas en los índices de Azure AI Search mediante el SDK de Python para realizar búsquedas de texto completo, vectoriales, híbridas y semánticas con enriquecimiento mediante IA.

...Expandir todo
2
Tiempo actualizado 14 de septiembre de 2026

SDK de Azure AI Search para Python

Búsqueda de texto completo, vectorial e híbrida con capacidades de enriquecimiento mediante IA.

Instalación

pip install azure-search-documents

Variables de entorno

AZURE_SEARCH_ENDPOINT=https://.search.windows.net  # Obligatorio para todos los métodos de autenticación
AZURE_SEARCH_INDEX_NAME= # Obligatorio para todos los métodos de autenticación
AZURE_TOKEN_CREDENTIALS=prod # Requerida solo si se utiliza DefaultAzureCredential en producción
AZURE_SEARCH_API_KEY= # Solo requerida para la ruta de autenticación con clave API heredada que se indica a continuación

Autenticación y ciclo de vida

🔑 Hay dos reglas que se aplican a todos los ejemplos de código que aparecen a continuación:

  1. Da prioridad a DefaultAzureCredential. Funciona tanto a nivel local (Azure CLI / VS Code / Developer CLI) como en Azure (identidad gestionada, identidad de carga de trabajo) sin necesidad de modificar el código. Evita las cadenas de conexión y las claves de cuenta o API, ya que eluden la auditoría y la rotación de Entra.
    • Desarrollo local: DefaultAzureCredential funciona tal cual.
    • Producción: establece AZURE_TOKEN_CREDENTIALS=prod (o AZURE_TOKEN_CREDENTIALS=) para limitar la cadena de credenciales a aquellas seguras para producción.
  2. Envuelve cada cliente en un gestor de contexto para que los transportes HTTP, los sockets y las cachés de tokens se liberen de forma determinista:
    • Sincrónico: con (...) como cliente:
    • Asíncrono: async con (...) como cliente: y async con DefaultAzureCredential() como credencial: (de azure.identity.aio)

Los fragmentos de código pueden abreviar esta configuración, pero el código de producción siempre debe seguir ambas reglas.

import os
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
from azure.search.documents import SearchClient

# Desarrollo local: DefaultAzureCredential. Producción: establece AZURE_TOKEN_CREDENTIALS=prod o AZURE_TOKEN_CREDENTIALS=
credential = DefaultAzureCredential(require_envvar=True)
# O bien, utiliza una credencial específica directamente en producción:
# Consulta https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()

with SearchClient(
    endpoint=os.environ["AZURE_SEARCH_ENDPOINT"],
    index_name=os.environ["AZURE_SEARCH_INDEX_NAME"],
    credential=credential,
) as client:
    results = list(client.search(search_text="*", top=5))

Antiguo: clave de API (implementaciones existentes con clave)

El código nuevo debe utilizar DefaultAzureCredential, tal y como se indica más arriba. Utilice AzureKeyCredential únicamente si dispone de una implementación con clave existente que aún no se haya migrado a Entra ID; por ejemplo, entornos regulados que aún estén completando su implementación de Entra. La misma AzureKeyCredential funciona con SearchIndexClient y SearchIndexerClient para operaciones de administración.

import os
from azure.core.credentials import AzureKeyCredential
from azure.search.documents import SearchClient

with SearchClient(
    endpoint=os.environ["AZURE_SEARCH_ENDPOINT"],
    index_name=os.environ["AZURE_SEARCH_INDEX_NAME"],
    credential=AzureKeyCredential(os.environ["AZURE_SEARCH_API_KEY"]),
) as client:
    results = list(client.search(search_text="*", top=5))

Tipos de cliente

Cliente Finalidad
SearchClient Operaciones de búsqueda y de documentos
SearchIndexClient Gestión de índices, mapas de sinónimos
SearchIndexerClient Indexadores, fuentes de datos, conjuntos de habilidades

Crear un índice con un campo vectorial

from azure.search.documents.indexes import SearchIndexClient
from azure.search.documents.indexes.models import (
    SearchIndex,
    SearchField,
    SearchFieldDataType,
    VectorSearch,
    HnswAlgorithmConfiguration,
    VectorSearchProfile,
    SearchableField,
    SimpleField
)

campos = [
    SimpleField(nombre="id", tipo=SearchFieldDataType.String, clave=True),
    SearchableField(nombre="título", tipo=SearchFieldDataType.String),
    SearchableField(nombre="contenido", tipo=SearchFieldDataType.String),
    SearchField(
        name="content_vector",
        type=SearchFieldDataType.Collection(SearchFieldDataType.Single),
        searchable=True,
        dimensiones_de_búsqueda_vectorial=1536,
        nombre_del_perfil_de_búsqueda_vectorial="mi-perfil-vectorial"
    )
]

vector_search = VectorSearch(
    algorithms=[
        HnswAlgorithmConfiguration(name="my-hnsw")
    ],
    perfiles=[
        VectorSearchProfile(
            nombre="my-vector-profile",
            nombre_de_la_configuración_del_algoritmo="my-hnsw"
        )
    ]
)

index = SearchIndex(
    name="my-index",
    fields=fields,
    vector_search=vector_search
)

with SearchIndexClient(endpoint, DefaultAzureCredential()) as index_client:
    index_client.create_or_update_index(index)

Cargar documentos

from azure.search.documents import SearchClient

documents = [
    {
        "id": "1",
        "title": "Azure AI Search",
        "content": "Servicio de búsqueda de texto completo y vectorial",
        "content_vector": [0,1, 0,2, ...]  # 1536 dimensiones
    }
]

with SearchClient(endpoint, "my-index", DefaultAzureCredential()) as client:
    result = client.upload_documents(documents)
    print(f"Se han cargado {len(result)} documentos")

Búsqueda por palabra clave

results = client.search(
    search_text="azure search",
    select=["id", "title", "content"],
    top=10
)

for result in results:
    print(f"{result['title']}: {result['@search.score']}")

Búsqueda vectorial

from azure.search.documents.models import VectorizedQuery

# Tu vector de incrustación de la consulta (1536 dimensiones)
query_vector = get_embedding("capacidades de búsqueda semántica")

vector_query = VectorizedQuery(
    vector=query_vector,
    k_nearest_neighbors=10,
    fields="content_vector"
)

results = client.search(
    vector_queries=[vector_query],
    select=["id", "title", "content"]
)

for result in results:
    print(f"{result['title']}: {result['@search.score']}")

Búsqueda híbrida (vector + palabra clave)

from azure.search.documents.models import VectorizedQuery

vector_query = VectorizedQuery(
    vector=query_vector,
    k_nearest_neighbors=10,
    fields="content_vector"
)

results = client.search(
    search_text="azure search",
    vector_queries=[vector_query],
    select=["id", "title", "content"],
    top=10
)

Clasificación semántica

from azure.search.documents.models import QueryType

results = client.search(
    search_text="what is azure search",
    query_type=QueryType.SEMANTIC,
    semantic_configuration_name="my-semantic-config",
    select=["id", "title", "content"],
    top=10
)

for result in results:
    print(f"{result['title']}")
    if result.get("@search.captions"):
        print(f"  Título: {result['@search.captions'][0].text}")

Filtros

results = client.search(
    search_text="*",
    filter="category eq 'Technology' and rating gt 4",
    order_by=["rating desc"],
    select=["id", "title", "category", "rating"]
)

Facetas

results = client.search(
    search_text="*",
    facets=["category,count:10", "rating"],
    top=0  # Solo se obtienen las facetas, no los documentos
)

for facet_name, facet_values in results.get_facets().items():
    print(f"{facet_name}:")
    for facet in facet_values:
        print(f"  {facet['value']}: {facet['count']}")

Autocompletado y sugerencias

# Autocompletado
results = client.autocomplete(
    search_text="sea",
    suggester_name="my-suggester",
    mode="twoTerms"
)

# Sugerencias
results = client.suggest(
    search_text="sea",
    suggester_name="my-suggester",
    select=["title"]
)

Indexador con conjunto de habilidades

from azure.search.documents.indexes import SearchIndexerClient
from azure.search.documents.indexes.models import (
    SearchIndexer,
    SearchIndexerDataSourceConnection,
    SearchIndexerSkillset,
    EntityRecognitionSkill,
    InputFieldMappingEntry,
    OutputFieldMappingEntry
)

with SearchIndexerClient(endpoint, DefaultAzureCredential()) as indexer_client:
    # Utiliza una identidad gestionada (el servicio de búsqueda debe tener un rol RBAC en la cuenta de almacenamiento). Evita las cadenas de conexión de almacenamiento con claves incrustadas.
    data_source = SearchIndexerDataSourceConnection(
        name="my-datasource",
        type="azureblob",
        connection_string="ResourceId=/subscriptions//resourceGroups//providers/Microsoft.Storage/storageAccounts/",
        container={"name": "documents"}
    )
    indexer_client.create_or_update_data_source_connection(data_source)

    # Crear conjunto de habilidades
    skillset = SearchIndexerSkillset(
        name="my-skillset",
        skills=[
            EntityRecognitionSkill(
                inputs=[InputFieldMappingEntry(name="text", source="/document/content")],
                outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")]
            )
        ]
    )
    indexer_client.create_or_update_skillset(skillset)

    # Crear el indexador
    indexer = SearchIndexer(
        name="my-indexer",
        data_source_name="my-datasource",
        target_index_name="my-index",
        skillset_name="my-skillset"
    )
    indexer_client.create_or_update_indexer(indexer)

Prácticas recomendadas

  1. Elige entre síncrono O asíncrono y mantén la coherencia. No mezcles clientes síncronos azure.xxx con clientes asíncronos azure.xxx.aio en la misma ruta de llamada. Elige un modo por módulo.
  2. Utilice siempre gestores de contexto para los clientes y las credenciales asíncronas. Envuelva cada cliente con Client(...) como cliente: (sincrónico) o asíncrono con Client(...) como cliente: (asíncrono). Para el modo asíncrono, con DefaultAzureCredential de azure.identity.aio, utiliza también el modo asíncrono con credential: para que se eliminen los tokens y los transportes.
  3. Utiliza la búsqueda híbrida para obtener la mejor relevancia combinando vectores y palabras clave
  4. Habilita la clasificación semántica para las consultas en lenguaje natural
  5. Indexa en lotes de 100 a 1000 documentos para mayor eficiencia
  6. Utiliza filtros para acotar los resultados antes de la clasificación
  7. Configura las dimensiones vectoriales para que se ajusten a tu modelo de incrustación
  8. Utiliza el algoritmo HNSW para la búsqueda vectorial a gran escala
  9. Crea sugeridores en el momento de crear el índice (no se pueden añadir posteriormente)

Archivos de referencia

Archivo Contenido
references/vector-search.md Configuración de HNSW, vectorización integrada, consultas multivectoriales
references/semantic-ranking.md Configuración semántica, pies de foto, respuestas, patrones híbridos
scripts/setup_vector_index.py Script de la CLI para crear un índice de búsqueda con soporte vectorial

Patrones adicionales de Azure AI Search

SDK de Python para Azure AI Search

Escribe código Python limpio e idiomático para Azure AI Search utilizando azure-search-documents.

Instalación

pip install azure-search-documents azure-identity

Variables de entorno

AZURE_SEARCH_ENDPOINT=https://.search.windows.net  # Requerido para todos los métodos de autenticación
AZURE_SEARCH_INDEX_NAME= # Requerido para todos los métodos de autenticación
AZURE_TOKEN_CREDENTIALS=prod # Obligatorio solo si se utiliza DefaultAzureCredential en producción

Autenticación

import os
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
from azure.search.documents import SearchClient

# Desarrollo local: DefaultAzureCredential. Producción: establece AZURE_TOKEN_CREDENTIALS=prod o AZURE_TOKEN_CREDENTIALS=
credential = DefaultAzureCredential(require_envvar=True)
# O bien, utiliza una credencial específica directamente en producción:
# Consulta https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()

with SearchClient(
    endpoint=os.environ["AZURE_SEARCH_ENDPOINT"],
    index_name=os.environ["AZURE_SEARCH_INDEX_NAME"],
    credential=credential,
) as client:
    results = list(client.search(search_text="*", top=5))

Selección del cliente

Cliente Finalidad
SearchClient Consultar índices, cargar/actualizar/eliminar documentos
SearchIndexClient Crear y gestionar índices, fuentes de conocimiento y bases de conocimiento
SearchIndexerClient Gestionar indexadores, conjuntos de habilidades y fuentes de datos
KnowledgeBaseRetrievalClient Recuperación basada en agentes con preguntas y respuestas impulsadas por modelos de lenguaje grande (LLM)

Patrón de creación de índices

from azure.search.documents.indexes import SearchIndexClient
from azure.search.documents.indexes.models import (
    SearchIndex, SearchField, VectorSearch, VectorSearchProfile,
    HnswAlgorithmConfiguration, AzureOpenAIVectorizer,
    AzureOpenAIVectorizerParameters, SemanticSearch,
    SemanticConfiguration, SemanticPrioritizedFields, SemanticField
)

index = SearchIndex(
    name=index_name,
    fields=[
        SearchField(name="id", type="Edm.String", key=True),
        SearchField(name="content", type="Edm.String", searchable=True),
        SearchField(name="embedding", type="Collection(Edm.Single)",
                   vector_search_dimensions=3072,
                   vector_search_profile_name="vector-profile"),
    ],
    vector_search=VectorSearch(
        profiles=[VectorSearchProfile(
            name="vector-profile",
            algorithm_configuration_name="hnsw-algo",
            vectorizer_name="openai-vectorizer"
        )],
        algorithms=[HnswAlgorithmConfiguration(name="hnsw-algo")],
        vectorizers=[AzureOpenAIVectorizer(
            vectorizer_name="openai-vectorizer",
            parámetros=AzureOpenAIVectorizerParameters(
                url_del_recurso=aoai_endpoint,
                nombre_de_la_implementación=embedding_deployment,
                nombre_del_modelo=embedding_model
            )
        )]
    ),
    semantic_search=SemanticSearch(
        default_configuration_name="semantic-config",
        configurations=[SemanticConfiguration(
            name="semantic-config",
            campos_priorizados=SemanticPrioritizedFields(
                campos_de_contenido=[SemanticField(nombre_del_campo="content")]
            )
        )]
    )
)

con SearchIndexClient(endpoint, credential) como index_client:
    index_client.create_or_update_index(index)

Operaciones con documentos

from azure.search.documents import SearchIndexingBufferedSender

# Carga por lotes con agrupación automática
with SearchIndexingBufferedSender(endpoint, index_name, credential) as sender:
    sender.upload_documents(documents)

# Operaciones directas a través de SearchClient
with SearchClient(punto de conexión, nombre_del_índice, credencial) as search_client:
    search_client.upload_documents(documentos)      # Añadir nuevos
    search_client.merge_documents(documentos)       # Actualizar los existentes
    search_client.merge_or_upload_documents(documents)  # Upsert
    search_client.delete_documents(documents)      # Eliminar

Patrones de búsqueda

# Búsqueda básica
results = search_client.search(search_text="query")

# Búsqueda vectorial
from azure.search.documents.models import VectorizedQuery

resultados = search_client.search(
    text_de_búsqueda=None,
    consultas_vectoriales=[VectorizedQuery(
        vector=embedding,
        k_vecinos_más_cercanos=5,
        campos="embedding"
    )]
)

# Búsqueda híbrida (vector + palabra clave)
resultados = search_client.search(
    text_de_búsqueda="query",
    vector_queries=[VectorizedQuery(vector=embedding, k_nearest_neighbors=5, fields="embedding")],
    query_type="semantic",
    semantic_configuration_name="semantic-config"
)

# Con filtros
results = search_client.search(
    search_text="consulta",
    filter="category eq 'tecnología'",
    select=["id", "título", "contenido"],
    top=10
)

Recuperación agencial (bases de conocimiento)

Para consultar el sistema de preguntas y respuestas basado en LLM con síntesis de respuestas, véase references/agentic-retrieval.md.

Conceptos clave:

  • Fuente de conocimiento: apunta a un índice de búsqueda
  • Base de conocimiento: agrupa las fuentes de conocimiento y el LLM para la planificación y síntesis de consultas
  • Modos de salida: EXTRACTIVE_DATA (fragmentos sin procesar) o ANSWER_SYNTHESIS (respuestas generadas por el LLM)

Patrón asíncrono

from azure.search.documents.aio import SearchClient

async with SearchClient(endpoint, index_name, credential) as client:
    results = await client.search(search_text="query")
    async for result in results:
        print(result["title"])

Prácticas recomendadas

  1. Utiliza variables de entorno para los puntos de conexión, las claves y los nombres de implementación
  2. Utiliza DefaultAzureCredential para el código que se ejecuta localmente (en lugar de claves de API). Utiliza una credencial de token específica para el código que se ejecuta en Azure.
  3. Utilice SearchIndexingBufferedSender para las cargas por lotes (gestiona los lotes y los reintentos)
  4. Define siempre la configuración semántica para los índices de recuperación de tipo «agentic»
  5. Utilice ` create_or_update_index ` para la creación idempotente de índices
  6. Cierra los clientes con gestores de contexto o mediante la función close() explícita

Referencia de tipos de campo

Tipo EDM Python Notas
Edm.String str Texto en el que se puede realizar una búsqueda
Edm.Int32 int entero
Edm.Int64 int Entero largo
Edm.Double float Punto flotante
Edm.Boolean bool Verdadero/Falso
Edm.DateTimeOffset fecha y hora ISO 8601
Colección (Edm.Single) Lista[float] Representaciones vectoriales
Colección (Edm.String) Lista[str] Matrices de cadenas

Gestión de errores

from azure.core.exceptions import (
    HttpResponseError,
    ResourceNotFoundError,
    ResourceExistsError
)

try:
    result = search_client.get_document(key="123")
except ResourceNotFoundError:
    print("Documento no encontrado")
except HttpResponseError as e:
    print(f"Error de búsqueda: {e.message}")
Ver en GitHub
---
name: azure-search-documents-py
description: Search Azure AI Search indexes using the Python SDK for full-text, vector, hybrid, and semantic search with AI enrichment.
license: MIT
---

# Azure AI Search SDK for Python

Full-text, vector, and hybrid search with AI enrichment capabilities.

## Installation

```bash
pip install azure-search-documents
```

## Environment Variables

```bash
AZURE_SEARCH_ENDPOINT=https://<service-name>.search.windows.net  # Required for all auth methods
AZURE_SEARCH_INDEX_NAME=<your-index-name>  # Required for all auth methods
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
AZURE_SEARCH_API_KEY=<your-api-key>  # Only required for the legacy API-key auth path below
```

## Authentication & Lifecycle

> **🔑 Two rules apply to every code sample below:**
>
> 1. **Prefer `DefaultAzureCredential`.** It works locally (Azure CLI / VS Code / Developer CLI) and in Azure (managed identity, workload identity) with no code change. Avoid connection strings, account/API keys — they bypass Entra audit and rotation.
>    - Local dev: `DefaultAzureCredential` works as-is.
>    - Production: set `AZURE_TOKEN_CREDENTIALS=prod` (or `AZURE_TOKEN_CREDENTIALS=<specific_credential>`) to constrain the credential chain to production-safe credentials.
> 2. **Wrap every client in a context manager** so HTTP transports, sockets, and token caches are released deterministically:
>    - Sync: `with <Client>(...) as client:`
>    - Async: `async with <Client>(...) as client:` **and** `async with DefaultAzureCredential() as credential:` (from `azure.identity.aio`)
>
> Snippets may abbreviate this setup, but production code should always follow both rules.

```python
import os
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
from azure.search.documents import SearchClient

# Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
credential = DefaultAzureCredential(require_envvar=True)
# Or use a specific credential directly in production:
# See https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()

with SearchClient(
    endpoint=os.environ["AZURE_SEARCH_ENDPOINT"],
    index_name=os.environ["AZURE_SEARCH_INDEX_NAME"],
    credential=credential,
) as client:
    results = list(client.search(search_text="*", top=5))
```

### Legacy: API Key (existing keyed deployments)

New code should use `DefaultAzureCredential` above. Use `AzureKeyCredential` only if you have an existing keyed deployment that hasn't been migrated to Entra ID yet — for example, regulated environments still completing their Entra rollout. The same `AzureKeyCredential` works with `SearchIndexClient` and `SearchIndexerClient` for admin operations.

```python
import os
from azure.core.credentials import AzureKeyCredential
from azure.search.documents import SearchClient

with SearchClient(
    endpoint=os.environ["AZURE_SEARCH_ENDPOINT"],
    index_name=os.environ["AZURE_SEARCH_INDEX_NAME"],
    credential=AzureKeyCredential(os.environ["AZURE_SEARCH_API_KEY"]),
) as client:
    results = list(client.search(search_text="*", top=5))
```

## Client Types

| Client | Purpose |
|--------|---------|
| `SearchClient` | Search and document operations |
| `SearchIndexClient` | Index management, synonym maps |
| `SearchIndexerClient` | Indexers, data sources, skillsets |

## Create Index with Vector Field

```python
from azure.search.documents.indexes import SearchIndexClient
from azure.search.documents.indexes.models import (
    SearchIndex,
    SearchField,
    SearchFieldDataType,
    VectorSearch,
    HnswAlgorithmConfiguration,
    VectorSearchProfile,
    SearchableField,
    SimpleField
)

fields = [
    SimpleField(name="id", type=SearchFieldDataType.String, key=True),
    SearchableField(name="title", type=SearchFieldDataType.String),
    SearchableField(name="content", type=SearchFieldDataType.String),
    SearchField(
        name="content_vector",
        type=SearchFieldDataType.Collection(SearchFieldDataType.Single),
        searchable=True,
        vector_search_dimensions=1536,
        vector_search_profile_name="my-vector-profile"
    )
]

vector_search = VectorSearch(
    algorithms=[
        HnswAlgorithmConfiguration(name="my-hnsw")
    ],
    profiles=[
        VectorSearchProfile(
            name="my-vector-profile",
            algorithm_configuration_name="my-hnsw"
        )
    ]
)

index = SearchIndex(
    name="my-index",
    fields=fields,
    vector_search=vector_search
)

with SearchIndexClient(endpoint, DefaultAzureCredential()) as index_client:
    index_client.create_or_update_index(index)
```

## Upload Documents

```python
from azure.search.documents import SearchClient

documents = [
    {
        "id": "1",
        "title": "Azure AI Search",
        "content": "Full-text and vector search service",
        "content_vector": [0.1, 0.2, ...]  # 1536 dimensions
    }
]

with SearchClient(endpoint, "my-index", DefaultAzureCredential()) as client:
    result = client.upload_documents(documents)
    print(f"Uploaded {len(result)} documents")
```

## Keyword Search

```python
results = client.search(
    search_text="azure search",
    select=["id", "title", "content"],
    top=10
)

for result in results:
    print(f"{result['title']}: {result['@search.score']}")
```

## Vector Search

```python
from azure.search.documents.models import VectorizedQuery

# Your query embedding (1536 dimensions)
query_vector = get_embedding("semantic search capabilities")

vector_query = VectorizedQuery(
    vector=query_vector,
    k_nearest_neighbors=10,
    fields="content_vector"
)

results = client.search(
    vector_queries=[vector_query],
    select=["id", "title", "content"]
)

for result in results:
    print(f"{result['title']}: {result['@search.score']}")
```

## Hybrid Search (Vector + Keyword)

```python
from azure.search.documents.models import VectorizedQuery

vector_query = VectorizedQuery(
    vector=query_vector,
    k_nearest_neighbors=10,
    fields="content_vector"
)

results = client.search(
    search_text="azure search",
    vector_queries=[vector_query],
    select=["id", "title", "content"],
    top=10
)
```

## Semantic Ranking

```python
from azure.search.documents.models import QueryType

results = client.search(
    search_text="what is azure search",
    query_type=QueryType.SEMANTIC,
    semantic_configuration_name="my-semantic-config",
    select=["id", "title", "content"],
    top=10
)

for result in results:
    print(f"{result['title']}")
    if result.get("@search.captions"):
        print(f"  Caption: {result['@search.captions'][0].text}")
```

## Filters

```python
results = client.search(
    search_text="*",
    filter="category eq 'Technology' and rating gt 4",
    order_by=["rating desc"],
    select=["id", "title", "category", "rating"]
)
```

## Facets

```python
results = client.search(
    search_text="*",
    facets=["category,count:10", "rating"],
    top=0  # Only get facets, no documents
)

for facet_name, facet_values in results.get_facets().items():
    print(f"{facet_name}:")
    for facet in facet_values:
        print(f"  {facet['value']}: {facet['count']}")
```

## Autocomplete & Suggest

```python
# Autocomplete
results = client.autocomplete(
    search_text="sea",
    suggester_name="my-suggester",
    mode="twoTerms"
)

# Suggest
results = client.suggest(
    search_text="sea",
    suggester_name="my-suggester",
    select=["title"]
)
```

## Indexer with Skillset

```python
from azure.search.documents.indexes import SearchIndexerClient
from azure.search.documents.indexes.models import (
    SearchIndexer,
    SearchIndexerDataSourceConnection,
    SearchIndexerSkillset,
    EntityRecognitionSkill,
    InputFieldMappingEntry,
    OutputFieldMappingEntry
)

with SearchIndexerClient(endpoint, DefaultAzureCredential()) as indexer_client:
    # Use managed identity (search service must have RBAC role on the storage account). Avoid storage connection strings with embedded keys.
    data_source = SearchIndexerDataSourceConnection(
        name="my-datasource",
        type="azureblob",
        connection_string="ResourceId=/subscriptions/<sub>/resourceGroups/<rg>/providers/Microsoft.Storage/storageAccounts/<acct>",
        container={"name": "documents"}
    )
    indexer_client.create_or_update_data_source_connection(data_source)

    # Create skillset
    skillset = SearchIndexerSkillset(
        name="my-skillset",
        skills=[
            EntityRecognitionSkill(
                inputs=[InputFieldMappingEntry(name="text", source="/document/content")],
                outputs=[OutputFieldMappingEntry(name="organizations", target_name="organizations")]
            )
        ]
    )
    indexer_client.create_or_update_skillset(skillset)

    # Create indexer
    indexer = SearchIndexer(
        name="my-indexer",
        data_source_name="my-datasource",
        target_index_name="my-index",
        skillset_name="my-skillset"
    )
    indexer_client.create_or_update_indexer(indexer)
```

## Best Practices

1. **Pick sync OR async and stay consistent.** Do not mix `azure.xxx` sync clients with `azure.xxx.aio` async clients in the same call path. Choose one mode per module.
2. **Always use context managers for clients and async credentials.** Wrap every client in `with Client(...) as client:` (sync) or `async with Client(...) as client:` (async). For async `DefaultAzureCredential` from `azure.identity.aio`, also use `async with credential:` so tokens and transports are cleaned up.
3. **Use hybrid search** for best relevance combining vector and keyword
4. **Enable semantic ranking** for natural language queries
5. **Index in batches** of 100-1000 documents for efficiency
6. **Use filters** to narrow results before ranking
7. **Configure vector dimensions** to match your embedding model
8. **Use HNSW algorithm** for large-scale vector search
9. **Create suggesters** at index creation time (cannot add later)

## Reference Files

| File | Contents |
|------|----------|
| [references/vector-search.md](references/vector-search.md) | HNSW configuration, integrated vectorization, multi-vector queries |
| [references/semantic-ranking.md](references/semantic-ranking.md) | Semantic configuration, captions, answers, hybrid patterns |
| [scripts/setup_vector_index.py](scripts/setup_vector_index.py) | CLI script to create vector-enabled search index |


---

## Additional Azure AI Search Patterns

# Azure AI Search Python SDK

Write clean, idiomatic Python code for Azure AI Search using `azure-search-documents`.

## Installation

```bash
pip install azure-search-documents azure-identity
```

## Environment Variables

```bash
AZURE_SEARCH_ENDPOINT=https://<search-service>.search.windows.net  # Required for all auth methods
AZURE_SEARCH_INDEX_NAME=<index-name>  # Required for all auth methods
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
```

## Authentication

```python
import os
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
from azure.search.documents import SearchClient

# Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
credential = DefaultAzureCredential(require_envvar=True)
# Or use a specific credential directly in production:
# See https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()

with SearchClient(
    endpoint=os.environ["AZURE_SEARCH_ENDPOINT"],
    index_name=os.environ["AZURE_SEARCH_INDEX_NAME"],
    credential=credential,
) as client:
    results = list(client.search(search_text="*", top=5))
```

## Client Selection

| Client | Purpose |
|--------|---------|
| `SearchClient` | Query indexes, upload/update/delete documents |
| `SearchIndexClient` | Create/manage indexes, knowledge sources, knowledge bases |
| `SearchIndexerClient` | Manage indexers, skillsets, data sources |
| `KnowledgeBaseRetrievalClient` | Agentic retrieval with LLM-powered Q&A |

## Index Creation Pattern

```python
from azure.search.documents.indexes import SearchIndexClient
from azure.search.documents.indexes.models import (
    SearchIndex, SearchField, VectorSearch, VectorSearchProfile,
    HnswAlgorithmConfiguration, AzureOpenAIVectorizer,
    AzureOpenAIVectorizerParameters, SemanticSearch,
    SemanticConfiguration, SemanticPrioritizedFields, SemanticField
)

index = SearchIndex(
    name=index_name,
    fields=[
        SearchField(name="id", type="Edm.String", key=True),
        SearchField(name="content", type="Edm.String", searchable=True),
        SearchField(name="embedding", type="Collection(Edm.Single)",
                   vector_search_dimensions=3072,
                   vector_search_profile_name="vector-profile"),
    ],
    vector_search=VectorSearch(
        profiles=[VectorSearchProfile(
            name="vector-profile",
            algorithm_configuration_name="hnsw-algo",
            vectorizer_name="openai-vectorizer"
        )],
        algorithms=[HnswAlgorithmConfiguration(name="hnsw-algo")],
        vectorizers=[AzureOpenAIVectorizer(
            vectorizer_name="openai-vectorizer",
            parameters=AzureOpenAIVectorizerParameters(
                resource_url=aoai_endpoint,
                deployment_name=embedding_deployment,
                model_name=embedding_model
            )
        )]
    ),
    semantic_search=SemanticSearch(
        default_configuration_name="semantic-config",
        configurations=[SemanticConfiguration(
            name="semantic-config",
            prioritized_fields=SemanticPrioritizedFields(
                content_fields=[SemanticField(field_name="content")]
            )
        )]
    )
)

with SearchIndexClient(endpoint, credential) as index_client:
    index_client.create_or_update_index(index)
```

## Document Operations

```python
from azure.search.documents import SearchIndexingBufferedSender

# Batch upload with automatic batching
with SearchIndexingBufferedSender(endpoint, index_name, credential) as sender:
    sender.upload_documents(documents)

# Direct operations via SearchClient
with SearchClient(endpoint, index_name, credential) as search_client:
    search_client.upload_documents(documents)      # Add new
    search_client.merge_documents(documents)       # Update existing
    search_client.merge_or_upload_documents(documents)  # Upsert
    search_client.delete_documents(documents)      # Remove
```

## Search Patterns

```python
# Basic search
results = search_client.search(search_text="query")

# Vector search
from azure.search.documents.models import VectorizedQuery

results = search_client.search(
    search_text=None,
    vector_queries=[VectorizedQuery(
        vector=embedding,
        k_nearest_neighbors=5,
        fields="embedding"
    )]
)

# Hybrid search (vector + keyword)
results = search_client.search(
    search_text="query",
    vector_queries=[VectorizedQuery(vector=embedding, k_nearest_neighbors=5, fields="embedding")],
    query_type="semantic",
    semantic_configuration_name="semantic-config"
)

# With filters
results = search_client.search(
    search_text="query",
    filter="category eq 'technology'",
    select=["id", "title", "content"],
    top=10
)
```

## Agentic Retrieval (Knowledge Bases)

For LLM-powered Q&A with answer synthesis, see [references/agentic-retrieval.md](references/agentic-retrieval.md).

Key concepts:
- **Knowledge Source**: Points to a search index
- **Knowledge Base**: Wraps knowledge sources + LLM for query planning and synthesis
- **Output modes**: `EXTRACTIVE_DATA` (raw chunks) or `ANSWER_SYNTHESIS` (LLM-generated answers)

## Async Pattern

```python
from azure.search.documents.aio import SearchClient

async with SearchClient(endpoint, index_name, credential) as client:
    results = await client.search(search_text="query")
    async for result in results:
        print(result["title"])
```

## Best Practices

1. **Use environment variables** for endpoints, keys, and deployment names
2. **Use `DefaultAzureCredential`** for code that runs locally (instead of API keys). Use a specific token credential for code that runs in Azure.
3. **Use `SearchIndexingBufferedSender`** for batch uploads (handles batching/retries)
4. **Always define semantic configuration** for agentic retrieval indexes
5. **Use `create_or_update_index`** for idempotent index creation
6. **Close clients** with context managers or explicit `close()`

## Field Types Reference

| EDM Type | Python | Notes |
|----------|--------|-------|
| `Edm.String` | str | Searchable text |
| `Edm.Int32` | int | Integer |
| `Edm.Int64` | int | Long integer |
| `Edm.Double` | float | Floating point |
| `Edm.Boolean` | bool | True/False |
| `Edm.DateTimeOffset` | datetime | ISO 8601 |
| `Collection(Edm.Single)` | List[float] | Vector embeddings |
| `Collection(Edm.String)` | List[str] | String arrays |

## Error Handling

```python
from azure.core.exceptions import (
    HttpResponseError,
    ResourceNotFoundError,
    ResourceExistsError
)

try:
    result = search_client.get_document(key="123")
except ResourceNotFoundError:
    print("Document not found")
except HttpResponseError as e:
    print(f"Search error: {e.message}")
```

Todos los archivos

0 archivos

Instalar azure-search-documents-py

Descarga y descomprime los archivos de habilidades en tu directorio .claude/skills/.

Descargar ZIP

Clona el repositorio y copia los archivos de la habilidad a tu proyecto.

git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-python/skills/azure-search-documents-py # Copy SKILL.md to your .claude/skills/ directory

Copiar Copiar
Configuración rápida: Copia la carpeta de la habilidad en .claude/skills/ Claude detectará y utilizará automáticamente la habilidad
Repositorio microsoft/skills

Habilidades relacionadas

microservices-patterns
Tiempo actualizado 29 de junio de 2026
jpa-patterns
Tiempo actualizado 30 de junio de 2026
fabric-lakehouse
Tiempo actualizado 30 de junio de 2026
prisma-expert
Tiempo actualizado 29 de junio de 2026
OR