The Azure AI Search client library for Python allows developers to build rich search experiences and generative AI apps that combine large language models with enterprise data.
Install the Azure AI Search client library for Python using pip:
pip install azure-search-documents
To interact with the search service, you'll need to create an instance of the appropriate client class: SearchClient
for searching indexed documents, SearchIndexClient
for managing indexes, or SearchIndexerClient
for crawling data sources and loading search documents into an index. To instantiate a client object, you'll need an endpoint and Azure roles or an API key.
To create a SearchClient
instance, you'll need the endpoint, API key, and index name. You can use the following code:
from azure.core.credentials import AzureKeyCredential
from azure.search.documents import SearchClient
service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"]
index_name = os.environ["AZURE_SEARCH_INDEX_NAME"]
key = os.environ["AZURE_SEARCH_API_KEY"]
search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key))
In addition to querying for documents using keywords and optional filters, you can retrieve a specific document from your index if you already know the key. You can use the following code:
from azure.core.credentials import AzureKeyCredential
from azure.search.documents import SearchClient
search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key))
result = search_client.get_document(key="23")
You can upload, merge, merge or upload, and delete multiple documents from an index in a single batched request. You can use the following code:
from azure.core.credentials import AzureKeyCredential
from azure.search.documents import SearchClient
documents = [
{
"category": "Hotel",
"hotelId": "1000",
"rating": 4.0,
"rooms": [],
"hotelName": "Azure Inn",
}
]
result = search_client.upload_documents(documents=[document])
The Azure AI Search client library for Python includes several examples in the samples
directory. These examples demonstrate how to use the client library to search for documents, create indexes, add documents to indexes, and retrieve specific documents.
The Azure AI Search client will raise exceptions defined in Azure Core. You can troubleshoot issues by checking the error message and the status code returned by the API. You can also use the logging feature of the client library to log detailed information about the HTTP sessions.
To learn more about the Azure AI Search client library for Python and how to use it, please refer to the Azure AI Search documentation. You can also explore the azure-azure.ai-search-python-sample project on GitHub, which provides a sample implementation of the client library.
See CONTRIBUTING.md for details on building, testing, and contributing to this library.