Azure 認知搜尋適用于 Python 的用戶端程式庫 - 11.4.0 版

Azure 認知搜尋是搜尋即服務雲端解決方案,可為開發人員提供 API 和工具,透過 Web、行動和企業應用程式中的私用和異質內容來增添豐富的搜尋體驗。

Azure 認知搜尋服務非常適合下列應用程式案例:

  • 將不同的內容類型合併成單一可搜尋的索引。 若要填入索引,您可以推送包含內容的 JSON 檔,或者如果您的資料已經在 Azure 中,請建立索引子以自動提取資料。
  • 將技能集附加至索引子,以從影像和大型文字檔建立可搜尋的內容。 技能集利用認知服務的 AI 進行內建 OCR、實體辨識、關鍵字組擷取、語言偵測、文字翻譯和情感分析。 您也可以新增自訂技能,以在資料擷取期間整合內容的外部處理。
  • 在搜尋用戶端應用程式中,實作類似商業 Web 搜尋引擎的查詢邏輯和使用者體驗。

使用 Azure.Search.Documents 用戶端程式庫來:

  • 針對包含模糊搜尋、萬用字元搜尋、正則運算式的簡單和進階查詢表單提交查詢。
  • 針對多面向導覽、地理空間搜尋或根據篩選準則縮小結果範圍,實作篩選的查詢。
  • 建立和管理搜尋索引。
  • 上傳和更新搜尋索引中的檔。
  • 建立和管理索引子,以將資料從 Azure 提取至索引。
  • 建立和管理將 AI 擴充新增至資料擷取的技能集。
  • 建立及管理進階文字分析或多語系內容的分析器。
  • 透過評分設定檔將結果優化,以納入商務邏輯或最新狀態。

| 原始程式碼套件 (PyPI) | 套件 (Conda) | API 參考檔 | 產品檔 | 樣品

開始使用

安裝套件

使用pip安裝適用于 Python 的Azure 認知搜尋用戶端程式庫:

pip install azure-search-documents

必要條件

若要建立新的搜尋服務,您可以使用Azure 入口網站Azure PowerShellAzure CLI

az search service create --name <mysearch> --resource-group <mysearch-rg> --sku free --location westus

如需可用選項的詳細資訊 ,請參閱選擇定價層

驗證用戶端

若要與搜尋服務互動,您必須建立適當的用戶端類別實例: SearchClient 搜尋索引的檔、 SearchIndexClient 管理索引,或 SearchIndexerClient 編目資料來源,並將搜尋檔載入索引中。 若要具現化用戶端物件,您需要 端點API 金鑰。 如需搜尋服務支援驗證方法的詳細資訊,請參閱檔。

取得 API 金鑰

您可以從Azure入口網站中的搜尋服務取得端點API 金鑰。 如需如何取得 API 金鑰的指示,請參閱

或者,您可以使用下列Azure CLI命令,從搜尋服務擷取 API 金鑰:

az search admin-key show --service-name <mysearch> --resource-group <mysearch-rg>

有兩種類型的金鑰可用來存取您的搜尋服務:系統管理員 (讀寫) 查詢 (唯讀) 金鑰。 限制用戶端應用程式中的存取和作業是保護服務上搜尋資產的必要條件。 請一律針對源自用戶端應用程式的任何查詢使用查詢金鑰,而非使用系統管理員金鑰。

注意:上述範例 Azure CLI 程式碼片段會擷取系統管理金鑰,以便更輕鬆地開始探索 API,但應該謹慎管理。

建立 SearchClient

若要具現化 SearchClient ,您需要 端點API 金鑰索引名稱

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

service_endpoint = os.environ["AZURE_SEARCH_SERVICE_ENDPOINT"]
index_name = os.environ["AZURE_SEARCH_INDEX_NAME"]
key = os.environ["AZURE_SEARCH_API_KEY"]

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

使用 Azure Active Directory 驗證建立用戶端

您也可以建立 SearchClientSearchIndexClient 或使用 SearchIndexerClient Azure Active Directory (AAD) 驗證。 您的使用者或服務主體必須獲指派「搜尋索引資料讀取者」角色。 使用 DefaultAzureCredential ,您可以使用受控識別或服務主體來驗證服務、以開發人員身分驗證應用程式,以及更多專案,而不需要變更程式碼。 如需如何使用 Azure 角色型存取控制 (Azure RBAC) 連線到Azure 認知搜尋的指示,請參閱

您必須先安裝 Azure.Identity 套件,才能使用DefaultAzureCredential 、 或任何認證類型。

若要搭配用戶端識別碼和秘密使用 DefaultAzureCredential ,您必須設定 AZURE_TENANT_IDAZURE_CLIENT_IDAZURE_CLIENT_SECRET 環境變數;或者,您也可以將這些值傳遞至 ClientSecretCredential Azure.Identity 中的 。

請確定您在原始程式檔頂端使用正確的命名空間 DefaultAzureCredential

from azure.identity import DefaultAzureCredential
from azure.search.documents import SearchClient

service_endpoint = os.getenv("AZURE_SEARCH_SERVICE_ENDPOINT")
index_name = os.getenv("AZURE_SEARCH_INDEX_NAME")
credential = DefaultAzureCredential()

search_client = SearchClient(service_endpoint, index_name, credential)

重要概念

Azure 認知搜尋服務包含一或多個索引,以 JSON 檔的形式提供可搜尋資料的持續性儲存體。 (如果您不熟悉搜尋,您可以在索引和資料庫資料表之間產生非常粗略的類比。) Azure.Search.Documents 用戶端程式庫會透過兩個主要用戶端類型公開這些資源的作業。

Azure 認知搜尋提供兩個功能強大的功能:語意搜尋向量搜尋

語意搜尋 可增強文字型查詢的搜尋結果品質。 藉由在搜尋服務上啟用語意搜尋,您可以透過兩種方式改善搜尋結果的相關性:

  • 它會將次要排名套用至初始結果集,將最語意上相關的結果升階至頂端。
  • 它會擷取並傳迴響應中的標題和答案,這可以在搜尋頁面上顯示,以增強使用者的搜尋體驗。

若要深入瞭解語意搜尋,您可以參考

向量搜尋 是一種資訊擷取技術,可克服傳統關鍵字型搜尋的限制。 向量搜尋會利用機器學習模型來擷取單字和片語的內容意義,而不是只依賴語彙分析和比對個別查詢詞彙。 它會在稱為內嵌的高維度空間中,將檔和查詢表示為向量。 藉由瞭解查詢背後的意圖,向量搜尋可以提供更相關的結果,以符合使用者的需求,即使檔中沒有確切的詞彙也一樣。 此外,向量搜尋也可以套用至各種類型的內容,包括影像和影片,而不只是文字。

若要瞭解如何編制向量欄位的索引並執行向量搜尋,您可以參考 範例。 此範例提供索引向量欄位的詳細指引,並示範如何執行向量搜尋。

此外,如需有關向量搜尋的更完整資訊,包括其概念和使用方式,您可以參考 。 本檔提供深入說明和指引,以運用Azure 認知搜尋中的向量搜尋功能。

用戶端 Azure.Search.Documents 程式庫 (v1) 是一項全新的供應專案,適用于想要在其應用程式中使用搜尋技術的 Python 開發人員。 有一個較舊的完整功能 Microsoft.Azure.Search 用戶端程式庫, (v10) 有許多類似外觀的 API,因此在探索線上資源時請小心避免混淆。

範例

下列範例全都使用簡單的Hotel 資料集,您可以從Azure 入口網站匯入自己的索引。這些只是一些基本概念- 請參閱我們的範例以取得更多內容。

查詢

讓我們從匯入命名空間開始。

import os
from azure.core.credentials import AzureKeyCredential
from azure.search.documents import SearchClient

然後,我們將建立 來 SearchClient 存取旅館搜尋索引。

index_name = "hotels"
# Get the service endpoint and API key from the environment
endpoint = os.environ["SEARCH_ENDPOINT"]
key = os.environ["SEARCH_API_KEY"]

# Create a client
credential = AzureKeyCredential(key)
client = SearchClient(endpoint=endpoint,
                      index_name=index_name,
                      credential=credential)

讓我們搜尋「飯店」。

results = client.search(search_text="luxury")

for result in results:
    print("{}: {})".format(result["hotelId"], result["hotelName"]))

建立索引

您可以使用 SearchIndexClient 來建立搜尋索引。 您可以使用方便 SimpleField 的 、 SearchableFieldComplexField 模型來定義欄位。 索引也可以定義建議工具、語彙分析器等等。

client = SearchIndexClient(service_endpoint, AzureKeyCredential(key))
name = "hotels"
fields = [
    SimpleField(name="hotelId", type=SearchFieldDataType.String, key=True),
    SimpleField(name="baseRate", type=SearchFieldDataType.Double),
    SearchableField(name="description", type=SearchFieldDataType.String, collection=True),
    ComplexField(
        name="address",
        fields=[
            SimpleField(name="streetAddress", type=SearchFieldDataType.String),
            SimpleField(name="city", type=SearchFieldDataType.String),
        ],
        collection=True,
    ),
]
cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60)
scoring_profiles: List[ScoringProfile] = []
index = SearchIndex(name=name, fields=fields, scoring_profiles=scoring_profiles, cors_options=cors_options)

result = client.create_index(index)

將檔新增至索引

您可以在 Upload 單一批次要求中,從索引、 MergeMergeOrUpload 、 和 Delete 多個檔。 有 一些特殊規則可以注意合併

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

在國家雲端中驗證

若要在 國家雲端中驗證,您必須在用戶端設定中新增下列專案:

  • AuthorityHost在認證選項中或透過環境變數設定 AZURE_AUTHORITY_HOST
  • audience在 、 SearchIndexClient 或 中 SearchClient 設定SearchIndexerClient
# Create a SearchClient that will authenticate through AAD in the China national cloud.
import os
from azure.identity import DefaultAzureCredential, AzureAuthorityHosts
from azure.search.documents import SearchClient

index_name = "hotels"
endpoint = os.environ["SEARCH_ENDPOINT"]
key = os.environ["SEARCH_API_KEY"]
credential = DefaultAzureCredential(authority=AzureAuthorityHosts.AZURE_CHINA)

search_client = SearchClient(endpoint, index_name, credential=credential, audience="https://search.azure.cn")

從索引擷取特定檔

除了使用關鍵字和選擇性篩選來查詢檔之外,如果您已經知道索引鍵,也可以從索引中擷取特定檔。 例如,您可以從查詢取得金鑰,並想要顯示其詳細資訊,或將您的客戶巡覽至該檔。

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

非同步 API

此程式庫包含完整的非同步 API。 若要使用它,您必須先安裝非同步傳輸,例如 aioHTTP。 如需詳細資訊 ,請參閱 azure 核心檔

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

疑難排解

一般

Azure 認知搜尋用戶端會引發Azure Core中定義的例外狀況。

記錄

此程式庫會使用標準記錄程式庫進行 記錄 。 HTTP 會話的基本資訊 (URL、標頭等。) 會記錄在 INFO 層級。

您可以在具備 logging_enable 關鍵字引數的用戶端啟用詳細的「偵錯」層級記錄,包括要求/回應本文和未刪改的標頭:

import sys
import logging
from azure.core.credentials import AzureKeyCredential
from azure.search.documents import SearchClient

# Create a logger for the 'azure' SDK
logger = logging.getLogger('azure')
logger.setLevel(logging.DEBUG)

# Configure a console output
handler = logging.StreamHandler(stream=sys.stdout)
logger.addHandler(handler)

# This client will log detailed information about its HTTP sessions, at DEBUG level
client = SearchClient("<service endpoint>", "<index_name>", AzureKeyCredential("<api key>"), logging_enable=True)

同樣地,logging_enable 可對單一作業啟用詳細記錄,即使未對用戶端啟用也可行:

result =  client.search(search_text="spa", logging_enable=True)

後續步驟

參與

如需建置、測試和參與此程式庫的詳細資訊,請參閱我們的 搜尋 CONTRIBUTING.md

此專案歡迎參與和提供建議。 大部分的參與都要求您同意「參與者授權合約 (CLA)」,宣告您有權且確實授與我們使用投稿的權利。 如需詳細資訊,請造訪 cla.microsoft.com

此專案採用 Microsoft Open Source Code of Conduct (Microsoft 開放原始碼管理辦法)。 如需詳細資訊,請參閱管理辦法常見問題集,如有任何其他問題或意見請連絡 opencode@microsoft.com

印象

曝光數