azure.search package

class azure.search.AutocompleteQuery(**kwargs)[source]

Parameters for fuzzy matching, and other autocomplete query behaviors.

All required parameters must be populated in order to send to Azure.

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

  • autocomplete_mode (str or AutocompleteMode) – Specifies the mode for Autocomplete. The default is ‘oneTerm’. Use ‘twoTerms’ to get shingles and ‘oneTermWithContext’ to use the current context while producing auto-completed terms. Possible values include: ‘oneTerm’, ‘twoTerms’, ‘oneTermWithContext’.

  • filter (str) – An OData expression that filters the documents used to produce completed terms for the Autocomplete result.

  • use_fuzzy_matching (bool) – A value indicating whether to use fuzzy matching for the autocomplete query. Default is false. When set to true, the query will autocomplete terms even if there’s a substituted or missing character in the search text. While this provides a better experience in some scenarios, it comes at a performance cost as fuzzy autocomplete queries are slower and consume more resources.

  • highlight_post_tag (str) – A string tag that is appended to hit highlights. Must be set with highlightPreTag. If omitted, hit highlighting is disabled.

  • highlight_pre_tag (str) – A string tag that is prepended to hit highlights. Must be set with highlightPostTag. If omitted, hit highlighting is disabled.

  • minimum_coverage (float) – A number between 0 and 100 indicating the percentage of the index that must be covered by an autocomplete query in order for the query to be reported as a success. This parameter can be useful for ensuring search availability even for services with only one replica. The default is 80.

  • search_fields (str) – The comma-separated list of field names to consider when querying for auto-completed terms. Target fields must be included in the specified suggester.

  • suggester_name (str) – Required. The name of the suggester as specified in the suggesters collection that’s part of the index definition.

  • top (int) – The number of auto-completed terms to retrieve. This must be a value between 1 and 100. The default is 5.

filter(expression)

Add a filter expression for the search results.

Parameters

expression (str) – An ODate expression of for the query filter.

property request

The service request for this operation.

class azure.search.IndexAction(*, additional_properties: Optional[Dict[str, object]] = None, action_type: Union[str, IndexActionType, None] = None, **kwargs)[source]

Represents an index action that operates on a document.

Parameters
  • additional_properties (dict[str, object]) – Unmatched properties from the message are deserialized to this collection.

  • action_type (str or IndexActionType) – The operation to perform on a document in an indexing batch. Possible values include: ‘upload’, ‘merge’, ‘mergeOrUpload’, ‘delete’.

as_dict(keep_readonly=True, key_transformer=<function attribute_transformer>, **kwargs)

Return a dict that can be JSONify using json.dump.

Advanced usage might optionaly use a callback as parameter:

Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains ‘type’ with the msrest type and ‘key’ with the RestAPI encoded key. Value is the current value in this object.

The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict.

See the three examples in this file:

  • attribute_transformer

  • full_restapi_key_transformer

  • last_restapi_key_transformer

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

key_transformer (function) – A key transformer function.

Returns

A dict JSON compatible object

Return type

dict

classmethod deserialize(data, content_type=None)

Parse a str using the RestAPI syntax and return a model.

Parameters
  • data (str) – A str using RestAPI structure. JSON by default.

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod enable_additional_properties_sending()
classmethod from_dict(data, key_extractors=None, content_type=None)

Parse a dict using given key extractor return a model.

By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor)

Parameters
  • data (dict) – A dict using RestAPI structure

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod is_xml_model()
serialize(keep_readonly=False, **kwargs)

Return the JSON that would be sent to azure from this model.

This is an alias to as_dict(full_restapi_key_transformer, keep_readonly=False).

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

keep_readonly (bool) – If you want to serialize the readonly attributes

Returns

A dict JSON compatible object

Return type

dict

validate()

Validate this model recursively and return a list of ValidationError.

Returns

A list of validation error

Return type

list

class azure.search.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_documents(*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_documents(*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_documents(*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_documents(*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.IndexingResult(**kwargs)[source]

Status of an indexing operation for a single document.

Variables are only populated by the server, and will be ignored when sending a request.

All required parameters must be populated in order to send to Azure.

Variables
  • key (str) – Required. The key of a document that was in the indexing request.

  • error_message (str) – The error message explaining why the indexing operation failed for the document identified by the key; null if indexing succeeded.

  • succeeded (bool) – Required. A value indicating whether the indexing operation succeeded for the document identified by the key.

  • status_code (int) – Required. The status code of the indexing operation. Possible values include: 200 for a successful update or delete, 201 for successful document creation, 400 for a malformed input document, 404 for document not found, 409 for a version conflict, 422 when the index is temporarily unavailable, or 503 for when the service is too busy.

as_dict(keep_readonly=True, key_transformer=<function attribute_transformer>, **kwargs)

Return a dict that can be JSONify using json.dump.

Advanced usage might optionaly use a callback as parameter:

Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains ‘type’ with the msrest type and ‘key’ with the RestAPI encoded key. Value is the current value in this object.

The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict.

See the three examples in this file:

  • attribute_transformer

  • full_restapi_key_transformer

  • last_restapi_key_transformer

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

key_transformer (function) – A key transformer function.

Returns

A dict JSON compatible object

Return type

dict

classmethod deserialize(data, content_type=None)

Parse a str using the RestAPI syntax and return a model.

Parameters
  • data (str) – A str using RestAPI structure. JSON by default.

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod enable_additional_properties_sending()
classmethod from_dict(data, key_extractors=None, content_type=None)

Parse a dict using given key extractor return a model.

By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor)

Parameters
  • data (dict) – A dict using RestAPI structure

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod is_xml_model()
serialize(keep_readonly=False, **kwargs)

Return the JSON that would be sent to azure from this model.

This is an alias to as_dict(full_restapi_key_transformer, keep_readonly=False).

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

keep_readonly (bool) – If you want to serialize the readonly attributes

Returns

A dict JSON compatible object

Return type

dict

validate()

Validate this model recursively and return a list of ValidationError.

Returns

A list of validation error

Return type

list

class azure.search.SearchApiKeyCredential(api_key)[source]

Credential type used for authenticating a SearchIndexClient with an admin or query API key.

Parameters

api_key (str) – An admin or query key for your Azure Search index.

update_key(key)[source]

Update the API key. This can be used when you’ve regenerated your service API key and want to update long-lived clients.

Parameters

key (str) – The API key to your Azure search account.

property api_key

The value of the configured API key.

Return type

str

class azure.search.SearchIndexClient(endpoint, index_name, credential, **kwargs)[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 (SearchApiKeyCredential) – A credential to authorize search client requests

Example:

Creating the SearchIndexClient with an API key.
from azure.search import SearchApiKeyCredential, SearchIndexClient
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 = SearchIndexClient(service_endpoint, index_name, SearchApiKeyCredential(key))
autocomplete(query, **kwargs)[source]

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

Parameters

query – An query for auto-completions

Return type

List[dict]

Example:

Get a auto-completions.
from azure.search import AutocompleteQuery, SearchApiKeyCredential, SearchIndexClient

search_client = SearchIndexClient(service_endpoint, index_name, SearchApiKeyCredential(key))

query = AutocompleteQuery(search_text="bo", suggester_name="sg")

results = search_client.autocomplete(query=query)

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

Close the SearchIndexClient session.

delete_documents(documents, **kwargs)[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(key, selected_fields=None, **kwargs)[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.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"]))
get_document_count(**kwargs)[source]

Return the number of documents in the Azure search index.

Return type

int

index_documents(batch, **kwargs)[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, **kwargs)[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, **kwargs)[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(query, **kwargs)[source]

Search the Azure search index for documents.

Parameters

query – An query for searching the index

Return type

SearchItemPaged[dict]

Example:

Search on a simple text term.
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"]))

Example:

Filter and sort search results.
from azure.search import SearchApiKeyCredential, SearchIndexClient, SearchQuery

search_client = SearchIndexClient(service_endpoint, index_name, SearchApiKeyCredential(key))

query = SearchQuery(search_text="WiFi")
query.filter("Address/StateProvince eq 'FL' and Address/Country eq 'USA'")
query.select("HotelName", "Rating")
query.order_by("Rating desc")

results = search_client.search(query=query)

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

Example:

suggest(query, **kwargs)[source]

Get search suggestion results from the Azure search index.

Parameters

query – An query for search suggestions

Return type

List[dict]

Example:

Get search suggestions.
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(documents, **kwargs)[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.SearchItemPaged(*args, **kwargs)[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=None)

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_facets()[source]

Return any facet results if faceting was requested.

next()

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

class azure.search.SearchQuery(**kwargs)[source]

Parameters for filtering, sorting, faceting, paging, and other search query behaviors.

Parameters
  • include_total_result_count (bool) – A value that specifies whether to fetch the total count of results. Default is false. Setting this value to true may have a performance impact. Note that the count returned is an approximation.

  • facets (list[str]) – The list of facet expressions to apply to the search query. Each facet expression contains a field name, optionally followed by a comma-separated list of name:value pairs.

  • filter (str) – The OData $filter expression to apply to the search query.

  • highlight_fields (str) – The comma-separated list of field names to use for hit highlights. Only searchable fields can be used for hit highlighting.

  • highlight_post_tag (str) – A string tag that is appended to hit highlights. Must be set with highlightPreTag. Default is &lt;/em&gt;.

  • highlight_pre_tag (str) – A string tag that is prepended to hit highlights. Must be set with highlightPostTag. Default is &lt;em&gt;.

  • minimum_coverage (float) – A number between 0 and 100 indicating the percentage of the index that must be covered by a search query in order for the query to be reported as a success. This parameter can be useful for ensuring search availability even for services with only one replica. The default is 100.

  • order_by (str) – The comma-separated list of OData $orderby expressions by which to sort the results. Each expression can be either a field name or a call to either the geo.distance() or the search.score() functions. Each expression can be followed by asc to indicate ascending, or desc to indicate descending. The default is ascending order. Ties will be broken by the match scores of documents. If no $orderby is specified, the default sort order is descending by document match score. There can be at most 32 $orderby clauses.

  • query_type (str or QueryType) – A value that specifies the syntax of the search query. The default is ‘simple’. Use ‘full’ if your query uses the Lucene query syntax. Possible values include: ‘simple’, ‘full’.

  • scoring_parameters (list[str]) – The list of parameter values to be used in scoring functions (for example, referencePointParameter) using the format name-values. For example, if the scoring profile defines a function with a parameter called ‘mylocation’ the parameter string would be “mylocation–122.2,44.8” (without the quotes).

  • scoring_profile (str) – The name of a scoring profile to evaluate match scores for matching documents in order to sort the results.

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

  • search_fields (str) – The comma-separated list of field names to which to scope the full-text search. When using fielded search (fieldName:searchExpression) in a full Lucene query, the field names of each fielded search expression take precedence over any field names listed in this parameter.

  • search_mode (str or SearchMode) – A value that specifies whether any or all of the search terms must be matched in order to count the document as a match. Possible values include: ‘any’, ‘all’.

  • select (str) – The comma-separated list of fields to retrieve. If unspecified, all fields marked as retrievable in the schema are included.

  • skip (int) – The number of search results to skip. This value cannot be greater than 100,000. If you need to scan documents in sequence, but cannot use skip due to this limitation, consider using orderby on a totally-ordered key and filter with a range query instead.

  • top (int) – The number of search results to retrieve. This can be used in conjunction with $skip to implement client-side paging of search results. If results are truncated due to server-side paging, the response will include a continuation token that can be used to issue another Search request for the next page of results.

filter(expression)

Add a filter expression for the search results.

Parameters

expression (str) – An ODate expression of for the query filter.

order_by(*fields)[source]

Update the orderby property for the search results.

Parameters

fields – An list of fields for the query result to be ordered by.

Raises

ValueError

select(*fields)[source]

Update the select property for the search results.

Parameters

fields – An list of fields for the query result to return.

Raises

ValueError

property request

The service request for this operation.

class azure.search.SuggestQuery(**kwargs)[source]

Parameters for filtering, sorting, fuzzy matching, and other suggestions query behaviors.

All required parameters must be populated in order to send to Azure.

Parameters
  • filter (str) – An OData expression that filters the documents considered for suggestions.

  • use_fuzzy_matching (bool) – A value indicating whether to use fuzzy matching for the suggestion query. Default is false. When set to true, the query will find suggestions even if there’s a substituted or missing character in the search text. While this provides a better experience in some scenarios, it comes at a performance cost as fuzzy suggestion searches are slower and consume more resources.

  • highlight_post_tag (str) – A string tag that is appended to hit highlights. Must be set with highlightPreTag. If omitted, hit highlighting of suggestions is disabled.

  • highlight_pre_tag (str) – A string tag that is prepended to hit highlights. Must be set with highlightPostTag. If omitted, hit highlighting of suggestions is disabled.

  • minimum_coverage (float) – A number between 0 and 100 indicating the percentage of the index that must be covered by a suggestion query in order for the query to be reported as a success. This parameter can be useful for ensuring search availability even for services with only one replica. The default is 80.

  • order_by (str) – The comma-separated list of OData $orderby expressions by which to sort the results. Each expression can be either a field name or a call to either the geo.distance() or the search.score() functions. Each expression can be followed by asc to indicate ascending, or desc to indicate descending. The default is ascending order. Ties will be broken by the match scores of documents. If no $orderby is specified, the default sort order is descending by document match score. There can be at most 32 $orderby clauses.

  • search_text (str) – Required. The search text to use to suggest documents. Must be at least 1 character, and no more than 100 characters.

  • search_fields (str) – The comma-separated list of field names to search for the specified search text. Target fields must be included in the specified suggester.

  • select (str) – The comma-separated list of fields to retrieve. If unspecified, only the key field will be included in the results.

  • suggester_name (str) – Required. The name of the suggester as specified in the suggesters collection that’s part of the index definition.

  • top (int) – The number of suggestions to retrieve. This must be a value between 1 and 100. The default is 5.

filter(expression)

Add a filter expression for the search results.

Parameters

expression (str) – An ODate expression of for the query filter.

property request

The service request for this operation.

azure.search.odata(statement, **kwargs)[source]

Escape an OData query string.

The statement to prepare should include fields to substitute given inside braces, e.g. {somevar} and then pass the corresponing value as a keyword argument, e.g. somevar=10.

Parameters

statement (str) – An OData query string to prepare

Return type

str

Example:

>>> odata("name eq {name} and age eq {age}", name="O'Neil", age=37)
"name eq 'O''Neil' and age eq 37"

Submodules

azure.search.aio module

class azure.search.aio.AsyncSearchItemPaged(*args, **kwargs)[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_facets() → Optional[dict][source]

Return any facet results if faceting was requested.

class azure.search.aio.SearchIndexClient(endpoint, index_name, credential, **kwargs)[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 (SearchApiKeyCredential) – A credential to authorize search client requests

Example:

Creating the SearchIndexClient with an API key.
from azure.search.aio import SearchIndexClient
from azure.search import SearchApiKeyCredential
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 = SearchIndexClient(service_endpoint, index_name, SearchApiKeyCredential(key))
async autocomplete(query, **kwargs)[source]

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

Parameters

query – An query for auto-completions

Return type

List[dict]

Example:

Get a auto-completions.
from azure.search.aio import SearchIndexClient
from azure.search import AutocompleteQuery, SearchApiKeyCredential

search_client = SearchIndexClient(service_endpoint, index_name, SearchApiKeyCredential(key))

query = AutocompleteQuery(search_text="bo", suggester_name="sg")

results = await search_client.autocomplete(query=query)

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

await search_client.close()
async close()[source]

Close the SearchIndexClient session.

async delete_documents(documents, **kwargs)[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(key, selected_fields=None, **kwargs)[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.search.aio import SearchIndexClient
from azure.search import SearchApiKeyCredential

search_client = SearchIndexClient(service_endpoint, index_name, SearchApiKeyCredential(key))

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

await search_client.close()
async get_document_count(**kwargs)[source]

Return the number of documents in the Azure search index.

Return type

int

async index_documents(batch, **kwargs)[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, **kwargs)[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, **kwargs)[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(query, **kwargs)[source]

Search the Azure search index for documents.

Parameters

query – An query for searching the index

Return type

AsyncSearchItemPaged[dict]

Example:

Search on a simple text term.
from azure.search.aio import SearchIndexClient
from azure.search import SearchApiKeyCredential

search_client = SearchIndexClient(service_endpoint, index_name, SearchApiKeyCredential(key))

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

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

await search_client.close()

Example:

Filter and sort search results.
from azure.search.aio import SearchIndexClient
from azure.search import SearchApiKeyCredential, SearchQuery

search_client = SearchIndexClient(service_endpoint, index_name, SearchApiKeyCredential(key))

query = SearchQuery(search_text="WiFi")
query.filter("Address/StateProvince eq 'FL' and Address/Country eq 'USA'")
query.select("HotelName", "Rating")
query.order_by("Rating desc")

results = await search_client.search(query=query)

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

await search_client.close()

Example:

Get search result facets.
from azure.search.aio import SearchIndexClient
from azure.search import SearchApiKeyCredential, SearchQuery

search_client = SearchIndexClient(service_endpoint, index_name, SearchApiKeyCredential(key))

query = SearchQuery(search_text="WiFi", facets=["Category"], top=0)

results = await search_client.search(query=query)

facets = await results.get_facets()

print("Catgory facet counts for hotels:")
for facet in facets["Category"]:
    print("    {}".format(facet))

await search_client.close()
async suggest(query, **kwargs)[source]

Get search suggestion results from the Azure search index.

Parameters

query – An query for search suggestions

Return type

List[dict]

Example:

Get search suggestions.
from azure.search.aio import SearchIndexClient
from azure.search import SearchApiKeyCredential, SuggestQuery

search_client = SearchIndexClient(service_endpoint, index_name, SearchApiKeyCredential(key))

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

results = await search_client.suggest(query=query)

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

await search_client.close()
async upload_documents(documents, **kwargs)[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))