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

警告

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

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

先决条件

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

创建 Azure 资源

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

必应实体搜索资源

  • 在删除资源前,可通过 Azure 门户使用。
  • 使用免费定价层试用该服务,稍后升级到用于生产的付费层。
  • 必应实体搜索也在必应搜索 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 的必应实体搜索客户端库来搜索实体。 虽然必应实体搜索具有与大多数编程语言兼容的 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 门户使用。
  • 使用免费定价层试用该服务,稍后升级到用于生产的付费层。
  • 必应实体搜索也在必应搜索 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. 重写 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
  • @azure/ms-rest-azure-js 包中的 CognitiveServicesCredentials 类,用于对客户端进行身份验证。
    • 若要安装,请运行 npm install @azure/ms-rest-azure-js

创建 Azure 资源

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

必应实体搜索资源

  • 在删除资源前,可通过 Azure 门户使用。
  • 使用免费定价层试用该服务,稍后升级到用于生产的付费层。
  • 必应实体搜索也在必应搜索 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 的必应实体搜索客户端库来搜索实体。 虽然必应实体搜索具有与大多数编程语言兼容的 REST API,但该客户端库提供了一种简单方法来将服务集成到应用程序中。 可以在 GitHub 上找到此示例的源代码。

先决条件

建议使用 Python 虚拟环境。 可以使用 venv 模块安装并初始化虚拟环境。 可以使用以下命令安装 virtualenv:

python -m venv mytestenv

通过以下操作安装必应实体搜索客户端库:

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

创建 Azure 资源

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

必应实体搜索资源

  • 在删除资源前,可通过 Azure 门户使用。
  • 使用免费定价层试用该服务,稍后升级到用于生产的付费层。
  • 必应实体搜索也在必应搜索 v7 资源的付费层中提供。

多服务资源

  • 在删除资源前,可通过 Azure 门户使用。
  • 在多个 Azure AI 服务中对应用程序使用相同的密钥和终结点。

创建并初始化应用程序

  1. 在你喜欢使用的 IDE 或编辑器中创建新的 Python 文件,然后添加以下 import 语句。

    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)
    

后续步骤