Skip to main content

Microsoft Azure Cognitive Search Client Library for Python

Project description

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.

Related projects

Impressions

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

azure-search-1.0.0b1.zip (89.9 kB view details)

Uploaded Source

Built Distribution

azure_search-1.0.0b1-py2.py3-none-any.whl (49.8 kB view details)

Uploaded Python 2 Python 3

File details

Details for the file azure-search-1.0.0b1.zip.

File metadata

  • Download URL: azure-search-1.0.0b1.zip
  • Upload date:
  • Size: 89.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.43.0 CPython/3.8.2

File hashes

Hashes for azure-search-1.0.0b1.zip
Algorithm Hash digest
SHA256 24f447b6814f0052440cbcf35ca5d97f8a78d5c738bda21080a695b7703b4ff8
MD5 4a6b256d166d9c0d95399c51cdbb5328
BLAKE2b-256 1948c6547fd8963eee305ce8954eeaa91a3e2f8ad812a088617533605fc2d480

See more details on using hashes here.

File details

Details for the file azure_search-1.0.0b1-py2.py3-none-any.whl.

File metadata

  • Download URL: azure_search-1.0.0b1-py2.py3-none-any.whl
  • Upload date:
  • Size: 49.8 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.43.0 CPython/3.8.2

File hashes

Hashes for azure_search-1.0.0b1-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 d8d0b11e4c4d84837b9fa8c9db3576198aa816734f30f2c7b574c3026a8967e0
MD5 da7a2f3ed8b20826d186033d304f50e8
BLAKE2b-256 5f05c7843573e3596e25c28e871fc1f35b95ab464f23f7a57dc44d9a49db6dac

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page