通过 Visual Studio Code 开始使用 Azure 认知搜索Get started with Azure Cognitive Search using Visual Studio Code

本文介绍如何使用 Azure 认知搜索 REST APIVisual Studio Code 以交互方式构建 REST API 请求。This article explains how to formulate REST API requests interactively using the Azure Cognitive Search REST APIs and Visual Studio Code. 借助适用于 Azure 认知搜索的 Visual Studio Code 扩展(预览版)和这些说明,你可以在编写任何代码之前发送请求和查看响应。With the Visual Studio code extension for Azure Cognitive Search (preview) and these instructions, you can send requests and view responses before writing any code.

如果没有 Azure 订阅,可在开始前创建一个试用帐户If you don't have an Azure subscription, create a Trial before you begin.

重要

此功能目前处于公开预览状态。This feature is currently in public preview. 提供的预览版功能不附带服务级别协议,我们不建议将其用于生产工作负荷。Preview functionality is provided without a service level agreement, and is not recommended for production workloads. 有关详细信息,请参阅适用于 Azure 预览版的补充使用条款For more information, see Supplemental Terms of Use for Azure Previews.

先决条件Prerequisites

本快速入门需要以下服务和工具。The following services and tools are required for this quickstart.

安装扩展Install the extension

首先打开 VS CodeStart by opening VS Code. 选择活动栏上的“扩展”选项卡,然后搜索 Azure 认知搜索。Select the Extensions tab on the activity bar then search for Azure Cognitive Search. 在搜索结果中找到扩展,然后选择“安装”。Find the extension in the search results, and select Install.

VS Code 扩展窗格VS Code extension pane

或者,可以在 Web 浏览器中从 VS Code 市场安装 Azure 认知搜索扩展Alternatively, you can install the Azure Cognitive Search extension from the VS Code marketplace in a web browser.

如果尚未安装,活动栏上应会显示新的 Azure 选项卡。You should see a new Azure tab appear on the activity bar if you didn't already have it.

VS Code Azure 窗格VS Code Azure pane

连接到订阅Connect to your subscription

选择“登录到 Azure...”然后登录到 Azure 帐户。Select Sign in to Azure... and log into your Azure Account.

应会显示你的订阅。You should see your subscriptions appear. 选择订阅以查看订阅中的搜索服务的列表。Select the subscription to see a list of the search services in the subscription.

VS Code Azure 订阅VS Code Azure subscriptions

若要限制显示的订阅,请打开命令面板(Ctrl+Shift+P 或 Cmd+Shift+P),搜索 Azure 或选择订阅 。To limit the subscriptions displayed, open the command palette (Ctrl+Shift+P or Cmd+Shift+P) and search for Azure or Select Subscriptions. 还有一些命令可用于登录和注销 Azure 帐户。There are also commands available for signing in and out of your Azure account.

展开搜索服务时,你将看到每个认知搜索资源的树项:索引、数据源、索引器、技能集和同义词映射。When you expand the search service, you will see tree items for each of the Cognitive Search resources: indexes, data sources, indexers, skillsets, and synonym maps.

VS Code Azure 搜索树VS Code Azure search tree

可以扩展这些树项以显示搜索服务中的资源These tree items can be expanded to show any resources you have in your search service

1 - 创建索引1 - Create an index

若要开始使用 Azure 认知搜索,首先需要创建搜索索引。To get started with Azure Cognitive Search, you first need to create a search index. 这是使用创建索引 REST API 来完成的。This is done using the Create Index REST API.

使用 VS Code 扩展时,只需要考虑请求的正文。With the VS Code extension, you only need to worry about the body of the request. 在本快速入门中,我们提供了一个示例索引定义和相应的文档。For this quickstart, we provide a sample index definition and corresponding documents.

索引定义Index definition

以下索引定义是虚构酒店的示例架构。The index definition below is a sample schema for fictitious hotels.

fields 集合定义搜索索引中文档的结构。The fields collection defines the structure of documents in the search index. 每个字段都有一个数据类型和多个其他属性,这些属性决定了如何使用该字段。Each field has a data type and a number of additional attributes that determine how the field can be used.

{
    "name": "hotels-quickstart",
    "fields": [
        {
            "name": "HotelId",
            "type": "Edm.String",
            "key": true,
            "filterable": true
        },
        {
            "name": "HotelName",
            "type": "Edm.String",
            "searchable": true,
            "filterable": false,
            "sortable": true,
            "facetable": false
        },
        {
            "name": "Description",
            "type": "Edm.String",
            "searchable": true,
            "filterable": false,
            "sortable": false,
            "facetable": false,
            "analyzer": "en.lucene"
        },
        {
            "name": "Description_fr",
            "type": "Edm.String",
            "searchable": true,
            "filterable": false,
            "sortable": false,
            "facetable": false,
            "analyzer": "fr.lucene"
        },
        {
            "name": "Category",
            "type": "Edm.String",
            "searchable": true,
            "filterable": true,
            "sortable": true,
            "facetable": true
        },
        {
            "name": "Tags",
            "type": "Collection(Edm.String)",
            "searchable": true,
            "filterable": true,
            "sortable": false,
            "facetable": true
        },
        {
            "name": "ParkingIncluded",
            "type": "Edm.Boolean",
            "filterable": true,
            "sortable": true,
            "facetable": true
        },
        {
            "name": "LastRenovationDate",
            "type": "Edm.DateTimeOffset",
            "filterable": true,
            "sortable": true,
            "facetable": true
        },
        {
            "name": "Rating",
            "type": "Edm.Double",
            "filterable": true,
            "sortable": true,
            "facetable": true
        },
        {
            "name": "Address",
            "type": "Edm.ComplexType",
            "fields": [
                {
                    "name": "StreetAddress",
                    "type": "Edm.String",
                    "filterable": false,
                    "sortable": false,
                    "facetable": false,
                    "searchable": true
                },
                {
                    "name": "City",
                    "type": "Edm.String",
                    "searchable": true,
                    "filterable": true,
                    "sortable": true,
                    "facetable": true
                },
                {
                    "name": "StateProvince",
                    "type": "Edm.String",
                    "searchable": true,
                    "filterable": true,
                    "sortable": true,
                    "facetable": true
                },
                {
                    "name": "PostalCode",
                    "type": "Edm.String",
                    "searchable": true,
                    "filterable": true,
                    "sortable": true,
                    "facetable": true
                },
                {
                    "name": "Country",
                    "type": "Edm.String",
                    "searchable": true,
                    "filterable": true,
                    "sortable": true,
                    "facetable": true
                }
            ]
        }
    ],
    "suggesters": [
        {
            "name": "sg",
            "searchMode": "analyzingInfixMatching",
            "sourceFields": [
                "HotelName"
            ]
        }
    ]
}

若要创建新索引,请右键单击“索引”然后选择“创建新索引” 。To create a new index, right-click on Indexes and then select Create new index. 将弹出一个名称类似于 indexes-new-28c972f661.azsindex 的编辑器。An editor with a name similar to indexes-new-28c972f661.azsindex will pop up.

将上面的索引定义粘贴到窗口中。Paste the index definition from above into the window. 如果想要更新索引,请保存文件并在出现提示时选择“上传”。Save the file and select Upload when prompted if you want to update the index. 这将创建索引,并且该索引将在树状视图中可用。This will create the index and it will be available in the tree view.

创建索引的 Gif

如果索引定义有问题,会弹出错误消息,说明该错误。If there is a problem with your index definition, you should see an error message pop up explaining the error.

创建索引错误消息

如果发生这种情况,请修复问题并重新保存该文件。If this happens, fix the issue and resave the file.

2 - 加载文档2 - Load documents

创建索引和填充索引是分开的步骤。Creating the index and populating the index are separate steps. 在 Azure 认知搜索中,索引包含所有可搜索的数据。In Azure Cognitive Search, the index contains all searchable data. 在此场景中,数据以 JSON 文档的形式提供。In this scenario, the data is provided as JSON documents. 本任务将使用添加、更新或删除文档 REST APIThe Add, Update, or Delete Documents REST API is used for this task.

若要在 VS Code 中添加新文档:To add new documents in VS Code:

  1. 展开创建的 hotels-quickstart 索引。Expand the hotels-quickstart index you created. 右键单击“文档”并选择“创建新文档” 。Right-click on Documents and select Create new document.

    创建文档

  2. 这会打开一个已推断出索引架构的 JSON 编辑器。This will open up a JSON editor that has inferred the schema of your index.

    创建文档 JSON

  3. 粘贴下面的 JSON,并保存该文件。Paste in the JSON below and then save the file. 将打开一个提示,要求确认更改。A prompt will open up asking you to confirm your changes. 选择“上传”以保存更改。Select Upload to save the changes.

    {
        "HotelId": "1",
        "HotelName": "Secret Point Motel",
        "Description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.",
        "Category": "Boutique",
        "Tags": [ "pool", "air conditioning", "concierge" ],
        "ParkingIncluded": false,
        "LastRenovationDate": "1970-01-18T00:00:00Z",
        "Rating": 3.60,
        "Address": {
            "StreetAddress": "677 5th Ave",
            "City": "New York",
            "StateProvince": "NY",
            "PostalCode": "10022",
            "Country": "USA"
        } 
    }
    
  4. 为其余三个文档重复此过程Repeat this process for the three remaining documents

    文档 2:Document 2:

    {
        "HotelId": "2",
        "HotelName": "Twin Dome Motel",
        "Description": "The hotel is situated in a  nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts.",
        "Category": "Boutique",
        "Tags": [ "pool", "free wifi", "concierge" ],
        "ParkingIncluded": false,
        "LastRenovationDate": "1979-02-18T00:00:00Z",
        "Rating": 3.60,
        "Address": {
            "StreetAddress": "140 University Town Center Dr",
            "City": "Sarasota",
            "StateProvince": "FL",
            "PostalCode": "34243",
            "Country": "USA"
        } 
    }
    

    文档 3:Document 3:

    {
        "HotelId": "3",
        "HotelName": "Triple Landscape Hotel",
        "Description": "The Hotel stands out for its gastronomic excellence under the management of William Dough, who advises on and oversees all of the Hotel’s restaurant services.",
        "Category": "Resort and Spa",
        "Tags": [ "air conditioning", "bar", "continental breakfast" ],
        "ParkingIncluded": true,
        "LastRenovationDate": "2015-09-20T00:00:00Z",
        "Rating": 4.80,
        "Address": {
            "StreetAddress": "3393 Peachtree Rd",
            "City": "Atlanta",
            "StateProvince": "GA",
            "PostalCode": "30326",
            "Country": "USA"
        } 
    }
    

    文档 4:Document 4:

    {
        "HotelId": "4",
        "HotelName": "Sublime Cliff Hotel",
        "Description": "Sublime Cliff Hotel is located in the heart of the historic center of Sublime in an extremely vibrant and lively area within short walking distance to the sites and landmarks of the city and is surrounded by the extraordinary beauty of churches, buildings, shops and monuments. Sublime Cliff is part of a lovingly restored 1800 palace.",
        "Category": "Boutique",
        "Tags": [ "concierge", "view", "24-hour front desk service" ],
        "ParkingIncluded": true,
        "LastRenovationDate": "1960-02-06T00:00:00Z",
        "Rating": 4.60,
        "Address": {
            "StreetAddress": "7400 San Pedro Ave",
            "City": "San Antonio",
            "StateProvince": "TX",
            "PostalCode": "78216",
            "Country": "USA"
        }
    }
    

此时,你应该在“文档”部分看到所有四个文档。At this point, you should see all four documents available in the documents section.

上载所有文档后的状态

3 - 搜索索引3 - Search an index

现在,索引和文档集已加载,可以使用搜索文档 REST API 针对它们发出查询了。Now that the index and document set are loaded, you can issue queries against them using Search Documents REST API.

若要在 VS Code 执行此操作:To do this in VS Code:

  1. 右键单击要搜索的索引,然后选择“搜索索引”。Right-click the index you want to search and select Search index. 这会打开一个名称类似于 sandbox-b946dcda48.azs 的编辑器。This will open an editor with a name similar to sandbox-b946dcda48.azs.

    扩展的搜索视图

  2. 会自动填充一个简单查询。A simple query is autopopulated. 按“Ctrl+Alt+R”或“Cmd+Alt+R”以提交查询 。Press Ctrl+Alt+R or Cmd+Alt+R to submit the query. 你将在左侧的窗口中看到弹出的结果。You'll see the results pop up in a window to the left.

    扩展中的搜索结果

查询示例Example queries

尝试其他查询示例来了解语法。Try a few other query examples to get a feel for the syntax. 下面有另外四个可尝试的查询。There's four additional queries below for you to try. 可以将多个查询添加到同一个编辑器。You can add multiple queries to the same editor. 按“Ctrl+Alt+R”或“Cmd+Alt+R”时,光标所在的行决定了要提交的查询 。When you press Ctrl+Alt+R or Cmd+Alt+R, the line your cursor determines which query will be submitted.

并行查询和结果

在第一个查询中,只搜索特定字段 boutiqueselectIn the first query, we search boutique and select only certain fields. 最佳做法是通过 select 仅选择你需要的字段,因为回发不必要的数据可能会增加查询的延迟时间。It's a best practice to only select the fields you need because pulling back unnecessary data can add latency to your queries. 该查询还将 $count=true 设置为搜索结果的返回总数。The query also sets $count=true to return the total number of results with the search results.

// Query example 1 - Search `boutique` with select and return count
search=boutique&$count=true&$select=HotelId,HotelName,Rating,Category

在下一个查询中,我们指定搜索词 wifi,还包括一个筛选器,以仅返回状态等于 'FL' 的结果。In the next query, we specify the search term wifi and also include a filter to only return results where the state is equal to 'FL'. 还会按酒店的 Rating 对结果进行排序。Results are also ordered by the Hotel's Rating.

// Query example 2 - Search with filter, orderBy, select, and count
search=wifi&$filter=Address/StateProvince eq 'FL'&$select=HotelId,HotelName,Rating&$orderby=Rating desc

接下来,使用 searchFields 参数将搜索限制为单个可搜索字段。Next, the search is limited to a single searchable field using the searchFields parameter. 如果你知道自己只对某些字段中的匹配感兴趣,则很适合使用该选项来提高查询的效率。This is a great option to make your query more efficient if you know you're only interested in matches in certain fields.

// Query example 3 - Limit searchFields
search=submlime cliff&$select=HotelId,HotelName,Rating&searchFields=HotelName

查询中包含的另一个常见选项是 facetsAnother common option to include in a query is facets. 通过 facet,可在 UI 上构建筛选器,使用户能够轻松地了解可筛选出的值。Facets allow you to build out filters on your UI to make it easy for users to know what values they can filter down to.

// Query example 4 - Take the top two results, and show only HotelName and Category in the results
search=*&$select=HotelId,HotelName,Rating&searchFields=HotelName&facet=Category

在门户中打开索引Open index in the portal

若要在门户中查看搜索服务,请右键单击搜索服务的名称,然后选择“在门户中打开”。If you'd like to view your search service in the portal, right-click the name of the search service and select Open in Portal. 这会将你转到 Azure 门户中的搜索服务。This will take you to the search service in the Azure portal.

清理资源Clean up resources

在自己的订阅中操作时,最好在项目结束时确定是否仍需要已创建的资源。When you're working in your own subscription, it's a good idea at the end of a project to identify whether you still need the resources you created. 持续运行资源可能会产生费用。Resources left running can cost you money. 可以逐个删除资源,也可以删除资源组以删除整个资源集。You can delete resources individually or delete the resource group to delete the entire set of resources.

可以使用左侧导航窗格中的“所有资源”或“资源组”链接 ,在门户中查找和管理资源。You can find and manage resources in the portal, using the All resources or Resource groups link in the left-navigation pane.

如果使用的是免费服务,请记住只能设置三个索引、索引器和数据源。If you are using a free service, remember that you are limited to three indexes, indexers, and data sources. 可以在门户中删除单个项目,以不超出此限制。You can delete individual items in the portal to stay under the limit.

后续步骤Next steps

现在你已了解如何执行核心任务,你可以继续使用其他 REST API 调用来获取更高级的功能,例如索引器或设置将内容转换添加到索引的扩充管道Now that you know how to perform core tasks, you can move forward with additional REST API calls for more advanced features, such as indexers or setting up an enrichment pipeline that adds content transformations to indexing. 在下一步中,我们建议你访问以下链接:For your next step, we recommend the following link: