Registry / azure / azure-search-documents

azure-search-documents

JSON →
library12.0.0pypypi✓ verified 25d ago

The `azure-search-documents` library is the Microsoft Azure AI Search client library for Python. Azure AI Search (formerly known as "Azure Cognitive Search") is an AI-powered information retrieval platform that enables developers to build rich search experiences and generative AI applications that combine large language models with enterprise data. The current stable version is 11.6.0, and the library follows a regular release cadence as part of the Azure SDK for Python.

pip install azure-search-documents
INSTALL
IMPORT
SIG · AZURE-SEARCH-DOCUM
A
azure-search-documents
azurepythonv12.0.0
Install
2.6s avg
Import
550ms
Disk
26MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v12.0.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.572s · 27.2MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 2.6s · import 0.528s · 28MB
26MB installed
● package 26MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

SearchClient
from azure.search.documents import SearchClient
SearchIndexClient
from azure.search.documents.indexes import SearchIndexClient
SearchIndexerClient
from azure.search.documents.indexers import SearchIndexerClient
AzureKeyCredential
from azure.core.credentials import AzureKeyCredential
DefaultAzureCredential
from azure.identity import DefaultAzureCredential
Required for Azure Active Directory (AAD) authentication.

This quickstart demonstrates how to instantiate a `SearchClient` using an API key and perform a basic search query and retrieve a document. Ensure `AZURE_SEARCH_SERVICE_ENDPOINT`, `AZURE_SEARCH_INDEX_NAME`, and `AZURE_SEARCH_API_KEY` environment variables are set. Replace 'hotelName', 'id', and 'rating' with actual field names from your index schema.

import os from azure.core.credentials import AzureKeyCredential from azure.search.documents import SearchClient # Set environment variables for your Azure AI Search service endpoint, API key, and index name service_endpoint = os.environ.get("AZURE_SEARCH_SERVICE_ENDPOINT", "") index_name = os.environ.get("AZURE_SEARCH_INDEX_NAME", "") api_key = os.environ.get("AZURE_SEARCH_API_KEY", "") if not service_endpoint or not index_name or not api_key: raise ValueError("Please set AZURE_SEARCH_SERVICE_ENDPOINT, AZURE_SEARCH_INDEX_NAME, and AZURE_SEARCH_API_KEY environment variables.") # Create a SearchClient search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(api_key)) # Example: Search for documents results = search_client.search(search_text="office") print("Search Results:") for result in results: print(f"ID: {result['id']}, Name: {result['hotelName']}") # Adjust field names based on your index schema # Example: Get a single document by key document_key = "23" try: document = search_client.get_document(key=document_key) print(f"\nDetails for document '{document_key}':") print(f"Name: {document['hotelName']}") # Adjust field name based on your index schema print(f"Rating: {document['rating']}") # Adjust field name based on your index schema except Exception as e: print(f"\nError retrieving document '{document_key}': {e}")
Debug
Known issues
breakingVersion 11 (`azure-search-documents`) is a complete redesign of the client library from previous versions (e.g., `Microsoft.Azure.Search` v10). It introduces new client classes (`SearchClient`, `SearchIndexClient`, `SearchIndexerClient`) and significant API and naming differences, consolidating functionality from four packages into one.
fix
Rewrite code to use the new `azure-search-documents` client classes and API surface. Refer to migration guides for detailed changes.
affects: <11.0.0 to 11.x.x
breakingAzure AI Search API versions are updated regularly, and older preview versions (e.g., `2023-07-01-preview` for vector search) are deprecated and no longer supported. Migrating to newer API versions may require changes to vector search configurations and other features.
fix
Regularly check the Azure AI Search documentation for the latest recommended API versions and update your client library and code accordingly, especially for new features like vector search.
affects: API versions deprecated before current service versions
gotchaAlways use a query API key for client-side applications to restrict access and operations to read-only queries. Admin keys grant full read-write access to the search service and should be protected and only used for administrative tasks.
fix
When creating an `AzureKeyCredential`, ensure you are using a query key retrieved from the Azure portal for client applications. Admin keys should only be used in secure backend services for index management and document ingestion.
affects: All
gotchaModifying or removing an existing field in an Azure AI Search index's schema is not allowed directly. To change an index schema (e.g., changing field types, adding/removing fields, making a field filterable), you must create an entirely new index with the desired schema, re-populate it with all documents, and then update your application to point to the new index.
fix
Plan schema changes carefully. Use index aliases to manage seamless transitions between old and new indexes in production environments.
affects: All
gotchaFiltering in Azure AI Search is case-sensitive. A filter for `Make eq 'toyota'` will not match a document where `Make` is 'Toyota' or 'TOYOTA'.
fix
If case-insensitive filtering is required, consider storing a normalized (e.g., lowercase) version of the field in your index specifically for filtering, alongside the original field for display. Alternatively, use fuzzy search or other query types if exact filtering isn't strictly necessary.
affects: All
gotchaIn hybrid search, if you intend to apply a strict filter (e.g., using regular expressions in `search_text`), unexpected results might occur because vector search always returns a `k` number of matches, which are then combined. For hard filters where non-matching documents must be excluded, use the `filter` argument with OData syntax.
fix
Differentiate between `search_text` for relevance-based matching and the `filter` argument for strict, Boolean-logic filtering. Use `filter` for hard constraints.
affects: All (especially with hybrid search and `search_text` constraints)
breakingTo connect to Azure AI Search, the service endpoint, API key, and typically the index name must be provided. These are commonly configured via environment variables (e.g., `AZURE_SEARCH_SERVICE_ENDPOINT`, `AZURE_SEARCH_API_KEY`, `AZURE_SEARCH_INDEX_NAME`) or passed as arguments to client constructors. Failure to provide this essential connection information will prevent the client from initializing or connecting to the service.
fix
Ensure the necessary environment variables (`AZURE_SEARCH_SERVICE_ENDPOINT`, `AZURE_SEARCH_API_KEY`, `AZURE_SEARCH_INDEX_NAME`) are set in your execution environment, or pass these values directly as parameters when creating Azure AI Search client objects (e.g., `SearchClient`, `SearchIndexClient`, `SearchIndexerClient`).
affects: All
gotchaThe Azure AI Search client library requires essential configuration (service endpoint, index name, and API key) to be provided for successful initialization and operation. Failure to provide these credentials will result in client instantiation or connection errors.
fix
Ensure `AZURE_SEARCH_SERVICE_ENDPOINT`, `AZURE_SEARCH_INDEX_NAME`, and `AZURE_SEARCH_API_KEY` environment variables are correctly set, or pass these values directly when initializing client objects (e.g., `SearchClient`, `SearchIndexClient`).
affects: All
Errors
Common errors & fixes
AttributeError: 'SearchIndexClient' object has no attribute 'index_documents'
Developers often confuse `SearchIndexClient` (used for managing search indexes) with `SearchClient` (used for adding, updating, and deleting documents within an index). The `index_documents` method belongs to `SearchClient`.
fix
Ensure you are using an instance of `SearchClient` for document operations. You can obtain a `SearchClient` from a `SearchIndexClient` using `get_search_client()` or instantiate it directly.
```python
from azure.search.documents import SearchClient
from azure.core.credentials import AzureKeyCredential

service_endpoint = "YOUR_SEARCH_SERVICE_ENDPOINT"
index_name = "YOUR_INDEX_NAME"
key = "YOUR_ADMIN_API_KEY"

# Instantiate SearchClient directly for document operations
search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key))

documents = [
    {"id": "1", "text": "This is a sample document."}
]
result = search_client.upload_documents(documents=documents)
# or for more granular control, use index_documents
# from azure.search.documents.models import IndexAction, IndexActionType
# actions = [IndexAction(document=doc, action_type=IndexActionType.UPLOAD) for doc in documents]
# result = search_client.index_documents(actions=actions)
```
ModuleNotFoundError: No module named 'azure'
This error occurs because the top-level `azure` meta-package is deprecated, and you should install the specific service client library (e.g., `azure-search-documents`) directly. Installing `azure` typically results in this error or an outdated package.
fix
Install the specific client library directly using pip. If you see this error, it means the required `azure-search-documents` (or its dependencies like `azure-core`) is not correctly installed or recognized in your environment.
```bash
pip install azure-search-documents
# If you also need core components or other Azure SDKs, install them explicitly:
pip install azure-core azure-identity
```
HttpResponseError: Operation returned an invalid status 'Forbidden'
This error (HTTP 403) indicates that the credentials provided (API key or Azure AD identity) do not have sufficient permissions to perform the requested operation on the Azure AI Search service.
fix
Verify that your API key is correct and has the necessary permissions (admin key for index management/document write, query key for document read). If using Azure AD, ensure the Managed Identity or Service Principal has been assigned appropriate roles (e.g., 'Search Service Contributor' for index creation, 'Search Index Data Contributor' for document write, 'Search Index Data Reader' for document read) on the Azure AI Search service.
```python
from azure.core.credentials import AzureKeyCredential
from azure.search.documents.indexes import SearchIndexClient

service_endpoint = "https://<your-search-service-name>.search.windows.net"
admin_key = "YOUR_ADMIN_API_KEY_FROM_PORTAL" # Ensure this is an admin key for index creation

credential = AzureKeyCredential(admin_key)
index_client = SearchIndexClient(endpoint=service_endpoint, credential=credential)

# Example: Attempting to create an index requires appropriate permissions
# index_client.create_index(SearchIndex(...))
```
AttributeError: module 'azure.search.documents.indexes.models._edm' has no attribute 'Single'
This error typically occurs when an unsupported data type `SearchFieldDataType.Single` is used, often in integrations like LangChain. The `SearchFieldDataType` enum in `azure-search-documents` does not have a `Single` attribute; `Double` should be used for floating-point numbers.
fix
Replace `SearchFieldDataType.Single` with `SearchFieldDataType.Double` when defining fields in your search index schema.
```python
from azure.search.documents.indexes.models import SearchField, SearchFieldDataType

# Incorrect
# SearchField(name="price", type=SearchFieldDataType.Single)

# Correct
SearchField(name="price", type=SearchFieldDataType.Double, searchable=True, filterable=True)
```
KeyError: 'content' (when using Langchain's AzureCognitiveSearchRetriever)
When using Langchain's `AzureCognitiveSearchRetriever`, the `content_key` parameter is set to 'content' by default, but your Azure AI Search index might not have a field with this exact name. The retriever attempts to extract document content using this key, leading to a `KeyError` if it's not found.
fix
Specify the `content_key` parameter in the `AzureCognitiveSearchRetriever` constructor to match the actual name of the field in your Azure AI Search index that holds the main document content.
```python
import os
from langchain_community.retrievers import AzureCognitiveSearchRetriever

# Assume these are set as environment variables or directly defined
cognitive_search_name = os.environ.get("AZURE_COGNITIVE_SEARCH_SERVICE_NAME")
index_name = os.environ.get("AZURE_COGNITIVE_SEARCH_INDEX_NAME")
vector_store_address = f"https://{cognitive_search_name}.search.windows.net/"
vector_store_password = os.environ.get("AZURE_COGNITIVE_SEARCH_API_KEY")

# If your index field for content is 'text' instead of 'content'
retriever = AzureCognitiveSearchRetriever(
    service_name=cognitive_search_name,
    index_name=index_name,
    api_key=vector_store_password,
    content_key="text" # Change 'text' to whatever your actual content field name is
)

# Example usage:
# documents = retriever.invoke("your query")
```
Upgrade
Version history
12.0.0latest on PyPI · released May 1, 2026
Audit
Dependencies
azure-identityoptionalRequired for Azure Active Directory (AAD) authentication using credential types like DefaultAzureCredential.
Agent activity
45 hits · last 30 days
node
36
OpenAI (training)
1
Resources
azure-search-documents — pip install azure-search-documents · libregistry