快速入门:使用必应自定义搜索客户端库

警告

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

开始使用适用于 C# 的必应自定义搜索客户端库。 请按照以下步骤安装程序包并试用基本任务的示例代码。 借助必应自定义搜索 API,可为关注的主题创建定制的无广告搜索体验。 可以在 GitHub 上找到此示例的源代码。

使用适用于 C# 的必应自定义搜索客户端库,可以执行以下操作:

  • 使用必应自定义搜索实例在网上查找搜索结果。

参考文档 | 库源代码 | 包 (NuGet) | 示例

先决条件

  • 必应自定义搜索实例。 请参阅快速入门:创建第一个必应自定义搜索实例,了解详细信息。
  • Microsoft .NET Core
  • 任何版本的 Visual Studio 2017 或更高版本
  • 如果使用的是 Linux/MacOS,则可使用 Mono 运行此应用程序。
  • 必应自定义搜索 NuGet 包。
    • 在 Visual Studio 中的解决方案资源管理器内,右键单击你的项目,并从菜单中选择“管理 NuGet 包”。 安装 Microsoft.Azure.CognitiveServices.Search.CustomSearch 包。 安装 NuGet 自定义搜索包还会安装以下程序集:
      • Microsoft.Rest.ClientRuntime
      • Microsoft.Rest.ClientRuntime.Azure
      • Newtonsoft.Json

创建 Azure 资源

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

必应自定义搜索资源

  • 在删除资源前,可通过 Azure 门户使用。
  • 使用免费定价层试用该服务,稍后升级到用于生产的付费层。

多服务资源

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

创建并初始化应用程序

  1. 在 Visual Studio 中创建新的 C# 控制台应用程序。 然后,将以下包添加到项目。

    using System;
    using System.Linq;
    using Microsoft.Azure.CognitiveServices.Search.CustomSearch;
    
  2. 在应用程序的 main 方法中,使用 API 密钥实例化搜索客户端。

    var client = new CustomSearchAPI(new ApiKeyServiceClientCredentials("YOUR-SUBSCRIPTION-KEY"));
    

发送搜索请求和接收响应

  1. 使用客户端的 SearchAsync() 方法发送搜索查询,并保存响应。 请务必将 YOUR-CUSTOM-CONFIG-ID 替换为实例的配置 ID(可在必应自定义搜索门户中找到该 ID)。 此示例将搜索“Xbox”。

    // This will look up a single query (Xbox).
    var webData = client.CustomInstance.SearchAsync(query: "Xbox", customConfig: Int32.Parse("YOUR-CUSTOM-CONFIG-ID")).Result;
    
  2. SearchAsync() 方法将返回 WebData 对象。 使用该对象循环访问找到的任何 WebPages。 此代码可查找第一个网页结果并打印网页的 NameURL

    if (webData?.WebPages?.Value?.Count > 0)
    {
        // find the first web page
        var firstWebPagesResult = webData.WebPages.Value.FirstOrDefault();
    
        if (firstWebPagesResult != null)
        {
            Console.WriteLine("Number of webpage results {0}", webData.WebPages.Value.Count);
            Console.WriteLine("First web page name: {0} ", firstWebPagesResult.Name);
            Console.WriteLine("First web page URL: {0} ", firstWebPagesResult.Url);
        }
        else
        {
            Console.WriteLine("Couldn't find web results!");
        }
    }
    else
    {
        Console.WriteLine("Didn't see any Web data..");
    }
    

后续步骤

开始使用适用于 Java 的必应自定义搜索客户端库。 请按照以下步骤安装程序包并试用基本任务的示例代码。 借助必应自定义搜索 API,可为关注的主题创建定制的无广告搜索体验。 可以在 GitHub 上找到此示例的源代码

使用适用于 Java 的必应自定义搜索客户端库,可以执行以下操作:

  • 使用必应自定义搜索实例在网上查找搜索结果。

参考文档 | 库源代码 | 项目 (Maven) | 示例

先决条件

创建 Azure 资源

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

必应自定义搜索资源

  • 在删除资源前,可通过 Azure 门户使用。
  • 使用免费定价层试用该服务,稍后升级到用于生产的付费层。

多服务资源

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

从资源获取密钥后,为密钥创建一个环境变量(名为 AZURE_BING_CUSTOM_SEARCH_API_KEY)。

创建新的 Gradle 项目

提示

如果使用 Gradle,则可在 Maven 中央存储库中找到客户端库以及其他依赖项管理器的详细信息。

在控制台窗口(例如 cmd、PowerShell 或 Bash)中,为应用创建一个新目录并导航到该目录。

mkdir myapp && cd myapp

从工作目录运行 gradle init 命令。 此命令创建 Gradle 的基本生成文件,包括 build.gradle.kts 文件,在运行时使用该文件配置应用程序。

gradle init --type basic

当提示你选择一个 DSL 时,选择 Kotlin

安装客户端库

找到 build.gradle.kts,并使用喜好的 IDE 或文本编辑器将其打开。 然后将以下生成配置复制到其中。 确保 dependencies 下包含客户端库:

plugins {
    java
    application
}
application {
    mainClassName = "main.java.BingCustomSearchSample"
}
repositories {
    mavenCentral()
}
dependencies {
    compile("org.slf4j:slf4j-simple:1.7.25")
    compile("com.microsoft.azure.cognitiveservices:azure-cognitiveservices-customsearch:1.0.2")
}

为示例应用创建一个文件夹。 在工作目录中运行以下命令:

mkdir src/main/java

导航到新文件夹,创建名为 BingCustomSearchSample.java 的文件。 打开它,并添加以下 import 语句:

package main.java;

import com.microsoft.azure.cognitiveservices.search.customsearch.BingCustomSearchAPI;
import com.microsoft.azure.cognitiveservices.search.customsearch.BingCustomSearchManager;
import com.microsoft.azure.cognitiveservices.search.customsearch.models.SearchResponse;
import com.microsoft.azure.cognitiveservices.search.customsearch.models.WebPage;

创建名为 BingCustomSearchSample 的类

public class BingCustomSearchSample {
}

在该类中创建一个 main 方法,并为资源的密钥创建变量。 如果在启动应用程序后创建了环境变量,请关闭再重新打开运行该应用程序的编辑器、IDE 或 shell,然后才能访问该变量。 稍后将定义方法。

public static void main(String[] args) {
    try {

        // Set the BING_CUSTOM_SEARCH_SUBSCRIPTION_KEY and AZURE_BING_SAMPLES_CUSTOM_CONFIG_ID environment variables, 
        // then reopen your command prompt or IDE. If not, you may get an API key not found exception.
        final String subscriptionKey = System.getenv("BING_CUSTOM_SEARCH_SUBSCRIPTION_KEY");
        // If you do not have a customConfigId, you can also use 1 as your value when setting your environment variable.
        final String customConfigId = System.getenv("AZURE_BING_SAMPLES_CUSTOM_CONFIG_ID");

        BingCustomSearchAPI client = BingCustomSearchManager.authenticate(subscriptionKey);

        runSample(client, customConfigId);
    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
}

对象模型

必应自定义搜索客户端是一个 BingCustomSearchAPI 对象,该对象通过 BingCustomSearchManager 对象的 authenticate() 方法创建。 可以使用客户端的 BingCustomInstances.search() 方法发送搜索请求。

API 响应是一个 SearchResponse 对象,该对象包含有关搜索查询的信息以及搜索结果。

代码示例

这些代码片段演示如何使用适用于 Java 的必应自定义搜索客户端库执行以下任务:

验证客户端

main 方法应该包含一个使用密钥的 BingCustomSearchManager 对象,并调用其 authenticate()

BingCustomSearchAPI client = BingCustomSearchManager.authenticate(subscriptionKey);

从自定义搜索实例获取搜索结果

使用客户端的 BingCustomInstances.search() 函数,向自定义实例发送搜索查询。 将 withCustomConfig 设置为自定义配置 ID,或默认设置为 1。 从 API 获得响应以后,检查是否发现了任何搜索结果。 如果发现了搜索结果,请通过调用响应的 webPages().value().get() 函数来获取第一个搜索结果,并输出结果的名称和 URL。

public static boolean runSample(BingCustomSearchAPI client, String customConfigId) {
    try {

        // This will search for "Xbox" using Bing Custom Search 
        //and print out name and url for the first web page in the results list

        System.out.println("Searching for Query: \"Xbox\"");
        SearchResponse webData = client.bingCustomInstances().search()
            .withCustomConfig(customConfigId != null ? Long.valueOf(customConfigId) : 0)
            .withQuery("Xbox")
            .withMarket("en-us")
            .execute();

        if (webData != null && webData.webPages() != null && webData.webPages().value().size() > 0)
        {
            // find the first web page
            WebPage firstWebPagesResult = webData.webPages().value().get(0);

            if (firstWebPagesResult != null) {
                System.out.println(String.format("Webpage Results#%d", webData.webPages().value().size()));
                System.out.println(String.format("First web page name: %s ", firstWebPagesResult.name()));
                System.out.println(String.format("First web page URL: %s ", firstWebPagesResult.url()));
            } else {
                System.out.println("Couldn't find web results!");
            }
        } else {
            System.out.println("Didn't see any Web data..");
        }

        return true;
    } catch (Exception f) {
        System.out.println(f.getMessage());
        f.printStackTrace();
    }
    return false;
}

运行应用程序

在项目的主目录中使用以下命令来生成应用:

gradle build

使用 run 目标运行应用程序:

gradle run

清理资源

如果想要清理并移除 Azure AI 服务订阅,可以删除资源或资源组。 删除资源组同时也会删除与之相关联的任何其他资源。

后续步骤

开始使用适用于 Python 的必应自定义搜索客户端库。 请按照以下步骤安装程序包并试用基本任务的示例代码。 借助必应自定义搜索 API,可为关注的主题创建定制的无广告搜索体验。此示例的源代码可以在 GitHub 上找到。

使用适用于 Python 的必应自定义搜索客户端库,可以执行以下操作:

  • 使用必应自定义搜索实例在网上查找搜索结果。

参考文档 | 库源代码 | 包 (PyPi) | 示例

先决条件

创建 Azure 资源

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

必应自定义搜索资源

  • 在删除资源前,可通过 Azure 门户使用。
  • 使用免费定价层试用该服务,稍后升级到用于生产的付费层。

多服务资源

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

安装 Python 客户端库

使用以下命令安装必应自定义搜索客户端库。

python -m pip install azure-cognitiveservices-search-customsearch

创建新应用程序

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

from azure.cognitiveservices.search.customsearch import CustomSearchClient
from msrest.authentication import CognitiveServicesCredentials

创建搜索客户端并发送请求

  1. 为你的订阅密钥和终结点创建变量。

    subscription_key = 'your-subscription-key'
    endpoint = 'your-endpoint'
    
  2. CognitiveServicesCredentials 对象与订阅密钥配合使用,创建 CustomSearchClient 的实例。

    client = CustomSearchClient(endpoint=endpoint, credentials=CognitiveServicesCredentials(subscription_key))
    
  3. 发送包含 client.custom_instance.search() 的搜索请求。 将搜索词追加​​到 query 参数,并将 custom_config 设置为自定义配置 ID,以便使用搜索实例。 可以从必应自定义搜索门户获取 ID,只需单击“生产”选项卡即可。

    web_data = client.custom_instance.search(query="xbox", custom_config="your-configuration-id")
    

查看搜索结果

如果找到网页搜索结果,请获取第一个结果并输出其名称、URL 和找到的总网页数。

if web_data.web_pages.value:
    first_web_result = web_data.web_pages.value[0]
    print("Web Pages result count: {}".format(len(web_data.web_pages.value)))
    print("First Web Page name: {}".format(first_web_result.name))
    print("First Web Page url: {}".format(first_web_result.url))
else:
    print("Didn't see any web data..")

后续步骤