コード例 #1
0
    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']
コード例 #2
0
 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")
コード例 #3
0
 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'}]
コード例 #4
0
 async def test_suggest(self, api_key, endpoint, index_name, **kwargs):
     client = SearchIndexClient(
         endpoint, index_name, SearchApiKeyCredential(api_key)
     )
     async with client:
         query = SuggestQuery(search_text="mot", suggester_name="sg")
         results = await client.suggest(query=query)
         assert results == [
             {'hotelId': '2', 'text': 'Cheapest hotel in town. Infact, a motel.'},
             {'hotelId': '9', 'text': 'Secret Point Motel'},
         ]
コード例 #5
0
    async 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")

        async with client:
            results = await client.search(query=query)
            assert await results.get_facets() == {'category': [{'value': 'Budget', 'count': 4}, {'value': 'Luxury', 'count': 1}]}
コード例 #6
0
    async 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")

        async with client:
            results = await client.search(query=query)
            assert await results.get_facets() is None
コード例 #7
0
 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")
コード例 #8
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
コード例 #9
0
async def autocomplete_query():
    # [START get_document_async]
    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()
コード例 #10
0
async def authentication_with_api_key_credential_async():
    # [START create_search_client_with_key_async]
    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))
    # [END create_search_client_with_key_async]
    async with search_client:
        result = await search_client.get_document_count()

    print("There are {} documents in the {} search index.".format(
        result, repr(index_name)))
コード例 #11
0
async def simple_text_query():
    # [START simple_query_async]
    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()
コード例 #12
0
    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)
コード例 #13
0
    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
コード例 #14
0
async def suggest_query():
    # [START suggest_query_async]
    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()
コード例 #15
0
    async def test_delete_documents_missing(self, api_key, endpoint, index_name, **kwargs):
        client = SearchIndexClient(
            endpoint, index_name, SearchApiKeyCredential(api_key)
        )
        async with client:
            results = await 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 await client.get_document_count() == 9

            with pytest.raises(HttpResponseError):
                await client.get_document(key="1000")

            with pytest.raises(HttpResponseError):
                await client.get_document(key="4")
コード例 #16
0
async def filter_query():
    # [START facet_query_async]
    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()
コード例 #17
0
 async 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',
     }]
     async with client:
         results = await client.upload_documents(DOCUMENTS)
         assert len(results) == 2
         assert set(x.status_code for x in results) == {200, 201}
コード例 #18
0
async def filter_query():
    # [START filter_query_async]
    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()
コード例 #19
0
    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.aio import SearchIndexClient
from azure.search 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]
コード例 #20
0
 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