Azure AI Search Client Library for Python

11.6.0 · active · verified Thu Apr 09

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.

Warnings

Install

Imports

Quickstart

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

view raw JSON →