def test_credential_roll(self): credential = SearchApiKeyCredential(api_key="old_api_key") client = SearchIndexClient("endpoint", "index name", credential) assert client._headers == { "api-key": "old_api_key", "Accept": "application/json;odata.metadata=none", } credential.update_key("new_api_key") assert client._headers == { "api-key": "new_api_key", "Accept": "application/json;odata.metadata=none", }
async def test_get_document_missing(self, api_key, endpoint, index_name, **kwargs): client = SearchIndexClient(endpoint, index_name, SearchApiKeyCredential(api_key)) async with client: with pytest.raises(HttpResponseError): await client.get_document(key="1000")
async def test_get_search_filter(self, api_key, endpoint, index_name, **kwargs): client = SearchIndexClient(endpoint, index_name, SearchApiKeyCredential(api_key)) query = SearchQuery(search_text="WiFi") query.filter("category eq 'Budget'") query.select("hotelName", "category", "description") query.order_by("hotelName desc") async with client: results = [] async for x in await client.search(query=query): results.append(x) assert [x["hotelName"] for x in results ] == sorted([x["hotelName"] for x in results], reverse=True) expected = { "category", "hotelName", "description", "@search.score", "@search.highlights", } assert all(set(x) == expected for x in results) assert all(x["category"] == "Budget" for x in results)
async def test_autocomplete(self, api_key, endpoint, index_name, **kwargs): client = SearchIndexClient(endpoint, index_name, SearchApiKeyCredential(api_key)) async with client: query = AutocompleteQuery(search_text="mot", suggester_name="sg") results = await client.autocomplete(query=query) assert results == [{"text": "motel", "query_plus_text": "motel"}]
async def test_upload_documents_new(self, api_key, endpoint, index_name, **kwargs): client = SearchIndexClient(endpoint, index_name, SearchApiKeyCredential(api_key)) DOCUMENTS = [ { "hotelId": "1000", "rating": 5, "rooms": [], "hotelName": "Azure Inn" }, { "hotelId": "1001", "rating": 4, "rooms": [], "hotelName": "Redmond Hotel" }, ] async with client: results = await client.upload_documents(DOCUMENTS) assert len(results) == 2 assert set(x.status_code for x in results) == {201} # There can be some lag before a document is searchable time.sleep(3) assert await client.get_document_count() == 12 for doc in DOCUMENTS: result = await client.get_document(key=doc["hotelId"]) assert result["hotelId"] == doc["hotelId"] assert result["hotelName"] == doc["hotelName"] assert result["rating"] == doc["rating"] assert result["rooms"] == doc["rooms"]
async def test_merge_or_upload_documents(self, api_key, endpoint, index_name, **kwargs): client = SearchIndexClient(endpoint, index_name, SearchApiKeyCredential(api_key)) async with client: results = await client.merge_or_upload_documents([{ "hotelId": "1000", "rating": 1 }, { "hotelId": "4", "rating": 2 }]) assert len(results) == 2 assert set(x.status_code for x in results) == {200, 201} # There can be some lag before a document is searchable time.sleep(3) assert await client.get_document_count() == 11 result = await client.get_document(key="1000") assert result["rating"] == 1 result = await client.get_document(key="4") assert result["rating"] == 2
def test_get_search_simple(self, api_key, endpoint, index_name, **kwargs): client = SearchIndexClient( endpoint, index_name, SearchApiKeyCredential(api_key) ) results = list(client.search(query="hotel")) assert len(results) == 7 results = list(client.search(query="motel")) assert len(results) == 2
async def test_get_document(self, api_key, endpoint, index_name, **kwargs): client = SearchIndexClient(endpoint, index_name, SearchApiKeyCredential(api_key)) async with client: for hotel_id in range(1, 11): result = await client.get_document(key=str(hotel_id)) expected = BATCH["value"][hotel_id - 1] assert result.get("hotelId") == expected.get("hotelId") assert result.get("hotelName") == expected.get("hotelName") assert result.get("description") == expected.get("description")
def test_get_search_facets_none(self, api_key, endpoint, index_name, **kwargs): client = SearchIndexClient( endpoint, index_name, SearchApiKeyCredential(api_key) ) query = SearchQuery(search_text="WiFi") query.select("hotelName", "category", "description") results = client.search(query=query) assert results.get_facets() is None
def test_suggest(self, api_key, endpoint, index_name, **kwargs): client = SearchIndexClient( endpoint, index_name, SearchApiKeyCredential(api_key) ) query = SuggestQuery(search_text="mot", suggester_name="sg") results = client.suggest(query=query) assert results == [ {"hotelId": "2", "text": "Cheapest hotel in town. Infact, a motel."}, {"hotelId": "9", "text": "Secret Point Motel"}, ]
def test_headers_merge(self): credential = SearchApiKeyCredential(api_key="test_api_key") client = SearchIndexClient("endpoint", "index name", credential) orig = {"foo": "bar"} result = client._merge_client_headers(orig) assert result is not orig assert result == { "api-key": "test_api_key", "Accept": "application/json;odata.metadata=none", "foo": "bar", }
def test_upload_documents_existing(self, api_key, endpoint, index_name, **kwargs): client = SearchIndexClient( endpoint, index_name, SearchApiKeyCredential(api_key) ) DOCUMENTS = [ {"hotelId": "1000", "rating": 5, "rooms": [], "hotelName": "Azure Inn"}, {"hotelId": "3", "rating": 4, "rooms": [], "hotelName": "Redmond Hotel"}, ] results = client.upload_documents(DOCUMENTS) assert len(results) == 2 assert set(x.status_code for x in results) == {200, 201}
def test_get_search_counts(self, api_key, endpoint, index_name, **kwargs): client = SearchIndexClient( endpoint, index_name, SearchApiKeyCredential(api_key) ) query = SearchQuery(search_text="hotel") results = client.search(query=query) assert results.get_count() is None query = SearchQuery(search_text="hotel", include_total_result_count=True) results = client.search(query=query) assert results.get_count() == 7
def get_document(): # [START get_document] from azure.search.documents 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"]))
def simple_text_query(): # [START simple_query] from azure.search.documents 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"]))
def autocomplete_query(): # [START autocomplete_query] from azure.search.documents 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"]))
async def test_get_search_coverage(self, api_key, endpoint, index_name, **kwargs): client = SearchIndexClient(endpoint, index_name, SearchApiKeyCredential(api_key)) query = SearchQuery(search_text="hotel") results = await client.search(query=query) assert await results.get_coverage() is None query = SearchQuery(search_text="hotel", minimum_coverage=50.0) results = await client.search(query=query) cov = await results.get_coverage() assert isinstance(cov, float) assert cov >= 50.0
async def test_get_search_simple(self, api_key, endpoint, index_name, **kwargs): client = SearchIndexClient(endpoint, index_name, SearchApiKeyCredential(api_key)) async with client: results = [] async for x in await client.search(query="hotel"): results.append(x) assert len(results) == 7 results = [] async for x in await client.search(query="motel"): results.append(x) assert len(results) == 2
def suggest_query(): # [START suggest_query] from azure.search.documents 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"]))
def authentication_with_api_key_credential(): # [START create_search_client_with_key] from azure.search.documents 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)) # [END create_search_client_with_key] result = search_client.get_document_count() print("There are {} documents in the {} search index.".format( result, repr(index_name)))
def filter_query(): # [START facet_query] from azure.search.documents import SearchApiKeyCredential, SearchIndexClient, SearchQuery search_client = SearchIndexClient(service_endpoint, index_name, SearchApiKeyCredential(key)) query = SearchQuery(search_text="WiFi", facets=["Category"], top=0) results = search_client.search(query=query) facets = results.get_facets() print("Catgory facet counts for hotels:") for facet in facets["Category"]: print(" {}".format(facet))
def test_get_search_facets_result(self, api_key, endpoint, index_name, **kwargs): client = SearchIndexClient( endpoint, index_name, SearchApiKeyCredential(api_key) ) query = SearchQuery(search_text="WiFi", facets=["category"]) query.select("hotelName", "category", "description") results = client.search(query=query) assert results.get_facets() == { "category": [ {"value": "Budget", "count": 4}, {"value": "Luxury", "count": 1}, ] }
async def autocomplete_query(): # [START get_document_async] from azure.search.documents.aio import SearchIndexClient from azure.search.documents 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()
def test_delete_documents_missing(self, api_key, endpoint, index_name, **kwargs): client = SearchIndexClient( endpoint, index_name, SearchApiKeyCredential(api_key) ) results = client.delete_documents([{"hotelId": "1000"}, {"hotelId": "4"}]) assert len(results) == 2 assert set(x.status_code for x in results) == {200} # There can be some lag before a document is searchable time.sleep(3) assert client.get_document_count() == 9 with pytest.raises(HttpResponseError): client.get_document(key="1000") with pytest.raises(HttpResponseError): client.get_document(key="4")
def filter_query(): # [START filter_query] from azure.search.documents 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"]))
def test_merge_documents_existing(self, api_key, endpoint, index_name, **kwargs): client = SearchIndexClient( endpoint, index_name, SearchApiKeyCredential(api_key) ) results = client.merge_documents( [{"hotelId": "3", "rating": 1}, {"hotelId": "4", "rating": 2}] ) assert len(results) == 2 assert set(x.status_code for x in results) == {200} # There can be some lag before a document is searchable time.sleep(3) assert client.get_document_count() == 10 result = client.get_document(key="3") assert result["rating"] == 1 result = client.get_document(key="4") assert result["rating"] == 2
1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") 3) AZURE_SEARCH_API_KEY - your search API key """ import os import asyncio service_endpoint = os.getenv("AZURE_SEARCH_SERVICE_ENDPOINT") index_name = os.getenv("AZURE_SEARCH_INDEX_NAME") key = os.getenv("AZURE_SEARCH_API_KEY") from azure.search.documents.aio import SearchIndexClient from azure.search.documents import SearchApiKeyCredential, SearchQuery search_client = SearchIndexClient(service_endpoint, index_name, SearchApiKeyCredential(key)) async def upload_document(): # [START upload_document_async] 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)) # [END upload_document_async]
SearchDocumentsResult, SearchResult, ) from azure.search.documents._index._search_index_client import SearchPageIterator from azure.search.documents import ( AutocompleteQuery, IndexDocumentsBatch, SearchApiKeyCredential, SearchIndexClient, SearchQuery, SuggestQuery, odata, ) CREDENTIAL = SearchApiKeyCredential(api_key="test_api_key") CRUD_METHOD_NAMES = [ "upload_documents", "delete_documents", "merge_documents", "merge_or_upload_documents", ] CRUD_METHOD_MAP = dict( zip(CRUD_METHOD_NAMES, ["upload", "delete", "merge", "mergeOrUpload"])) class Test_odata(object): def test_const(self): assert odata("no escapes") == "no escapes"
Set the environment variables with your own values before running the sample: 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") 3) AZURE_SEARCH_API_KEY - your search API key """ import os service_endpoint = os.getenv("AZURE_SEARCH_SERVICE_ENDPOINT") index_name = os.getenv("AZURE_SEARCH_INDEX_NAME") key = os.getenv("AZURE_SEARCH_API_KEY") from azure.search.documents import SearchApiKeyCredential, SearchIndexClient search_client = SearchIndexClient(service_endpoint, index_name, SearchApiKeyCredential(key)) def upload_document(): # [START upload_document] 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))
async def test_async_get_document_count(self, api_key, endpoint, index_name, **kwargs): client = SearchIndexClient(endpoint, index_name, SearchApiKeyCredential(api_key)) async with client: assert await client.get_document_count() == 10