|
| 1 | +# coding: utf-8 |
| 2 | + |
| 3 | +# ------------------------------------------------------------------------- |
| 4 | +# Copyright (c) Microsoft Corporation. All rights reserved. |
| 5 | +# Licensed under the MIT License. See License.txt in the project root for |
| 6 | +# license information. |
| 7 | +# -------------------------------------------------------------------------- |
| 8 | + |
| 9 | +""" |
| 10 | +FILE: sample_query_session_async.py |
| 11 | +DESCRIPTION: |
| 12 | + To ensure more consistent and unique search results within a user's session, you can use session id. |
| 13 | + Simply include the session_id parameter in your queries to create a unique identifier for each user session. |
| 14 | + This ensures a uniform experience for users throughout their "query session". |
| 15 | +USAGE: |
| 16 | + python sample_query_session_async.py |
| 17 | +
|
| 18 | + Set the environment variables with your own values before running the sample: |
| 19 | + 1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service |
| 20 | + 2) AZURE_SEARCH_INDEX_NAME - the name of your search index (e.g. "hotels-sample-index") |
| 21 | + 3) AZURE_SEARCH_API_KEY - your search API key |
| 22 | +""" |
| 23 | + |
| 24 | +import os |
| 25 | +import asyncio |
| 26 | + |
| 27 | +service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"] |
| 28 | +index_name = os.environ["AZURE_SEARCH_INDEX_NAME"] |
| 29 | +key = os.environ["AZURE_SEARCH_API_KEY"] |
| 30 | + |
| 31 | + |
| 32 | +async def query_session(): |
| 33 | + # [START query_session_async] |
| 34 | + from azure.core.credentials import AzureKeyCredential |
| 35 | + from azure.search.documents.aio import SearchClient |
| 36 | + |
| 37 | + search_client = SearchClient(service_endpoint, index_name, AzureKeyCredential(key)) |
| 38 | + |
| 39 | + async with search_client: |
| 40 | + results = await search_client.search(search_text="spa", session_id="session-1") |
| 41 | + |
| 42 | + print("Hotels containing 'spa' in the name (or other fields):") |
| 43 | + async for result in results: |
| 44 | + print(" Name: {} (rating {})".format(result["hotelName"], result["rating"])) |
| 45 | + # [END query_session_async] |
| 46 | + |
| 47 | + |
| 48 | +if __name__ == "__main__": |
| 49 | + asyncio.run(query_session()) |
0 commit comments