azure.search.documents package

class azure.search.documents.IndexDocumentsBatch[source]

Represent a batch of upate operations for documents in an Azure Search index.

Index operations are performed in the order in which they are added to the batch.

add_delete_actions(*documents)[source]

Add documents to delete to the Azure search index.

Delete removes the specified document from the index. Any field you specify in a delete operation, other than the key field, will be ignored. If you want to remove an individual field from a document, use merge_documents instead and set the field explicitly to None.

Delete operations are idempotent. That is, even if a document key does not exist in the index, attempting a delete operation with that key will result in a 200 status code.

Parameters

documents (dict or list[dict]) – Documents to delete from an Azure search index. May be a single list of documents, or documents as individual parameters.

add_merge_actions(*documents)[source]

Add documents to merge in to existing documets in the Azure search index.

Merge updates an existing document with the specified fields. If the document doesn’t exist, the merge will fail. Any field you specify in a merge will replace the existing field in the document. This also applies to collections of primitive and complex types.

Parameters

documents (dict or list[dict]) – Documents to merge into an Azure search index. May be a single list of documents, or documents as individual parameters.

add_merge_or_upload_actions(*documents)[source]

Add documents to merge in to existing documets in the Azure search index, or upload if they do not yet exist.

This action behaves like merge if a document with the given key already exists in the index. If the document does not exist, it behaves like upload with a new document.

Parameters

documents (dict or list[dict]) – Documents to merge or uplaod into an Azure search index. May be a single list of documents, or documents as individual parameters.

add_upload_actions(*documents)[source]

Add documents to upload to the Azure search index.

An upload action is similar to an “upsert” where the document will be inserted if it is new and updated/replaced if it exists. All fields are replaced in the update case.

Parameters

documents (dict or list[dict]) – Documents to upload to an Azure search index. May be a single list of documents, or documents as individual parameters.

property actions

The list of currently configured index actions.

Return type

List[IndexAction]

class azure.search.documents.SearchClient(endpoint: str, index_name: str, credential: AzureKeyCredential, **kwargs: Any)[source]

A client to interact with an existing Azure search index.

Parameters
  • endpoint (str) – The URL endpoint of an Azure search service

  • index_name (str) – The name of the index to connect to

  • credential (AzureKeyCredential) – A credential to authorize search client requests

Example:

Creating the SearchClient with an API key.
from azure.core.credentials import AzureKeyCredential
from azure.search.documents import SearchClient

service_endpoint = os.getenv("AZURE_SEARCH_SERVICE_ENDPOINT")
index_name = os.getenv("AZURE_SEARCH_INDEX_NAME")
key = os.getenv("AZURE_SEARCH_API_KEY")

search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key))
autocomplete(**kwargs: Any) → List[dict][source]

Get search auto-completion results from the Azure search index.

Parameters
  • search_text (str) – The search text on which to base autocomplete results.

  • suggester_name (str) – The name of the suggester as specified in the suggesters

collection that’s part of the index definition. :rtype: List[dict]

Example:

Get a auto-completions.
from azure.core.credentials import AzureKeyCredential
from azure.search.documents import SearchClient

search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key))

results = search_client.autocomplete(search_text="bo", suggester_name="sg")

print("Autocomplete suggestions for 'bo'")
for result in results:
    print("    Completion: {}".format(result["text"]))
close()None[source]

Close the SearchClient session.

delete_documents(documents: List[dict], **kwargs: Any) → List[IndexingResult][source]

Delete documents from the Azure search index

Delete removes the specified document from the index. Any field you specify in a delete operation, other than the key field, will be ignored. If you want to remove an individual field from a document, use merge_documents instead and set the field explicitly to None.

Delete operations are idempotent. That is, even if a document key does not exist in the index, attempting a delete operation with that key will result in a 200 status code.

Parameters

documents (List[dict]) – A list of documents to delete.

Return type

List[IndexingResult]

Example:

Delete existing documents to an index
result = search_client.upload_documents(documents=[{"HotelId": "1000"}])

print("Delete new document succeeded: {}".format(result[0].succeeded))
get_document(**kwargs: Any)dict[source]

Retrieve a document from the Azure search index by its key.

Parameters
  • key (str) – The primary key value for the document to retrieve

  • selected_fields (List[str]) – a whitelist of fields to include in the results

Return type

dict

Example:

Get a specific document from the search index.
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")

print("Details for hotel '23' are:")
print("        Name: {}".format(result["HotelName"]))
print("      Rating: {}".format(result["Rating"]))
print("    Category: {}".format(result["Category"]))
get_document_count(**kwargs: Any)int[source]

Return the number of documents in the Azure search index.

Return type

int

index_documents(**kwargs: Any) → List[IndexingResult][source]

Specify a document operations to perform as a batch.

Parameters

batch (IndexDocumentsBatch) – A batch of document operations to perform.

Return type

List[IndexingResult]

merge_documents(documents: List[dict], **kwargs: Any) → List[IndexingResult][source]

Merge documents in to existing documents in the Azure search index.

Merge updates an existing document with the specified fields. If the document doesn’t exist, the merge will fail. Any field you specify in a merge will replace the existing field in the document. This also applies to collections of primitive and complex types.

Parameters

documents (List[dict]) – A list of documents to merge.

Return type

List[IndexingResult]

Example:

Merge fields into existing documents to an index
result = search_client.upload_documents(documents=[{"HotelId": "1000", "Rating": 4.5}])

print("Merge into new document succeeded: {}".format(result[0].succeeded))
merge_or_upload_documents(documents: List[dict], **kwargs: Any) → List[IndexingResult][source]

Merge documents in to existing documents in the Azure search index, or upload them if they do not yet exist.

This action behaves like merge_documents if a document with the given key already exists in the index. If the document does not exist, it behaves like upload_documents with a new document.

Parameters

documents (List[dict]) – A list of documents to merge or upload.

Return type

List[IndexingResult]

search(**kwargs: Any) → SearchItemPaged[dict][source]

Search the Azure search index for documents.

Parameters

search_text (str) – A full-text search query expression; Use “*” or omit this parameter to

match all documents. :rtype: SearchItemPaged[dict]

Example:

Search on a simple text term.
from azure.core.credentials import AzureKeyCredential
from azure.search.documents import SearchClient

search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key))

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

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

Example:

Filter and sort search results.
from azure.core.credentials import AzureKeyCredential
from azure.search.documents import SearchClient

search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key))

select = ("HotelName", "Rating")
results = search_client.search(
    search_text="WiFi",
    filter="Address/StateProvince eq 'FL' and Address/Country eq 'USA'",
    select=",".join(select),
    order_by="Rating desc"
)

print("Florida hotels containing 'WiFi', sorted by Rating:")
for result in results:
    print("    Name: {} (rating {})".format(result["HotelName"], result["Rating"]))

Example:

Get search result facets.
from azure.core.credentials import AzureKeyCredential
from azure.search.documents import SearchClient

search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key))

results = search_client.search(search_text="WiFi", facets=["Category"], top=0)

facets = results.get_facets()

print("Catgory facet counts for hotels:")
for facet in facets["Category"]:
    print("    {}".format(facet))
suggest(**kwargs: Any) → List[dict][source]

Get search suggestion results from the Azure search index.

Parameters

search_text (str) – Required. The search text to use to suggest documents. Must be at least 1

character, and no more than 100 characters. :param str suggester_name: Required. The name of the suggester as specified in the suggesters collection that’s part of the index definition. :rtype: List[dict]

Example:

Get search suggestions.
from azure.core.credentials import AzureKeyCredential
from azure.search.documents import SearchClient

search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key))

results = search_client.suggest(search_text="coffee", suggester_name="sg")

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(documents: List[dict], **kwargs: Any) → List[IndexingResult][source]

Upload documents to the Azure search index.

An upload action is similar to an “upsert” where the document will be inserted if it is new and updated/replaced if it exists. All fields are replaced in the update case.

Parameters

documents (List[dict]) – A list of documents to upload.

Return type

List[IndexingResult]

Example:

Upload new documents to an index
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))
class azure.search.documents.SearchItemPaged(*args, **kwds)[source]

Return an iterator of items.

args and kwargs will be passed to the PageIterator constructor directly, except page_iterator_class

by_page(continuation_token: Optional[str] = None) → Iterator[Iterator[ReturnType]]

Get an iterator of pages of objects, instead of an iterator of objects.

Parameters

continuation_token (str) – An opaque continuation token. This value can be retrieved from the continuation_token field of a previous generator object. If specified, this generator will begin returning results from this point.

Returns

An iterator of pages (themselves iterator of objects)

get_count()float[source]

Return the count of results if include_total_result_count was set for the query.

get_coverage()float[source]

Return the covereage percentage, if minimum_coverage was specificied for the query.

get_facets() → Union[dict, None][source]

Return any facet results if faceting was requested.

next()

Return the next item from the iterator. When exhausted, raise StopIteration

Submodules

azure.search.documents.aio module

class azure.search.documents.aio.AsyncSearchItemPaged(*args, **kwds)[source]

Return an async iterator of items.

args and kwargs will be passed to the AsyncPageIterator constructor directly, except page_iterator_class

by_page(continuation_token: Optional[str] = None) → AsyncIterator[AsyncIterator[ReturnType]]

Get an async iterator of pages of objects, instead of an async iterator of objects.

Parameters

continuation_token (str) – An opaque continuation token. This value can be retrieved from the continuation_token field of a previous generator object. If specified, this generator will begin returning results from this point.

Returns

An async iterator of pages (themselves async iterator of objects)

async get_count()float[source]

Return the count of results if include_total_result_count was set for the query.

async get_coverage()float[source]

Return the covereage percentage, if minimum_coverage was specificied for the query.

async get_facets() → Optional[dict][source]

Return any facet results if faceting was requested.

class azure.search.documents.aio.SearchClient(endpoint: str, index_name: str, credential: AzureKeyCredential, **kwargs: Any)[source]

A client to interact with an existing Azure search index.

Parameters
  • endpoint (str) – The URL endpoint of an Azure search service

  • index_name (str) – The name of the index to connect to

  • credential (AzureKeyCredential) – A credential to authorize search client requests

Example:

Creating the SearchClient with an API key.
from azure.core.credentials import AzureKeyCredential
from azure.search.documents.aio import SearchClient
service_endpoint = os.getenv("AZURE_SEARCH_SERVICE_ENDPOINT")
index_name = os.getenv("AZURE_SEARCH_INDEX_NAME")
key = os.getenv("AZURE_SEARCH_API_KEY")

search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key))
async autocomplete(**kwargs: Any) → List[dict][source]

Get search auto-completion results from the Azure search index.

Parameters
  • search_text (str) – The search text on which to base autocomplete results.

  • suggester_name (str) – The name of the suggester as specified in the suggesters

collection that’s part of the index definition. :rtype: List[dict]

Example:

Get a auto-completions.
from azure.core.credentials import AzureKeyCredential
from azure.search.documents.aio import SearchClient

search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key))

async with search_client:
    results = await search_client.autocomplete(search_text="bo", suggester_name="sg")

    print("Autocomplete suggestions for 'bo'")
    for result in results:
        print("    Completion: {}".format(result["text"]))
async close()None[source]

Close the SearchClient session.

async delete_documents(documents: List[dict], **kwargs: Any) → List[IndexingResult][source]

Delete documents from the Azure search index

Delete removes the specified document from the index. Any field you specify in a delete operation, other than the key field, will be ignored. If you want to remove an individual field from a document, use merge_documents instead and set the field explicitly to None.

Delete operations are idempotent. That is, even if a document key does not exist in the index, attempting a delete operation with that key will result in a 200 status code.

Parameters

documents (List[dict]) – A list of documents to delete.

Return type

List[IndexingResult]

Example:

Delete existing documents to an index
result = await search_client.upload_documents(documents=[{"HotelId": "1000"}])

print("Delete new document succeeded: {}".format(result[0].succeeded))
async get_document(**kwargs: Any)dict[source]

Retrieve a document from the Azure search index by its key.

Parameters
  • key (str) – The primary key value for the document to retrieve

  • selected_fields (List[str]) – a whitelist of fields to include in the results

Return type

dict

Example:

Get a specific document from the search index.
from azure.core.credentials import AzureKeyCredential
from azure.search.documents.aio import SearchClient

search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key))

async with search_client:
    result = await 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"]))
async get_document_count(**kwargs: Any)int[source]

Return the number of documents in the Azure search index.

Return type

int

async index_documents(**kwargs: Any) → List[IndexingResult][source]

Specify a document operations to perform as a batch.

Parameters

batch (IndexDocumentsBatch) – A batch of document operations to perform.

Return type

List[IndexingResult]

async merge_documents(documents: List[dict], **kwargs: Any) → List[IndexingResult][source]

Merge documents in to existing documents in the Azure search index.

Merge updates an existing document with the specified fields. If the document doesn’t exist, the merge will fail. Any field you specify in a merge will replace the existing field in the document. This also applies to collections of primitive and complex types.

Parameters

documents (List[dict]) – A list of documents to merge.

Return type

List[IndexingResult]

Example:

Merge fields into existing documents to an index
result = await search_client.upload_documents(documents=[{"HotelId": "1000", "Rating": 4.5}])

print("Merge into new document succeeded: {}".format(result[0].succeeded))
async merge_or_upload_documents(documents: List[dict], **kwargs: Any) → List[IndexingResult][source]

Merge documents in to existing documents in the Azure search index, or upload them if they do not yet exist.

This action behaves like merge_documents if a document with the given key already exists in the index. If the document does not exist, it behaves like upload_documents with a new document.

Parameters

documents (List[dict]) – A list of documents to merge or upload.

Return type

List[IndexingResult]

async search(**kwargs: Any) → AsyncSearchItemPaged[dict][source]

Search the Azure search index for documents.

Parameters

search_text (str) – A full-text search query expression; Use “*” or omit this parameter to

match all documents. :rtype: AsyncSearchItemPaged[dict]

Example:

Search on a simple text term.
from azure.core.credentials import AzureKeyCredential
from azure.search.documents.aio import SearchClient

search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key))

async with search_client:
    results = await search_client.search(search_text="spa")

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

Example:

Filter and sort search results.
from azure.core.credentials import AzureKeyCredential
from azure.search.documents.aio import SearchClient

search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key))

select = ("HotelName", "Rating")
async with search_client:
    results = await search_client.search(
        search_text="WiFi",
        filter="Address/StateProvince eq 'FL' and Address/Country eq 'USA'",
        select=",".join(select),
        order_by="Rating desc"
    )

    print("Florida hotels containing 'WiFi', sorted by Rating:")
    async for result in results:
        print("    Name: {} (rating {})".format(result["HotelName"], result["Rating"]))

Example:

Get search result facets.
from azure.core.credentials import AzureKeyCredential
from azure.search.documents.aio import SearchClient

search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key))

async with search_client:
    results = await search_client.search(search_text="WiFi", facets=["Category"], top=0)

    facets = await results.get_facets()

    print("Catgory facet counts for hotels:")
    for facet in facets["Category"]:
        print("    {}".format(facet))
async suggest(**kwargs: Any) → List[dict][source]

Get search suggestion results from the Azure search index.

Parameters

search_text (str) – Required. The search text to use to suggest documents. Must be at least 1

character, and no more than 100 characters. :param str suggester_name: Required. The name of the suggester as specified in the suggesters collection that’s part of the index definition. :rtype: List[dict]

Example:

Get search suggestions.
from azure.core.credentials import AzureKeyCredential
from azure.search.documents.aio import SearchClient

search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key))

async with search_client:
    results = await search_client.suggest(search_text="coffee", suggester_name="sg")

    print("Search suggestions for 'coffee'")
    for result in results:
        hotel = await search_client.get_document(key=result["HotelId"])
        print("    Text: {} for Hotel: {}".format(repr(result["text"]), hotel["HotelName"]))
async upload_documents(documents: List[dict], **kwargs: Any) → List[IndexingResult][source]

Upload documents to the Azure search index.

An upload action is similar to an “upsert” where the document will be inserted if it is new and updated/replaced if it exists. All fields are replaced in the update case.

Parameters

documents (List[dict]) – A list of documents to upload.

Return type

List[IndexingResult]

Example:

Upload new documents to an index
DOCUMENT = {
    'Category': 'Hotel',
    'HotelId': '1000',
    'Rating': 4.0,
    'Rooms': [],
    'HotelName': 'Azure Inn',
}

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

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