快速入门:使用 REST API 在 Postman 中创建 Azure 认知搜索索引Quickstart: Create an Azure Cognitive Search index in Postman using REST APIs

若要探索 Azure 认知搜索 REST API,最轻松的方式之一是使用 Postman 或其他 Web 测试工具来构建 HTTP 请求并检查响应。One of the easiest ways to explore the Azure Cognitive Search REST APIs is using Postman or another web testing tool to formulate HTTP requests and inspect the responses. 在编写任何代码之前,可以使用适当的工具按照这些说明发送请求和查看响应。With the right tools and these instructions, you can send requests and view responses before writing any code.

本文说明如何以交互方式表述请求。This article explains how to formulate requests interactively. 或者,你可以下载并导入 Postman 集合以使用预定义的请求。Alternatively, you can download and import a Postman collection to use predefined requests.

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


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

获取密钥和 URLGet a key and URL

REST 调用需要在每个请求中使用服务 URL 和访问密钥。REST calls require the service URL and an access key on every request. 搜索服务是使用这二者创建的,因此,如果向订阅添加了 Azure 认知搜索,则请按以下步骤获取必需信息:A search service is created with both, so if you added Azure Cognitive Search to your subscription, follow these steps to get the necessary information:

  1. 登录到 Azure 门户,在搜索服务的“概述”页中获取 URL。 Sign in to the Azure portal, and in your search service Overview page, get the URL. 示例终结点可能类似于 https://mydemo.search.azure.cnAn example endpoint might look like https://mydemo.search.azure.cn.

  2. 在“设置” > “密钥”中,获取有关该服务的完全权限的管理员密钥 。In Settings > Keys, get an admin key for full rights on the service. 有两个可交换的管理员密钥,为保证业务连续性而提供,以防需要滚动一个密钥。There are two interchangeable admin keys, provided for business continuity in case you need to roll one over. 可以在请求中使用主要或辅助密钥来添加、修改和删除对象。You can use either the primary or secondary key on requests for adding, modifying, and deleting objects.

获取 HTTP 终结点和访问密钥Get an HTTP endpoint and access key

所有请求对发送到服务的每个请求都需要 API 密钥。All requests require an api-key on every request sent to your service. 具有有效的密钥可以在发送请求的应用程序与处理请求的服务之间建立信任关系,这种信任关系以每个请求为基础。Having a valid key establishes trust, on a per request basis, between the application sending the request and the service that handles it.

在本部分中,将使用所选的 Web 工具来与 Azure 认知搜索建立连接。In this section, use your web tool of choice to set up connections to Azure Cognitive Search. 每个工具都会持久保留会话的请求标头信息,这意味着,只需输入 api-key 和 Content-Type 一次即可。Each tool persists request header information for the session, which means you only have to enter the api-key and Content-Type once.

使用任一工具都需要选择一个命令(GET、POST、PUT 等)并提供 URL 终结点;对于某些任务,需要在请求正文中提供 JSON。For either tool, you need to choose a command (GET, POST, PUT, and so forth), provide a URL endpoint, and for some tasks, provide JSON in the body of the request. 将搜索服务名称 (YOUR-SEARCH-SERVICE-NAME) 替换为一个有效值。Replace the search service name (YOUR-SEARCH-SERVICE-NAME) with a valid value. 添加 $select=name 以便仅返回每个索引的名称。Add $select=name to return just the name of each index.


请注意 HTTPS 前缀、服务的名称、对象(在本例中为索引集合)的名称和 api-versionNotice the HTTPS prefix, the name of the service, the name of an object (in this case, the indexes collection), and the api-version. api-version 是必需的小写字符串;对于当前版本,它指定为 ?api-version=2019-05-06The api-version is a required, lowercase string specified as ?api-version=2019-05-06 for the current version. API 版本定期更新。API versions are updated regularly. 将 api-version 包括在每个请求中即可完全控制要使用的版本。Including the api-version on each request gives you full control over which one is used.

请求标头组合包括两个元素:内容类型,以及用于在 Azure 认知搜索中进行身份验证的 api-key。Request header composition includes two elements, content type, plus the api-key used to authenticate to Azure Cognitive Search. 将管理员 API 密钥 (YOUR-AZURE-SEARCH-ADMIN-API-KEY) 替换为一个有效值。Replace the admin API key (YOUR-AZURE-SEARCH-ADMIN-API-KEY) with a valid value.

Content-Type: application/json

在 Postman 中,构建如以下屏幕截图所示的请求。In Postman, formulate a request that looks like the following screenshot. 选择“GET”作为谓词,提供 URL,然后单击“发送”。 Choose GET as the verb, provide the URL, and click Send. 此命令连接到 Azure 认知搜索,读取索引集合,并在成功连接后返回 HTTP 状态代码 200。This command connects to Azure Cognitive Search, reads the indexes collection, and returns HTTP status code 200 on a successful connection. 如果服务已有索引,则响应还会包含索引定义。If your service has indexes already, the response will also include index definitions.

Postman 请求 URL 和标头Postman request URL and header

1 - 创建索引1 - Create an index

在 Azure 认知搜索中,通常会先创建索引,然后再连同数据一起加载索引。In Azure Cognitive Search, you usually create the index before loading it with data. 本任务将使用创建索引 REST APIThe Create Index REST API is used for this task.

需扩展 URL 以包含 hotels 索引名称。The URL is extended to include the hotels index name.

为此,请在 Postman 中:To do this in Postman:

  1. 将谓词更改为“PUT”。 Change the verb to PUT.

  2. 复制此 URL https://<YOUR-SEARCH-SERVICE-NAME>.search.azure.cn/indexes/hotels-quickstart?api-version=2019-05-06Copy in this URL https://<YOUR-SEARCH-SERVICE-NAME>.search.azure.cn/indexes/hotels-quickstart?api-version=2019-05-06.

  3. 在请求正文中提供索引定义(下方提供了可直接复制的代码)。Provide the index definition (copy-ready code is provided below) in the body of the request.

  4. 单击“Send” 。Click Send.

在请求正文中为 JSON 文档编制索引Index JSON document in request body

索引定义Index definition

字段集合定义文档结构。The fields collection defines document structure. 每个文档必须包含这些字段,每个字段必须具有一个数据类型。Each document must have these fields, and each field must have a data type. 字符串字段用于全文搜索,因此,如果要求数值数据可供搜索,则需将该内容强制转换为字符串。String fields are used in full text search, so you might want to cast numeric data as strings if you need that content to be searchable.

字段的属性决定了允许的操作。Attributes on the field determine allowed action. 默认情况下,REST API 允许很多操作。The REST APIs allow many actions by default. 例如,默认情况下,所有字符串均可供搜索、检索、筛选、分面。For example, all strings are searchable, retrievable, filterable, and facetable by default. 通常,仅当需要禁用某种行为时,才要设置属性。Often, you only have to set attributes when you need to turn off a behavior.

    "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": "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}

提交此请求后,会获得 HTTP 201 响应,指示索引已成功创建。When you submit this request, you should get an HTTP 201 response, indicating the index was created successfully. 可以在门户中验证此操作,但请注意,门户页有刷新时间间隔,因此可能需要等待一到两分钟。You can verify this action in the portal, but note that the portal page has refresh intervals so it could take a minute or two to catch up.


如果收到 HTTP 504,请验证该 URL 是否指定了 HTTPS。If you get HTTP 504, verify the URL specifies HTTPS. 如果看到 HTTP 400 或 404,请检查请求正文,以验证是否没有复制粘贴错误。If you see HTTP 400 or 404, check the request body to verify there were no copy-paste errors. HTTP 403 通常指示 api-key 有问题(密钥无效或指定 api-key 的方式有语法问题)。An HTTP 403 typically indicates a problem with the api-key (either an invalid key or a syntax problem with how the api-key is specified).

2 - 加载文档2 - Load documents

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

需扩展 URL 以包含 docs 集合与 index 操作。The URL is extended to include the docs collections and index operation.

为此,请在 Postman 中:To do this in Postman:

  1. 将谓词更改为 POST。Change the verb to POST.

  2. 复制此 URL https://<YOUR-SEARCH-SERVICE-NAME>.search.azure.cn/indexes/hotels-quickstart/docs/index?api-version=2019-05-06Copy in this URL https://<YOUR-SEARCH-SERVICE-NAME>.search.azure.cn/indexes/hotels-quickstart/docs/index?api-version=2019-05-06.

  3. 在请求的正文中提供 JSON 文档(复制就绪代码如下)。Provide the JSON documents (copy-ready code is below) in the body of the request.

  4. 单击“Send” 。Click Send.

请求正文中的 JSON 文档JSON documents in request body

要载入索引的 JSON 文档JSON documents to load into the index

请求正文包含四个要添加到 hotels 索引的文档。The Request Body contains four documents to be added to the hotels index.

    "value": [
    "@search.action": "upload",
    "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,
        "StreetAddress": "677 5th Ave",
        "City": "New York",
        "StateProvince": "NY",
        "PostalCode": "10022",
        "Country": "USA"
    "@search.action": "upload",
    "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,
        "StreetAddress": "140 University Town Center Dr",
        "City": "Sarasota",
        "StateProvince": "FL",
        "PostalCode": "34243",
        "Country": "USA"
    "@search.action": "upload",
    "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,
        "StreetAddress": "3393 Peachtree Rd",
        "City": "Atlanta",
        "StateProvince": "GA",
        "PostalCode": "30326",
        "Country": "USA"
    "@search.action": "upload",
    "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,
        "StreetAddress": "7400 San Pedro Ave",
        "City": "San Antonio",
        "StateProvince": "TX",
        "PostalCode": "78216",
        "Country": "USA"

在几秒钟内,应在会话列表中看到 HTTP 201 响应。In a few seconds, you should see an HTTP 201 response in the session list. 这指示已成功创建文档。This indicates the documents were created successfully.

如果收到 207,则指示至少有一个文档无法上传。If you get a 207, at least one document failed to upload. 如果收到 404,则表示请求的标头或正文有语法错误:请验证是否已更改终结点,使之包括 /docs/indexIf you get a 404, you have a syntax error in either the header or body of the request: verify you changed the endpoint to include /docs/index.


对于所选数据源,可以选择备用的 indexer 方法,以便简化并减少进行索引操作所需的代码量。For selected data sources, you can choose the alternative indexer approach which simplifies and reduces the amount of code required for indexing. 有关详细信息,请参阅 Indexer operations(Indexer 操作)。For more information, see Indexer operations.

3 - 搜索索引3 - Search an index

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

需扩展 URL,以包含使用搜索运算符指定的查询表达式。The URL is extended to include a query expression, specified using the search operator.

为此,请在 Postman 中:To do this in Postman:

  1. 将谓词更改为 GETChange the verb to GET.

  2. 复制此 URL https://<YOUR-SEARCH-SERVICE-NAME>.search.azure.cn/indexes/hotels-quickstart/docs?search=*&$count=true&api-version=2019-05-06Copy in this URL https://<YOUR-SEARCH-SERVICE-NAME>.search.azure.cn/indexes/hotels-quickstart/docs?search=*&$count=true&api-version=2019-05-06.

  3. 单击“Send” 。Click Send.

此查询为空,在搜索结果中返回文档的计数。This query is an empty and returns a count of the documents in the search results. 在单击“发送”后,请求和响应应类似于以下针对 Postman 的屏幕截图 。The request and response should look similar to the following screenshot for Postman after you click Send. 状态代码应为 200。The status code should be 200.

使用 URL 上的搜索字符串 GETGET with search string on the URL

请尝试其他几个查询示例,以大致了解语法。Try a few other query examples to get a feel for the syntax. 可以执行字符串搜索、原义 $filter 查询、限制结果集、将搜索范围限定为特定的字段,等待。You can do a string search, verbatim $filter queries, limit the results set, scope the search to specific fields, and more.

将当前 URL 替换为以下 URL,并每次单击“发送”以查看结果 。Swap out the current URL with the ones below, clicking Send each time to view the results.

# Query example 1 - Search on restaurant and wifi
# Return only the HotelName, Description, and Tags fields
https://<YOUR-SEARCH-SERVICE>.search.azure.cn/indexes/hotels-quickstart/docs?search=restaurant wifi&$count=true&$select=HotelName,Description,Tags&api-version=2019-05-06

# Query example 2 - Apply a filter to the index to find hotels rated 4 or highter
# Returns the HotelName and Rating. Two documents match
https://<YOUR-SEARCH-SERVICE>.search.azure.cn/indexes/hotels-quickstart/docs?search=*&$filter=Rating gt 4&$select=HotelName,Rating&api-version=2019-05-06

# Query example 3 - Take the top two results, and show only HotelName and Category in the results

# Query example 4 - Sort by a specific field (Address/City) in ascending order
https://<YOUR-SEARCH-SERVICE>.search.azure.cn/indexes/hotels-quickstart/docs?search=pool&$orderby=Address/City asc&$select=HotelName, Address/City, Tags, Rating&api-version=2019-05-06

获取索引属性Get index properties

还可以使用获取统计信息来查询文档计数和索引大小:You can also use Get Statistics to query for document counts and index size:


向 URL 添加 /stats 会返回索引信息。Adding /stats to your URL returns index information. 在 Postman 中,请求应如下所示,响应包括文档计数和所用空间(以字节为单位)。In Postman, your request should look similar to the following, and the response includes a document count and space used in bytes.

获取索引信息Get index information

请注意,api-version 语法有所不同。Notice that the api-version syntax differs. 对于此请求,请使用 ? 来追加 api-version。For this request, use ? to append the api-version. ? 将 URL 路径与查询字符串分隔开,而 & 将查询字符串中的每个“名称=值”对分隔开。The ? separates the URL path from the query string, while & separates each 'name=value' pair in the query string. 就此查询来说,api-version 是查询字符串中的第一个项,也是唯一项。For this query, api-version is the first and only item in the query string.

清理资源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 a cognitive search pipeline. 在下一步中,我们建议你访问以下链接:For your next step, we recommend the following link: