快速入门:使用必应实体搜索客户端库

警告

2020 年 10 月 30 日,必应搜索 API 从 Azure AI 服务迁移到必应搜索服务。 本文档仅供参考。 有关更新的文档,请参阅 必应搜索 API 文档。 有关为必应搜索创建新 Azure 资源的说明,请参阅 通过 Azure 市场创建必应搜索资源。

使用此快速入门,开始用适用于 C# 的必应实体搜索客户端库进行实体搜索。 虽然必应实体搜索具有与大多数编程语言兼容的 REST API,但客户端库提供了将服务集成到应用程序中的简单方法。 可以在 GitHub 上找到此示例的源代码。

先决条件

若要将必应实体搜索客户端库添加到 Visual Studio 项目,请使用解决方案资源管理器 中的“管理 NuGet 包”选项,并添加 Microsoft.Azure.CognitiveServices.Search.EntitySearch 包。

创建 Azure 资源

要开始使用 Bing 实体搜索 API,请创建以下 Azure 资源之一。

必应实体搜索资源

多服务资源

  • 可通过 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 的必应实体搜索客户端库进行实体搜索。 虽然必应实体搜索具有与大多数编程语言兼容的 REST API,但客户端库提供了将服务集成到应用程序中的简单方法。 可以在 GitHub 上找到此示例的源代码。

先决条件

使用 Maven、Gradle 或其他依赖项管理系统安装必应实体搜索客户端库依赖项。 Maven POM 文件需要声明:

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

创建 Azure 资源

通过创建以下 Azure 资源之一开始使用必应实体搜索 API。

必应实体搜索资源

多服务资源

  • 可通过 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. 重写applyCredentialsFilter()函数,并以OkHttpClient.Builder对象作为参数。

      //...
      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 版必应实体搜索客户端库进行实体搜索。 虽然必应实体搜索具有与大多数编程语言兼容的 REST API,但客户端库提供了将服务集成到应用程序中的简单方法。 可以在 GitHub 上找到此示例的源代码。

先决条件

  • 最新版本的 Node.js
  • 适用于 JavaScript 的 必应实体搜索 SDK
    • 若要安装,请运行 npm install @azure/cognitiveservices-entitysearch
  • 用于认证客户端的 CognitiveServicesCredentials 包中的 @azure/ms-rest-azure-js 类。
    • 若要安装,请运行 npm install @azure/ms-rest-azure-js

创建 Azure 资源

要开始使用必应实体搜索 API,请创建以下 Azure 资源之一。

必应实体搜索资源

多服务资源

  • 可通过 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 中进行实体搜索。 虽然必应实体搜索具有与大多数编程语言兼容的 REST API,但客户端库提供了将服务集成到应用程序中的简单方法。 可以在 GitHub 上找到此示例的源代码。

先决条件

建议使用 Python 虚拟环境。 可以使用 venv 模块安装和初始化虚拟环境。 可以使用以下方法安装 virtualenv:

python -m venv mytestenv

安装必应实体搜索客户端库,请使用以下命令:

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

创建 Azure 资源

通过创建以下 Azure 资源之一来开始使用 Bing 实体搜索 API。

必应实体搜索资源

多服务资源

  • 可通过 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() 和搜索查询向必应实体搜索发送搜索请求。

    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)
    

后续步骤