Azure AI 搜尋服務 JavaScript 用戶端函式庫 - 版本 13.1.0

Azure AI 搜尋服務(前稱「Azure 認知搜尋」)是一個由 AI 驅動的資訊檢索平台,協助開發者打造豐富的搜尋體驗與結合大型語言模型與企業資料的生成式 AI 應用程式。

Azure AI 搜尋服務非常適合下列應用程式案例:

  • 將不同的內容類型合併成單一可搜尋的索引。 若要填入索引,您可以推送包含內容的 JSON 檔,或如果您的數據已在 Azure 中,請建立索引器來自動提取數據。
  • 將技能集附加至索引器,以從影像和非結構化檔建立可搜尋的內容。 技能集會利用 Azure AI Services 中的 API 進行內建 OCR、實體辨識、關鍵片語擷取、語言偵測、文字翻譯和情感分析。 您也可以新增自定義技能,以在數據擷取期間整合內容的外部處理。
  • 在搜尋用戶端應用程式中,實作類似商業 Web 搜尋引擎和聊天樣式應用程式的查詢邏輯和用戶體驗。

使用用戶端程式庫來 @azure/search-documents :

  • 使用向量、關鍵詞和混合式查詢表單提交查詢。
  • 針對元數據、地理空間搜尋、多面向導覽或根據篩選準則縮小結果,實作篩選的查詢。
  • 建立和管理搜尋索引。
  • 在搜尋索引中上傳和更新檔。
  • 建立和管理將數據從 Azure 提取到索引的索引器。
  • 建立和管理將 AI 擴充新增至數據擷取的技能集。
  • 建立及管理進階文字分析或多語種內容的分析器。
  • 透過語意排名和評分配置檔將結果優化,以納入商業規則或新鮮度。

主要連結:

開始

安裝 @azure/search-documents 套件

npm install @azure/search-documents

版本 13.1.0 預設鎖定 2026-10-01 GA 服務 API。 從 13.0.0 版本升級時,請檢視 GA-to-GA 的破壞性變更。 更新後的 TypeScript 與 JavaScript 範例可在 範例/v13 中取得。

目前支持的環境

如需詳細資訊,請參閱我們的支援原則。

先決條件

若要建立新的搜尋服務,您可以使用 Azure 入口網站、 Azure PowerShell 或 Azure CLI。 以下是使用 Azure CLI 建立免費實例以開始使用的範例:

az search service create --name <mysearch> --resource-group <mysearch-rg> --sku free --location westus

如需可用選項的詳細資訊,請參閱 選擇定價層 。

驗證用戶端

要與搜尋服務互動,請建立適當的客戶端: SearchClient 文件、 SearchIndexClient 索引與知識資源、 SearchIndexerClient 資料來源/索引器/技能組,或 KnowledgeRetrievalClient 知識庫檢索。 若要具現化用戶端物件,您需要 端點 和 Azure 角色 或 API 金鑰。 您可以參閱檔案,以取得搜尋服務支援 驗證方法 的詳細資訊。

取得 API 金鑰

API 金鑰可能是一種較容易開始的方法,因為它不需要預先存在的角色指派。

您可以從 Azure 入口網站中的搜尋服務取得端點和 API 金鑰。 請參閱 文件 ,以取得如何取得 API 金鑰的指示。

或者,您可以使用下列 Azure CLI 命令,從搜尋服務擷取 API 金鑰:

az search admin-key show --resource-group <your-resource-group-name> --service-name <your-resource-name>

有兩種類型的金鑰可用來存取搜尋服務: admin(讀取-寫入) 和 查詢(唯讀) 金鑰。 限制用戶端應用程式中的存取和作業,對於保護服務上的搜尋資產至關重要。 請一律針對源自用戶端應用程式的任何查詢使用查詢金鑰,而不是系統管理密鑰。

注意:上述範例 Azure CLI 片段會取得管理金鑰,方便開始探索 API,但必須謹慎管理。

有了 API 金鑰之後,您可以使用它,如下所示:

import {
  SearchClient,
  AzureKeyCredential,
  SearchIndexClient,
  SearchIndexerClient,
  KnowledgeRetrievalClient,
} from "@azure/search-documents";

// To query and manipulate documents
const searchClient = new SearchClient(
  "<endpoint>",
  "<indexName>",
  new AzureKeyCredential("<apiKey>"),
);

// To manage indexes and synonymmaps
const indexClient = new SearchIndexClient("<endpoint>", new AzureKeyCredential("<apiKey>"));

// To manage indexers, datasources and skillsets
const indexerClient = new SearchIndexerClient("<endpoint>", new AzureKeyCredential("<apiKey>"));

// To retrieve from a knowledge base
const knowledgeRetrievalClient = new KnowledgeRetrievalClient(
  "<endpoint>",
  "<knowledgeBaseName>",
  new AzureKeyCredential("<apiKey>"),
);

在國家雲端中驗證

若要在 國家雲端中進行驗證,您必須對用戶端設定進行下列新增:

  • 將AudienceSearchClientOptions
import { DefaultAzureCredential } from "@azure/identity";
import {
  SearchClient,
  KnownSearchAudience,
  SearchIndexClient,
  SearchIndexerClient,
  KnowledgeRetrievalClient,
} from "@azure/search-documents";

const credential = new DefaultAzureCredential({
  authorityHost: "https://login.chinacloudapi.cn",
});

// To query and manipulate documents
const searchClient = new SearchClient("<endpoint>", "<indexName>", credential, {
  audience: KnownSearchAudience.AzureChina,
});

// To manage indexes and synonymmaps
const indexClient = new SearchIndexClient("<endpoint>", credential, {
  audience: KnownSearchAudience.AzureChina,
});

// To manage indexers, datasources and skillsets
const indexerClient = new SearchIndexerClient("<endpoint>", credential, {
  audience: KnownSearchAudience.AzureChina,
});

// To retrieve from a knowledge base
const knowledgeRetrievalClient = new KnowledgeRetrievalClient(
  "<endpoint>",
  "<knowledgeBaseName>",
  credential,
  { audience: KnownSearchAudience.AzureChina },
);

重要概念

Azure AI 搜尋服務包含一或多個索引,這些索引會以 JSON 檔的形式持續儲存可搜尋的數據。 (如果你是搜尋新手,可以粗略地將索引與資料庫資料表作類比。)@azure/search-documents用戶端函式庫透過四種主要用戶端類型公開這些資源的操作。

注意:瀏覽器使用取決於所選搜尋操作及資源是否已設定 CORS。 檔案知識來源與知識庫會揭露 CORS 設定,但許多管理操作是針對受信任的伺服器端應用程式設計的。

TypeScript/JavaScript 特定概念

檔

儲存在搜尋索引內的專案。 此文件的形狀在索引中使用屬性 fields 進行描述。 每個都有 SearchField 名稱、資料類型和其他中繼資料,例如是否可搜尋或可篩選。

分頁

一般而言,您只希望一次 向使用者顯示搜尋結果的子集 。 若要支援此專案,您可以使用 top和 參數 skipincludeTotalCount ,在搜尋結果上方提供分頁體驗。

檔欄位編碼

索引中支援的資料型別 會映射到 API 請求/回應中的 JSON 型別。 JS 用戶端連結庫會保留這些大部分相同,但有一些例外:

  • Edm.DateTimeOffset 被轉換成 JS Date。
  • Edm.GeographyPoint 會轉換為 GeographyPoint 用戶端函式庫匯出的類型。
  • 類型 (NaN、Infinity、-Infinity) 的number特殊值會在 REST API 中序列化為字串,但會由用戶端程式庫轉換回。number

注意:資料型別是根據值轉換,而非索引結構中的欄位類型。 這表示如果您有ISO8601 Date 字串(例如“2020-03-06T18:48:27.896Z”)作為字段的值,則不論您儲存在架構中的方式為何,都會轉換成 Date。

例子

以下示例演示了基本知識 - 請 查看我們的示例 以獲取更多信息。

以下範例使用穩定 2026-10-01 服務 API,這是用戶端的預設。 它們擴展了現有的索引、索引器、知識來源與檢索工作流程,而非需要另行的客戶端。

為了完整可執行的工作流程, 範例來源 也涵蓋索引 SQL 內容欄位、私有擷取與服務選擇分析器、內容理解影像描述模型與語意區塊、服務/索引器執行時預算,以及搜尋自有的引用 URL。 可選的資源設定與先決條件列於 sample.env。

尋找類似文件

搭配現有的文件鍵使用 moreLikeThis ,且省略搜尋文字。 明確選取頂層可搜尋的文字欄位:複雜欄位不支援此操作。 索引必須包含其他文件以回傳有用的匹配。

import { SearchClient } from "@azure/search-documents";
import { DefaultAzureCredential } from "@azure/identity";

const client = new SearchClient("<endpoint>", "<indexName>", new DefaultAzureCredential());

const response = await client.search(undefined, {
  moreLikeThis: "1",
  searchFields: ["hotelName", "description"],
  select: ["hotelId", "hotelName"],
  top: 5,
});
for await (const result of response.results) {
  console.log(result.document);
}

設定知識庫

使用已填入且已設定語意搜尋的知識來源。 部署已配置的聊天模型,並在 Azure OpenAI 資源上授予搜尋服務的受管理身份認知服務 OpenAI 使用者權限。 部署名稱與模型名稱是不同的設定;部署名稱可以有自訂名稱。 呼叫者需要 搜尋服務貢獻者 來管理知識庫。

儲存的指令、輸出模式與推理努力可以在不替換知識來源的情況下更新。 answerSynthesis 使用已設定的模型; extractiveData 回傳擷取後的內容,無需合成答案。 GA 推理模式包括 minimal、 、 low和 medium。 明確的請求意圖可繞過模型查詢規劃。

import { SearchIndexClient } from "@azure/search-documents";
import { DefaultAzureCredential } from "@azure/identity";

const client = new SearchIndexClient("<endpoint>", new DefaultAzureCredential());

const knowledgeBase = await client.createKnowledgeBase({
  name: "hotel-knowledge-base",
  knowledgeSources: [{ name: "<existingKnowledgeSourceName>" }],
  models: [
    {
      kind: "azureOpenAI",
      azureOpenAIParameters: {
        resourceUrl: "<azureOpenAIEndpoint>",
        deploymentId: "<chatDeploymentName>",
        modelName: "gpt-5.4-mini",
      },
    },
  ],
  retrievalReasoningEffort: { kind: "low" },
  outputMode: "answerSynthesis",
  retrievalInstructions: "Prioritize hotel amenities and pricing information.",
  answerInstructions: "Answer concisely and cite the supporting sources.",
});

knowledgeBase.outputMode = "extractiveData";
await client.createOrUpdateKnowledgeBase(knowledgeBase);

帶有分頁控制項的資源清單

依名稱前綴篩選初始清單,並讓 SDK 跟隨不透明的續集連結。 SearchIndexClient呼叫器顯示 byPage()。 現有的同義詞映射、索引器、資料來源及技能集便利性清單方法在收集完所有頁面後仍會返回陣列;協定用戶端會公開相應的分頁操作。

import { SearchIndexClient } from "@azure/search-documents";
import { DefaultAzureCredential } from "@azure/identity";

const client = new SearchIndexClient("<endpoint>", new DefaultAzureCredential());

for await (const page of client
  .listIndexes({
    search: "hotel",
    searchType: "prefix",
    pageSize: 10,
  })
  .byPage()) {
  console.log(page.map((index) => index.name));
}

設定 SharePoint 文件權限

在建立索引之前,先註冊 SharePoint 連接器應用程式及其聯邦認證。 applicationId 以及 federatedCredentialId 是必須的; tenantId 當與搜尋服務租戶不同時,可以提供。 來電者需要 搜尋服務貢獻者。

組織範圍的共用授權會在權限欄位中使用orgLink:<tenantId>userIds。 organizationAccessExpiration 用來識別其到期時間戳記。 頂多只有一個頂層 Edm.DateTimeOffset 欄位能啟用此功能。 服務會在權限過濾查詢時驗證使用者的租戶與時間戳;僅宣告這些欄位並不代表存取權。

import { SearchIndexClient } from "@azure/search-documents";
import { DefaultAzureCredential } from "@azure/identity";

const client = new SearchIndexClient("<endpoint>", new DefaultAzureCredential());

await client.createIndex({
  name: "sharepoint-permissions",
  permissionFilterOption: "enabled",
  sharePointConnectorAppRegistration: {
    applicationId: "<applicationId>",
    federatedCredentialId: "<federatedCredentialId>",
  },
  fields: [
    { name: "id", type: "Edm.String", key: true },
    { name: "content", type: "Edm.String", searchable: true },
    {
      name: "userIds",
      type: "Collection(Edm.String)",
      filterable: true,
      permissionFilter: "userIds",
    },
    {
      name: "organizationLinkExpiresAt",
      type: "Edm.DateTimeOffset",
      organizationAccessExpiration: true,
    },
  ],
});

索引 SharePoint 網站內容

GA SharePoint 範圍除了現有的函式庫範圍外,還包括 AllSiteLists、 AllSitePages、 AllSiteContent和 。 透過環境中提供連接器 連接字串,而非將應用程式密鑰嵌入原始碼中。

import { SearchIndexClient, KnownIndexedSharePointContainerName } from "@azure/search-documents";
import { DefaultAzureCredential } from "@azure/identity";

const client = new SearchIndexClient("<endpoint>", new DefaultAzureCredential());
const connectionString = process.env.SHAREPOINT_CONNECTION_STRING;
if (!connectionString) {
  throw new Error("Set SHAREPOINT_CONNECTION_STRING before creating the knowledge source.");
}

await client.createKnowledgeSource({
  name: "sharepoint-site",
  kind: "indexedSharePoint",
  indexedSharePointParameters: {
    connectionString,
    containerName: KnownIndexedSharePointContainerName.AllSiteContent,
  },
});

重新整理未變更的 ADLS Gen2 權限

對於已存在的 ADLS Gen2 索引器,若會匯入權限 refreshAllAcls ,即使文件內容未變更,也會重新整理權限元資料。 它預設為 true,最多每 24 小時執行一次,且不會重新處理內容或豐富內容。 設定為 false 以停用刷新功能。

import { SearchIndexerClient } from "@azure/search-documents";
import { DefaultAzureCredential } from "@azure/identity";

const client = new SearchIndexerClient("<endpoint>", new DefaultAzureCredential());
const indexer = await client.getIndexer("<existingAdlsGen2Indexer>");

indexer.parameters = {
  ...indexer.parameters,
  configuration: {
    ...indexer.parameters?.configuration,
    refreshAllAcls: true,
  },
};
await client.createOrUpdateIndexer(indexer);

從知識庫檢索

import {
  KnowledgeRetrievalClient,
  AzureKeyCredential,
  KnownKnowledgeRetrievalReasoningEffortKind,
} from "@azure/search-documents";

const client = new KnowledgeRetrievalClient(
  "<endpoint>",
  "<knowledgeBaseName>",
  new AzureKeyCredential("<apiKey>"),
);

const response = await client.retrieve({
  intents: [{ type: "semantic", search: "What information is available?" }],
  retrievalReasoningEffort: { kind: KnownKnowledgeRetrievalReasoningEffortKind.Low },
  includeActivity: true,
});

console.log(response.response);

串流知識檢索

型別迭代器使用單一 SSE 連線,負責框架與心跳,並在 或 error後response.completed停止。 完成結果可報告完整(200)或部分206()結果。 打電話 controller.abort() 取消申請。 未知事件名稱會被忽略;token-delta 事件不屬於此 API 的一部分。 請參閱串流樣本以了解活動相關性與取消處理。

import { KnowledgeRetrievalClient, AzureKeyCredential } from "@azure/search-documents";

const client = new KnowledgeRetrievalClient(
  "<endpoint>",
  "<knowledgeBaseName>",
  new AzureKeyCredential("<apiKey>"),
);

const controller = new AbortController();
for await (const event of await client.retrieveStream(
  {
    intents: [{ type: "semantic", search: "Summarize the indexed information." }],
    includeActivity: true,
  },
  { abortSignal: controller.signal },
)) {
  if (event.event === "activity.completed") {
    console.log(`Activity ${event.data.id} took ${event.data.elapsedInMs}ms`);
  } else if (event.event === "response.completed") {
    console.log(event.data.statusCode === 206 ? "Partial results" : "Complete results");
    console.log(event.data.response.response);
  } else if (event.event === "error") {
    throw new Error(event.data.error.message);
  }
}

上傳與更新知識來源檔案

import { SearchIndexClient, AzureKeyCredential } from "@azure/search-documents";

const client = new SearchIndexClient("<endpoint>", new AzureKeyCredential("<apiKey>"));
const body = {
  metadata: { fileName: "manuals/example.txt", metadata: { category: "manual" } },
  content: {
    contents: new TextEncoder().encode("Azure AI Search retrieves relevant information."),
    contentType: "text/plain",
    filename: "example.txt",
  },
};

const uploaded = await client.uploadKnowledgeSourceFileMultipart("<knowledgeSourceName>", body);
if (!uploaded.fileId) {
  throw new Error("The service did not return an uploaded file ID.");
}

await client.updateKnowledgeSourceFile("<knowledgeSourceName>", uploaded.fileId, {
  ...body,
  metadata: { ...body.metadata, metadata: { category: "updated-manual" } },
});
for await (const file of client.listKnowledgeSourceFiles("<knowledgeSourceName>", {
  prefix: "manuals/",
  pageSize: 10,
})) {
  console.log(file.fileName, file.parsingMode, file.extractionMode);
}

檢查檔案知識來源容量

檔案知識來源的狀態會 fileCapacity 顯示 (KnowledgeSourceFileCapacity),顯示剩餘檔案數量及每個檔案位元組的限制。 上傳前請先檢查;其他類型的知識來源不會回報此欄位。 直接上傳需要搜尋 服務貢獻者,而搜尋服務的管理身份則需要嵌入資源上的 認知服務 OpenAI 使用者 。

import { SearchIndexClient } from "@azure/search-documents";
import { DefaultAzureCredential } from "@azure/identity";

const client = new SearchIndexClient("<endpoint>", new DefaultAzureCredential());
const status = await client.getKnowledgeSourceStatus("<fileKnowledgeSourceName>");

if (!status.fileCapacity) {
  throw new Error("The knowledge source did not report File upload capacity.");
}
console.log(`Remaining files: ${status.fileCapacity.remainingFileCount}`);
console.log(`Maximum file size: ${status.fileCapacity.maxFileSizeBytes} bytes`);

建立索引

import { SearchIndexClient, AzureKeyCredential } from "@azure/search-documents";

const indexClient = new SearchIndexClient("<endpoint>", new AzureKeyCredential("<apiKey>"));

const result = await indexClient.createIndex({
  name: "example-index",
  fields: [
    {
      type: "Edm.String",
      name: "id",
      key: true,
    },
    {
      type: "Edm.Double",
      name: "awesomenessLevel",
      sortable: true,
      filterable: true,
      facetable: true,
    },
    {
      type: "Edm.String",
      name: "description",
      searchable: true,
    },
    {
      type: "Edm.ComplexType",
      name: "details",
      fields: [
        {
          type: "Collection(Edm.String)",
          name: "tags",
          searchable: true,
        },
      ],
    },
    {
      type: "Edm.Int32",
      name: "hiddenWeight",
      hidden: true,
    },
  ],
});

console.log(`Index created with name ${result.name}`);

從索引擷取特定檔

特定檔案可以透過其主鍵值來擷取:

import { SearchClient, AzureKeyCredential } from "@azure/search-documents";

const searchClient = new SearchClient(
  "<endpoint>",
  "<indexName>",
  new AzureKeyCredential("<apiKey>"),
);

const result = await searchClient.getDocument("1234");

將檔新增至索引

您可以將多個檔案上傳至批次內的索引:

import { SearchClient, AzureKeyCredential } from "@azure/search-documents";

const searchClient = new SearchClient(
  "<endpoint>",
  "<indexName>",
  new AzureKeyCredential("<apiKey>"),
);

const uploadResult = await searchClient.uploadDocuments([
  // JSON objects matching the shape of the client's index
  {},
  {},
  {},
]);
for (const result of uploadResult.results) {
  console.log(`Uploaded ${result.key}; succeeded? ${result.succeeded}`);
}

對文件執行搜尋

若要列出特定查詢的所有結果,您可以 search 搭配使用 簡單查詢語法的搜尋字串:

import { SearchClient, AzureKeyCredential } from "@azure/search-documents";

const searchClient = new SearchClient(
  "<endpoint>",
  "<indexName>",
  new AzureKeyCredential("<apiKey>"),
);

const searchResults = await searchClient.search("wifi -luxury");
for await (const result of searchResults.results) {
  console.log(result);
}

如需使用 Lucene 語法的更進階搜尋,請指定 queryType 為 full:

import { SearchClient, AzureKeyCredential } from "@azure/search-documents";

const searchClient = new SearchClient(
  "<endpoint>",
  "<indexName>",
  new AzureKeyCredential("<apiKey>"),
);

const searchResults = await searchClient.search('Category:budget AND "recently renovated"^3', {
  queryType: "full",
  searchMode: "all",
});
for await (const result of searchResults.results) {
  console.log(result);
}

使用 TypeScript 進行查詢

在 TypeScript 中, SearchClient 採用通用參數,該參數是索引文件的模型形狀。 這可讓您對結果中傳回的字段執行強型別查閱。 TypeScript 也能夠檢查指定 select 參數時傳回的欄位。

import { SearchClient, AzureKeyCredential, SelectFields } from "@azure/search-documents";

// An example schema for documents in the index
interface Hotel {
  hotelId?: string;
  hotelName?: string | null;
  description?: string | null;
  descriptionVector?: Array<number>;
  parkingIncluded?: boolean | null;
  lastRenovationDate?: Date | null;
  rating?: number | null;
  rooms?: Array<{
    beds?: number | null;
    description?: string | null;
  }>;
}

const searchClient = new SearchClient<Hotel>(
  "<endpoint>",
  "<indexName>",
  new AzureKeyCredential("<apiKey>"),
);

const searchResults = await searchClient.search("wifi -luxury", {
  // Only fields in Hotel can be added to this array.
  // TS will complain if one is misspelled.
  select: ["hotelId", "hotelName", "rooms/beds"],
});

// These are other ways to declare the correct type for `select`.
const select = ["hotelId", "hotelName", "rooms/beds"] as const;
// This declaration lets you opt out of narrowing the TypeScript type of your documents,
// though the AI Search service will still only return these fields.
const selectWide: SelectFields<Hotel>[] = ["hotelId", "hotelName", "rooms/beds"];
// This is an invalid declaration. Passing this to `select` will result in a compiler error
// unless you opt out of including the model in the client constructor.
const selectInvalid = ["hotelId", "hotelName", "rooms/beds"];

for await (const result of searchResults.results) {
  // result.document has hotelId, hotelName, and rooms with only the beds property.
  // Trying to access result.document.description would emit a TS error.
  console.log(result.document.hotelName);
}

使用 OData 篩選進行查詢

使用 filter 查詢參數可讓您使用 OData $filter運算式的語法來查詢索引。

import { SearchClient, AzureKeyCredential, odata } from "@azure/search-documents";

const searchClient = new SearchClient(
  "<endpoint>",
  "<indexName>",
  new AzureKeyCredential("<apiKey>"),
);

const baseRateMax = 200;
const ratingMin = 4;
const searchResults = await searchClient.search("WiFi", {
  filter: odata`Rooms/any(room: room/BaseRate lt ${baseRateMax}) and Rating ge ${ratingMin}`,
  orderBy: ["Rating desc"],
  select: ["hotelId", "hotelName", "Rating"],
});
for await (const result of searchResults.results) {
  // Each result will have "HotelId", "HotelName", and "Rating"
  // in addition to the standard search result property "score"
  console.log(result);
}

使用向量查詢

可以使用搜尋參數查詢 vector 文字內嵌。 如需詳細資訊,請參閱查詢向量和篩選向量查詢。

import { SearchClient, AzureKeyCredential } from "@azure/search-documents";

const searchClient = new SearchClient(
  "<endpoint>",
  "<indexName>",
  new AzureKeyCredential("<apiKey>"),
);

const queryVector: number[] = [
  // Embedding of the query "What are the most luxurious hotels?"
];
const searchResults = await searchClient.search("*", {
  vectorSearchOptions: {
    queries: [
      {
        kind: "vector",
        vector: queryVector,
        fields: ["descriptionVector"],
        kNearestNeighborsCount: 3,
      },
    ],
  },
});
for await (const result of searchResults.results) {
  // These results are the nearest neighbors to the query vector
  console.log(result);
}

使用Facet進行查詢

Facets 用於協助應用程式使用者依預先設定的維度進行搜尋篩選。 Facet 語法 提供排序與分組 facet 值的選項。

import { SearchClient, AzureKeyCredential } from "@azure/search-documents";

const searchClient = new SearchClient(
  "<endpoint>",
  "<indexName>",
  new AzureKeyCredential("<apiKey>"),
);

const searchResults = await searchClient.search("WiFi", {
  facets: ["category,count:3,sort:count", "rooms/baseRate,interval:100"],
});
console.log(searchResults.facets);

擷取結果時,將提供屬性 facets ,指出落入每個 Facet 儲存區的結果數目。 這可用於推動細化(例如,發出後續搜索, Rating 過濾大於或等於 3 且小於 4。

故障排除

伐木

啟用記錄有助於找出有關失敗的實用資訊。 若要查看 HTTP 要求和回應的記錄,請將 AZURE_LOG_LEVEL 環境變數設定為 info。 或者,您可以在運行時間啟用記錄,方法是在 setLogLevel中呼叫 @azure/logger:

import { setLogLevel } from "@azure/logger";

setLogLevel("info");

如需如何啟用記錄的詳細指示,請參閱@azure/記錄器套件檔。

後續步驟

貢獻

如果您想要參與此連結庫,請閱讀 參與指南 ,以深入瞭解如何建置和測試程序代碼。

此項目歡迎參與和建議。 大部分的捐款都要求您同意「參與者許可協定」(CLA),宣告您有權,而且實際上確實會授與我們使用您貢獻的許可權。 詳情請瀏覽 cla.microsoft.com。

此專案採用了 Microsoft 開放原始碼管理辦法。 如需詳細資訊,請參閱 《行為規範》常見問題 或連絡 opencode@microsoft.com,以取得任何其他問題或意見。