快速入門:使用 Bing 實體搜尋用戶端程式庫

警告

在 2020 年 10 月 30 日,Bing 搜尋 API 已從 Azure AI 服務移至 Bing 搜尋 服務。 本文件僅供參考之用。 如需更新的文件,請參閱 Bing 搜尋 API 文件。 如需針對 Bing 搜尋建立新 Azure 資源的指示,請參閱透過 Azure Marketplace 建立 Bing 搜尋資源

使用本快速入門,透過適用於 C# 的 Bing 實體搜尋用戶端程式庫開始搜尋實體。 雖然 Bing 實體搜尋具有與大部分程式設計語言相容的 REST API,但此用戶端程式庫可提供簡單的方法,將服務整合到您的應用程式。 此範例的原始程式碼可以在 GitHub 上找到。

Prerequisites

若要將 Bing 實體搜尋用戶端程式庫新增至 Visual Studio 專案,請使用 [方案總管] 中的 [管理 NuGet 套件] 選項,然後新增 Microsoft.Azure.CognitiveServices.Search.EntitySearch 套件。

建立 Azure 資源

藉由建立下列其中一項 Azure 資源,開始使用 Bing 實體搜尋 API。

Bing 實體搜尋資源

  • 您可以透過 Azure 入口網站取得該資源,直到將其刪除為止。
  • 使用免費定價層來試用服務,之後可升級至付費層以用於實際執行環境。
  • Bing 實體搜尋也會在 Bing 搜尋 v7 資源的付費層中提供。

多服務資源

  • 您可以透過 Azure 入口網站取得該資源,直到將其刪除為止。
  • 針對您的應用程式,跨多個 Azure AI 服務使用相同的金鑰和端點。

建立應用程式並將其初始化

  1. 在 Visual Studio 中建立新的 C# 主控台解決方案。 然後將下列內容新增至主要程式碼檔案。

    using System;
    using System.Linq;
    using System.Text;
    using Microsoft.Azure.CognitiveServices.Search.EntitySearch;
    using Microsoft.Azure.CognitiveServices.Search.EntitySearch.Models;
    using Newtonsoft.Json;
    

建立用戶端並傳送搜尋要求

  1. 建立新的搜尋用戶端。 建立新的 ApiKeyServiceClientCredentials 以新增訂用帳戶金鑰。

    var client = new EntitySearchClient(new ApiKeyServiceClientCredentials("YOUR-ACCESS-KEY"));
    
  2. 使用用戶端的 Entities.Search() 函式來搜尋您的查詢:

    var entityData = client.Entities.Search(query: "Satya Nadella");
    

取得並列印實體描述

  1. 如果此 API 傳回搜尋結果,請從 entityData 取得主要實體。

    var mainEntity = entityData.Entities.Value.Where(thing => thing.EntityPresentationInfo.EntityScenario == EntityScenario.DominantEntity).FirstOrDefault();
    
  2. 列印主要實體的描述

    Console.WriteLine(mainEntity.Description);
    

後續步驟

使用本快速入門,透過適用於 Java 的 Bing 實體搜尋用戶端程式庫開始搜尋實體。 雖然 Bing 實體搜尋具有與大部分程式設計語言相容的 REST API,但此用戶端程式庫可提供簡單的方法,將服務整合到您的應用程式。 此範例的原始程式碼可以在 GitHub 上找到。

Prerequisites

使用 Maven、Gradle 或另一個相依性管理系統,安裝 Bing 實體搜尋用戶端程式庫相依性。 Maven POM 檔案需要宣告:

<dependency>
  <groupId>com.microsoft.azure.cognitiveservices</groupId>
  <artifactId>azure-cognitiveservices-entitysearch</artifactId>
  <version>1.0.2</version>
</dependency>

建立 Azure 資源

藉由建立下列其中一項 Azure 資源,開始使用 Bing 實體搜尋 API。

Bing 實體搜尋資源

  • 您可以透過 Azure 入口網站取得該資源,直到將其刪除為止。
  • 使用免費定價層來試用服務,之後可升級至付費層以用於實際執行環境。
  • Bing 實體搜尋也會在 Bing 搜尋 v7 資源的付費層中提供。

多服務資源

  • 您可以透過 Azure 入口網站取得該資源,直到將其刪除為止。
  • 針對您的應用程式,跨多個 Azure AI 服務使用相同的金鑰和端點。

建立專案並將其初始化

  1. 在您最愛的 IDE 或編輯器中建立新的 Java 專案,並匯入下列程式庫。

    import com.microsoft.azure.cognitiveservices.entitysearch.*;
    import com.microsoft.azure.cognitiveservices.entitysearch.implementation.EntitySearchAPIImpl;
    import com.microsoft.azure.cognitiveservices.entitysearch.implementation.SearchResponseInner;
    import com.microsoft.rest.credentials.ServiceClientCredentials;
    import okhttp3.Interceptor;
    import okhttp3.OkHttpClient;
    import okhttp3.Request;
    import okhttp3.Response;
    
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    
  2. 建立訂用帳戶金鑰的變數

    String subscriptionKey = "your-key-here"
    

建立搜尋用戶端

  1. 實作 dominantEntityLookup 用戶端,這需要 API 端點及 ServiceClientCredentials 類別的執行個體。 您可以使用下方的全域端點,也可以使用 Azure 入口網站中針對您的資源所顯示的自訂子網域端點。

    public static EntitySearchAPIImpl getClient(final String subscriptionKey) {
        return new EntitySearchAPIImpl("https://api.cognitive.microsoft.com/bing/v7.0/",
                new ServiceClientCredentials() {
                //...
                }
    )};
    

    若要實作 ServiceClientCredentials,請遵循下列步驟:

    1. 以作為參數的 OkHttpClient.Builder 物件覆寫 applyCredentialsFilter() 函式。

      //...
      new ServiceClientCredentials() {
              @Override
              public void applyCredentialsFilter(OkHttpClient.Builder builder) {
              //...
              }
      //...
      
    2. applyCredentialsFilter() 內呼叫 builder.addNetworkInterceptor()。 建立新的 Interceptor 物件,並覆寫其 intercept() 方法,以取用 Chain 攔截器物件。

      //...
      builder.addNetworkInterceptor(
          new Interceptor() {
              @Override
              public Response intercept(Chain chain) throws IOException {
              //...    
              }
          });
      ///...
      
    3. intercept 函式內,為您的要求建立變數。 使用 Request.Builder() 來建置您的要求。 將您的訂用帳戶金鑰新增至 Ocp-Apim-Subscription-Key 標頭,然後傳回要求物件上的 chain.proceed()

      //...
      public Response intercept(Chain chain) throws IOException {
          Request request = null;
          Request original = chain.request();
          Request.Builder requestBuilder = original.newBuilder()
                  .addHeader("Ocp-Apim-Subscription-Key", subscriptionKey);
          request = requestBuilder.build();
          return chain.proceed(request);
      }
      //...
      

傳送要求並接收回應

  1. 使用您的訂用帳戶金鑰建立新的搜尋用戶端執行個體。 使用 client.entities().search() 傳送搜尋查詢 satya nadella 的搜尋要求,並取得回應。

    EntitySearchAPIImpl client = getClient(subscriptionKey);
    SearchResponseInner entityData = client.entities().search(
            "satya nadella", null, null, null, null, null, null, "en-us", null, null, SafeSearch.STRICT, null);
    
  2. 如果傳回任何實體,請將其轉換為清單。 逐一查看這些項目,並列印主控實體。

    if (entityData.entities().value().size() > 0){
        // Find the entity that represents the dominant entity
        List<Thing> entries = entityData.entities().value();
        Thing dominateEntry = null;
        for(Thing thing : entries) {
            if(thing.entityPresentationInfo().entityScenario() == EntityScenario.DOMINANT_ENTITY) {
                System.out.println("\r\nSearched for \"Satya Nadella\" and found a dominant entity with this description:");
                System.out.println(thing.description());
                break;
            }
        }
    }
    

後續步驟

使用本快速入門,透過適用於 JavaScript 的 Bing 實體搜尋用戶端程式庫開始搜尋實體。 雖然 Bing 實體搜尋具有與大部分程式設計語言相容的 REST API,但此用戶端程式庫可提供簡單的方法,將服務整合到您的應用程式。 此範例的原始程式碼可以在 GitHub 上找到。

Prerequisites

  • 最新版的 Node.js
  • 適用於 JavaScript 的 Bing 實體搜尋 SDK
    • 若要安裝,請執行 npm install @azure/cognitiveservices-entitysearch
  • 來自 @azure/ms-rest-azure-js 套件中的 CognitiveServicesCredentials 類別,用來驗證用戶端。
    • 若要安裝,請執行 npm install @azure/ms-rest-azure-js

建立 Azure 資源

藉由建立下列其中一項 Azure 資源,開始使用 Bing 實體搜尋 API。

Bing 實體搜尋資源

  • 您可以透過 Azure 入口網站取得該資源,直到將其刪除為止。
  • 使用免費定價層來試用服務,之後可升級至付費層以用於實際執行環境。
  • Bing 實體搜尋也會在 Bing 搜尋 v7 資源的付費層中提供。

多服務資源

  • 您可以透過 Azure 入口網站取得該資源,直到將其刪除為止。
  • 針對您的應用程式,跨多個 Azure AI 服務使用相同的金鑰和端點。

建立應用程式並將其初始化

  1. 在您最愛的 IDE 或編輯器中建立新的 JavaScript 檔案,然後新增下列需求。

    const CognitiveServicesCredentials = require('@azure/ms-rest-azure-js').CognitiveServicesCredentials;
    const EntitySearchAPIClient = require('@azure/cognitiveservices-entitysearch');
    
  2. 使用您的訂用帳戶金鑰建立 CognitiveServicesCredentials 的執行個體。 然後,用它來建立搜尋用戶端的執行個體。

    let credentials = new CognitiveServicesCredentials('YOUR-ACCESS-KEY');
    let entitySearchApiClient = new EntitySearchAPIClient(credentials);
    

傳送要求並接收回應

  1. 使用 entitiesOperations.search() 傳送實體搜尋要求。 接收到回應後,請列印 queryContext、傳回的結果數,和第一個結果的描述。

    entitySearchApiClient.entitiesOperations.search('seahawks').then((result) => {
        console.log(result.queryContext);
        console.log(result.entities.value);
        console.log(result.entities.value[0].description);
    }).catch((err) => {
        throw err;
    });
    

後續步驟

使用本快速入門,透過適用於 Python 的 Bing 實體搜尋用戶端程式庫開始搜尋實體。 雖然 Bing 實體搜尋具有與大部分程式設計語言相容的 REST API,但此用戶端程式庫可提供簡單的方法,將服務整合到您的應用程式。 此範例的原始程式碼可以在 GitHub 上找到。

Prerequisites

建議您使用 Python 虛擬環境。 您可以使用 venv 模組來安裝和初始化虛擬環境。 您可以透過下列方式安裝 virtualenv:

python -m venv mytestenv

透過下列方式安裝 Bing 實體搜尋用戶端程式庫:

cd mytestenv
python -m pip install azure-cognitiveservices-search-entitysearch

建立 Azure 資源

藉由建立下列其中一項 Azure 資源,開始使用 Bing 實體搜尋 API。

Bing 實體搜尋資源

  • 您可以透過 Azure 入口網站取得該資源,直到將其刪除為止。
  • 使用免費定價層來試用服務,之後可升級至付費層以用於實際執行環境。
  • Bing 實體搜尋也會在 Bing 搜尋 v7 資源的付費層中提供。

多服務資源

  • 您可以透過 Azure 入口網站取得該資源,直到將其刪除為止。
  • 針對您的應用程式,跨多個 Azure AI 服務使用相同的金鑰和端點。

建立應用程式並將其初始化

  1. 在您慣用的 IDE 或編輯器中建立新的 Python 專案,以及新增下列匯入陳述式。

    from azure.cognitiveservices.search.entitysearch import EntitySearchClient
    from azure.cognitiveservices.search.entitysearch.models import Place, ErrorResponseException
    from msrest.authentication import CognitiveServicesCredentials
    
  2. 建立訂用帳戶金鑰和端點的變數。 以您的金鑰建立新的 CognitiveServicesCredentials 物件來具現化用戶端。

    subscription_key = "YOUR-SUBSCRIPTION-KEY"
    endpoint = "YOUR-ENDPOINT"
    client = EntitySearchclient(endpoint=endpoint, credentials=CognitiveServicesCredentials(subscription_key))
    

傳送搜尋要求並接收回應

  1. 使用 client.entities.search() 和搜尋查詢將搜尋要求傳送至 Bing 實體搜尋。

    entity_data = client.entities.search(query="Gibralter")
    
  2. 如果傳回實體,請將 entity_data.entities.value 轉換為清單,並列印第一個結果。

    if entity_data.entities.value:
    
        main_entities = [entity for entity in entity_data.entities.value
                         if entity.entity_presentation_info.entity_scenario == "DominantEntity"]
    
        if main_entities:
            print(main_entities[0].description)
    

後續步驟