選項
首頁首頁 Skill 資料庫管理 azure-search-documents-py

azure-search-documents-py

microsoft/skills microsoft/skills

使用 Python SDK 搜尋 Azure AI Search 索引,以進行具備 AI 增強功能的全文、向量、混合及語義搜尋。

...展開全部
2
更新時間 2026-09-14

Azure AI Search Python SDK

具備 AI 增強功能的全文、向量及混合搜尋。

安裝

pip install azure-search-documents

環境變數

AZURE_SEARCH_ENDPOINT=https://.search.windows.net  # 所有驗證方法皆需設定
AZURE_SEARCH_INDEX_NAME= # 所有驗證方法皆需設定
AZURE_TOKEN_CREDENTIALS=prod # 僅當在生產環境中使用 DefaultAzureCredential 時才需要
AZURE_SEARCH_API_KEY= # 僅適用於下方的舊版 API 金鑰驗證路徑

驗證與生命週期

🔑 以下每個程式碼範例均適用以下兩項規則:

  1. 優先使用DefaultAzureCredential它可在本地端(Azure CLI / VS Code / 開發人員 CLI)及 Azure 環境(託管身分識別、工作負載身分識別)中運作,且無需修改程式碼。請避免使用連線字串、帳戶/API 金鑰——這些會繞過 Entra 的稽核與輪替機制。
    • 本地開發:DefaultAzureCredential可直接使用。
    • 生產環境:請設定AZURE_TOKEN_CREDENTIALS=prod(或AZURE_TOKEN_CREDENTIALS= ),以將憑證鏈限制為符合生產環境安全標準的憑證。
  2. 將每個客戶端封裝在上下文管理器中,以確保 HTTP 傳輸、套接字和憑證快取能以確定性方式釋放:
    • 同步模式:使用 `(...) as client:`
    • 非同步:使用 `(...)` 作為 `client` 的非同步操作 ,以及 使用 `DefaultAzureCredential()` 作為憑證的非同步操作:(來自azure.identity.aio

程式碼片段可能會簡化此設定,但生產環境的程式碼應始終遵循這兩項規則。

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

# 本地開發環境:使用 DefaultAzureCredential。生產環境:請設定 AZURE_TOKEN_CREDENTIALS=prod 或 AZURE_TOKEN_CREDENTIALS=
credential = DefaultAzureCredential(require_envvar=True)
# 或者在生產環境中直接使用特定憑證:
# 請參閱 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))

舊版:API 金鑰(現有使用金鑰的部署)

新程式碼應使用上方的DefaultAzureCredential。 僅當您擁有尚未遷移至 Entra ID 的既有基於金鑰部署時,才應使用AzureKeyCredential— 例如,仍在完成 Entra 部署的受監管環境。同一組AzureKeyCredential亦可與SearchIndexClientSearchIndexerClient配合使用,以執行管理操作。

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 用途
SearchClient 搜尋與文件操作
SearchIndexClient 索引管理、同義詞映射
SearchIndexerClient 索引器、資料來源、技能集

建立帶有向量欄位的索引

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)

上傳文件

from azure.search.documents import SearchClient

documents = [
    {
        "id": "1",
        "title": "Azure AI Search",
        "content": "全文與向量搜尋服務",
        "content_vector": [0.1, 0.2, ...]  # 1536 維度
    }
]

with SearchClient(endpoint, "my-index", DefaultAzureCredential()) as client:
    result = client.upload_documents(documents)
    print(f"已上傳 {len(result)} 份文件")

關鍵字搜尋

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

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

向量搜尋

from azure.search.documents.models import VectorizedQuery

# 您的查詢嵌入向量(1536 維)
query_vector = get_embedding("語義搜尋功能")

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']}")

混合搜尋(向量 + 關鍵字)

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
)

語義排序

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"  說明文字:{result['@search.captions'][0].text}")

篩選條件

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

分面

results = client.search(
    search_text="*",
    facets=["category,count:10", "rating"],
    top=0  # 僅取得分面資料,不擷取文件
)

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']}")

自動完成與建議

# 自動完成
results = client.autocomplete(
    search_text="sea",
    suggester_name="my-suggester",
    mode="twoTerms"
)

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

具備技能集的索引器

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:
    # 使用託管身分識別(搜尋服務必須在儲存帳戶上擁有 RBAC 角色)。避免使用內嵌金鑰的儲存連線字串。
    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)

    # 建立技能集
    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)

    # 建立索引器
    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)

最佳實務

  1. 請選擇同步或非同步模式,並保持一致。請勿在同一個呼叫路徑中混合使用azure.xxx同步客戶端與azure.xxx.aio非同步客戶端。每個模組應選擇一種模式。
  2. 請務必為客戶端和非同步憑證使用上下文管理器。將每個客戶端以 Client(...) as client:(同步) 或Client(...) as client:(非同步) 進行封裝。 對於來自azure.identity.aio 的非同步DefaultAzureCredential,也請搭配 credential:採用非同步模式,以便妥善清理憑證及傳輸資料。
  3. 使用混合搜尋,結合向量與關鍵字以獲得最佳相關性
  4. 針對自然語言查詢啟用語義排序
  5. 為提高效率,請以100 至 1000 份文件為一批次進行索引
  6. 在排序前使用篩選器縮小結果範圍
  7. 設定向量維度以配合您的嵌入模型
  8. 針對大規模向量搜尋,採用 HNSW 演算法
  9. 請於建立索引時一併建立建議器(無法事後新增)

參考檔案

檔案 內容
references/vector-search.md HNSW 配置、整合式向量化、多向量查詢
references/semantic-ranking.md 語義配置、圖說、答案、混合模式
scripts/setup_vector_index.py 用於建立支援向量搜尋的索引的 CLI 腳本

其他 Azure AI Search 模式

Azure AI Search Python SDK

使用azure-search-documents 為 Azure AI Search 撰寫簡潔且符合 Python 慣例的程式碼。

安裝

pip install azure-search-documents azure-identity

環境變數

AZURE_SEARCH_ENDPOINT=https://.search.windows.net  # 所有驗證方法皆需此設定
AZURE_SEARCH_INDEX_NAME= # 所有驗證方法皆需此設定
AZURE_TOKEN_CREDENTIALS=prod # 僅當在生產環境中使用 DefaultAzureCredential 時才需要

驗證

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

# 本地開發環境:DefaultAzureCredential。生產環境:請設定 AZURE_TOKEN_CREDENTIALS=prod 或 AZURE_TOKEN_CREDENTIALS=
credential = DefaultAzureCredential(require_envvar=True)
# 或者在生產環境中直接使用特定憑證:
# 請參閱 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))

客戶端選擇

客戶端 用途
SearchClient 查詢索引、上傳/更新/刪除文件
SearchIndexClient 建立/管理索引、知識來源、知識庫
SearchIndexerClient 管理索引器、技能集、資料來源
KnowledgeBaseRetrievalClient 基於大型語言模型(LLM)的問答式代理檢索

索引建立模式

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",
            參數=AzureOpenAIVectorizerParameters(
                資源網址=aoai_endpoint,
                部署名稱=embedding_deployment,
                模型名稱=embedding_model
            )
        )]
    ),
    semantic_search=SemanticSearch(
        default_configuration_name="semantic-config",
        configurations=[SemanticConfiguration(
            name="semantic-config",
            優先字段=SemanticPrioritizedFields(
                內容字段=[SemanticField(字段名稱="content")]
            )
        )]
    )
)

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

文件操作

from azure.search.documents import SearchIndexingBufferedSender

# 批次上傳並自動分批處理
with SearchIndexingBufferedSender(endpoint, index_name, credential) as sender:
    sender.upload_documents(documents)

# 透過 SearchClient 進行直接操作
with SearchClient(endpoint, index_name, credential) as search_client:
    search_client.upload_documents(documents)      # 新增
    search_client.merge_documents(documents)       # 更新現有
    search_client.merge_or_upload_documents(documents)  # 更新或插入
    search_client.delete_documents(documents)      # 移除

搜尋模式

# 基本搜尋
results = search_client.search(search_text="query")

# 向量搜尋
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"
    )]
)

# 混合搜尋(向量 + 關鍵字)
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"
)

# 搭配篩選條件
results = search_client.search(
    search_text="query",
    filter="category eq 'technology'",
    select=["id", "title", "content"],
    top=10
)

代理式檢索(知識庫)

關於由大型語言模型(LLM)驅動且具備答案合成功能的問答系統,請參閱 references/agentic-retrieval.md。

關鍵概念:

  • 知識來源:指向搜尋索引
  • 知識庫:整合知識來源與 LLM,用於查詢規劃與答案合成
  • 輸出模式EXTRACTIVE_DATA(原始片段)或ANSWER_SYNTHESIS(由 LLM 生成的答案)

非同步模式

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"])

最佳實務

  1. 請使用環境變數設定端點、金鑰及部署名稱
  2. 對於在本地端執行的程式碼,請使用DefaultAzureCredential(而非 API 金鑰)。對於在 Azure 中執行的程式碼,請使用特定的憑證代碼。
  3. 批次上傳時請使用` SearchIndexingBufferedSender`(可處理批次處理與重試)
  4. 始終為代理檢索索引定義語義配置
  5. 使用` create_or_update_index` 進行幺正的索引建立
  6. 透過上下文管理器或明確呼叫close()來關閉客戶端

欄位類型參考

EDM 類型 Python 備註
Edm.String str 可搜尋文字
Edm.Int32 int 整數
Edm.Int64 int 長整數
Edm.Double float 浮點數
Edm.Boolean bool 真/假
Edm.DateTimeOffset 日期時間 ISO 8601
集合(Edm.Single) List[float] 向量嵌入
集合(Edm.String) List[str] 字串陣列

錯誤處理

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

try:
    result = search_client.get_document(key="123")
except ResourceNotFoundError:
    print("找不到文件")
except HttpResponseError as e:
    print(f"搜尋錯誤:{e.message}")
在 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}")
```

所有檔案

0 個檔案

安裝 azure-search-documents-py

請下載並將技能檔案解壓縮至您的 .claude/skills/ 目錄中。

下載 ZIP

複製儲存庫並將技能檔案複製到您的專案中。

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

複製 複製
快速設定: 將技能資料夾複製到 .claude/skills/ Claude 會自動偵測並使用該技能
儲存庫 microsoft/skills

相關技能

microservices-patterns
更新時間 2026-06-29
jpa-patterns
更新時間 2026-06-30
fabric-lakehouse
更新時間 2026-06-30
prisma-expert
更新時間 2026-06-29
OR