共用方式為


適用於 JavaScript 的 Azure AI 搜尋服務用戶端程式庫 - 12.2.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

目前支持的環境

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

先決條件

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

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

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

驗證用戶端

若要與搜尋服務互動,您必須建立適當用戶端類別的執行個體: SearchClient 用於搜尋索引文件、 SearchIndexClient 管理索引,或 SearchIndexerClient 編目資料來源並將搜尋文件載入索引。 若要具現化用戶端物件,您需要 端點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,
} 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>"));

在國家雲端中驗證

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

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

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

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

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

重要概念

Azure AI 搜尋服務包含一或多個索引,這些索引會以 JSON 檔的形式持續儲存可搜尋的數據。 (如果您是搜尋新手,您可以在索引和資料庫表之間進行非常粗略的類比。 用戶端程式庫會 @azure/search-documents 透過三種主要用戶端類型公開這些資源的作業。

注意:這些客戶端無法在瀏覽器中運行,因為它調用的API不支持跨來源資源共享(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。

例子

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

建立索引

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 語法的更進階搜尋,請指定 queryTypefull

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 rating.
  // 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進行查詢

Facet 可用來協助應用程式的使用者沿著預先設定的維度精簡搜尋。 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,以取得任何其他問題或意見。