azure-search-documents-py
microsoft/skills
Python SDK를 사용하여 AI 강화 기능이 적용된 전체 텍스트, 벡터, 하이브리드 및 시맨틱 검색을 위해 Azure AI Search 인덱스를 검색하세요.
...모든 것을 확장하십시오Python용 Azure AI Search 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 키 인증 경로에서만 필요
인증 및 수명 주기
🔑 아래의 모든 코드 예제에는 다음 두 가지 규칙이 적용됩니다:
DefaultAzureCredential을우선적으로 사용하십시오. 코드 변경 없이 로컬(Azure CLI / VS Code / Developer CLI)과 Azure(관리형 ID, 워크로드 ID)에서 모두 작동합니다. 연결 문자열, 계정/API 키는 사용하지 마십시오. 이러한 항목은 Entra 감사 및 키 순환 기능을 우회합니다.
- 로컬 개발:
DefaultAzureCredential은별다른 설정 없이 바로 작동합니다.- 프로덕션:
AZURE_TOKEN_CREDENTIALS=prod(또는AZURE_TOKEN_CREDENTIALS=)를 설정하여 자격 증명 체인을 프로덕션에 안전한 자격 증명으로 제한하십시오.- 모든 클라이언트를 컨텍스트 매니저로 감싸서 HTTP 전송, 소켓 및 토큰 캐시가 결정론적으로 해제되도록 하십시오:
- 동기식:
(...) as client: - 비동기:
및(...)을 클라이언트로 사용하는 async DefaultAzureCredential()을 자격 증명으로 사용하는 async:(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을 사용해야 합니다. AzureKeyCredential은 아직 Entra ID로 마이그레이션되지 않은 기존 키 기반 배포 환경(예: Entra 도입이 아직 완료되지 않은 규제 대상 환경)에서만 사용하십시오. 동일한 AzureKeyCredential은 관리자 작업을 위한 SearchIndexClient 및 SearchIndexerClient에서도 작동합니다.
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))
클라이언트 유형
| 클라이언트 | 용도 |
|---|---|
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("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']}")
하이브리드 검색 (벡터 + 키워드)
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:
# 관리형 ID 사용(검색 서비스는 스토리지 계정에 대한 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)
모범 사례
- 동기(sync) 또는 비동기(async) 중 하나를 선택하고 일관성을 유지하세요. 동일한 호출 경로에서
azure.xxx동기 클라이언트와azure.xxx.aio비동기 클라이언트를 혼합하여 사용하지 마세요. 모듈당 하나의 모드를 선택하세요. - 클라이언트 및 비동기 자격 증명에는 항상 컨텍스트 관리자를 사용하십시오. 모든 클라이언트를
Client(...) as client:(동기) 또는Client(...) as client: (비동기)로감싸십시오. 비동기 모드의 경우azure.identity.aio의DefaultAzureCredential을사용할 때,credential:을 사용하여 비동기 모드를적용해야 토큰과 전송 정보가 적절히 정리됩니다. - 벡터와 키워드를 결합하여 최적의 관련성을 얻으려면하이브리드 검색을 사용하십시오.
- 자연어 쿼리에 대해시맨틱 랭킹을 활성화하십시오.
- 효율성을 위해 100~1,000개의 문서로 묶어배치 단위로 색인을 생성하십시오.
- 순위 지정 전에필터를 사용하여 결과를 좁히십시오
- 임베딩 모델에 맞게벡터 차원을 구성하십시오.
- 대규모 벡터 검색에는HNSW 알고리즘을 사용하십시오
- 색인 생성 시점에제안 기능을 생성하십시오 (나중에 추가할 수 없음)
참조 파일
| 파일 | 내용 |
|---|---|
| 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 |
인덱스 쿼리, 문서 업로드/업데이트/삭제 |
검색 인덱스 클라이언트 |
인덱스, 지식 소스, 지식베이스 생성 및 관리 |
SearchIndexerClient |
인덱서, 스킬셋, 데이터 소스 관리 |
KnowledgeBaseRetrievalClient |
LLM 기반 Q&A를 활용한 에이전트형 검색 |
인덱스 생성 패턴
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")]
)
)]
)
)
SearchIndexClient(endpoint, credential)를 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 기반 Q&A에 대해서는 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"])
모범 사례
- 엔드포인트, 키 및 배포 이름에는환경 변수를 사용하세요
- 로컬에서 실행되는 코드의 경우
DefaultAzureCredential을사용하십시오 (API 키 대신). Azure에서 실행되는 코드의 경우 특정 토큰 자격 증명을 사용하십시오. - 일괄 업로드 시
SearchIndexingBufferedSender를사용하십시오 (일괄 처리 및 재시도 처리). - 에이전트 기반 검색 인덱스의 경우항상 시맨틱 구성을 정의하십시오
- 이멱포텐트 인덱스 생성을 위해
create_or_update_index를사용하십시오 - 컨텍스트 관리자 또는 명시적인
close()를 사용하여클라이언트를 닫으십시오
필드 유형 참조
| EDM 유형 | Python | 참고 사항 |
|---|---|---|
Edm.String |
str | 검색 가능한 텍스트 |
Edm.Int32 |
int | 정수 |
Edm.Int64 |
int | 긴 정수 |
Edm.Double |
float | 부동 소수점 |
Edm.Boolean |
bool | 참/거짓 |
Edm.DateTimeOffset |
datetime | 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}")
---
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
복사





집
