Azure Cognitive Search client library for Python

Azure Cognitive Search is a fully managed cloud search service that provides a rich search experience to custom applications.

Source code | Package (PyPI) | API reference documentation | Product documentation | Samples

Getting started

Prerequisites

If you need to create the resource, you can use the Azure Portal or Azure CLI.

If you use the Azure CLI, replace <your-resource-group-name> and <your-resource-name> with your own unique names:

az search service create --resource-group <your-resource-group-name> --name <your-resource-name> --sku S

The above creates a resource with the “Standard” pricing tier. See choosing a pricing tier for more information.

Install the package

Install the Azure Cognitive Search client library for Python with pip:

pip install azure-search --pre

Create an Azure Cognitive Search service

Using an API Key

You can get the Query Keys or Admin Key from the resource information in the Azure Portal.

Alternatively, youcan se the Azure CLI snippet below to get the Admin Key from the Cognitive Search resource.

az search admin-key show --resource-group <your-resource-group-name> --service-name <your-resource-name>

Authenticate the client

Interaction with this service begins with an instance of a client. To create a client object, you will need the endpoint for your search service and a credential that allows you access:

from azure.search import SearchApiKeyCredential, SearchIndexClient

credential = SearchApiKeyCredential("<api key>")

client = SearchIndexClient(endpoint="<service endpoint>",
                           index_name="<index name>",
                           credential=credential)

Key concepts

Client

The Cognitive Search client library provides a SearchIndexClient to perform search operations on batches of documents. It provides both synchronous and asynchronous operations to access a specific use of Cognitive Search indexes, such as querying, suggestions or autocompletion.

Examples

Retrieve a specific document from an index

Get a specific document from the index, e.f. obtain the document for hotel “23”:

from azure.search import SearchApiKeyCredential, SearchIndexClient
search_client = SearchIndexClient(service_endpoint, index_name, SearchApiKeyCredential(key))

result = search_client.get_document(key="23")

print("Details for hotel '23' are:")
print("        Name: {}".format(result["HotelName"]))
print("      Rating: {}".format(result["Rating"]))
print("    Category: {}".format(result["Category"]))

Perform a simple text search on documents

Search the entire index or documents matching a simple search text, e.g. find hotels with the text “spa”:

from azure.search import SearchApiKeyCredential, SearchIndexClient
search_client = SearchIndexClient(service_endpoint, index_name, SearchApiKeyCredential(key))

results = search_client.search(query="spa")

print("Hotels containing 'spa' in the name (or other fields):")
for result in results:
    print("    Name: {} (rating {})".format(result["HotelName"], result["Rating"]))

Get search suggestions

Get search suggestions for related terms, e.g. find search suggestions for the term “coffee”:

from azure.search import SearchApiKeyCredential, SearchIndexClient, SuggestQuery
search_client = SearchIndexClient(service_endpoint, index_name, SearchApiKeyCredential(key))

query = SuggestQuery(search_text="coffee", suggester_name="sg")

results = search_client.suggest(query=query)

print("Search suggestions for 'coffee'")
for result in results:
    hotel = search_client.get_document(key=result["HotelId"])
    print("    Text: {} for Hotel: {}".format(repr(result["text"]), hotel["HotelName"]))

Upload documents to an index

Add documents (or update existing ones), e.g add a new document for a new hotel:

from azure.search import SearchApiKeyCredential, SearchIndexClient
search_client = SearchIndexClient(service_endpoint, index_name, SearchApiKeyCredential(key))

DOCUMENT = {
    'Category': 'Hotel',
    'HotelId': '1000',
    'Rating': 4.0,
    'Rooms': [],
    'HotelName': 'Azure Inn',
}

result = search_client.upload_documents(documents=[DOCUMENT])

print("Upload of new document succeeded: {}".format(result[0].succeeded))

Troubleshooting

General

The Azure Cognitive Search client will raise exceptions defined in Azure Core.

Logging

This library uses the standard logging library for logging. Basic information about HTTP sessions (URLs, headers, etc.) is logged at INFO level.

etailed DEBUG level logging, including request/response bodies and unredacted headers, can be enabled on a client with the logging_enable keyword argument:

import sys
import logging
from azure.search import SearchApiKeyCredential, SearchIndexClient

# Create a logger for the 'azure' SDK
logger = logging.getLogger('azure')
logger.setLevel(logging.DEBUG)

# Configure a console output
handler = logging.StreamHandler(stream=sys.stdout)
logger.addHandler(handler)

# This client will log detailed information about its HTTP sessions, at DEBUG level
search_client = SearchIndexClient(service_endpoint, index_name, SearchApiKeyCredential(key), logging_enable=True)

Similarly, logging_enable can enable detailed logging for a single operation, even when it isn’t enabled for the client:

result =  search_client.search(query="spa", logging_enable=True)

Next steps

More sample code

Authenticate the client with a Azure Cognitive Search API Key Credential:

sample_authentication.py (async version)

Then for common search index operations:

Additional documentation

For more extensive documentation on Cognitive Search, see the Azure Cognitive Search documentation on docs.microsoft.com.

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit cla.microsoft.com.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.