適用於 JavaScript 的 Azure AI 搜尋用戶端連結庫 - 12.0.0 版

Azure AI 搜尋服務 (先前稱為「Azure 認知搜尋」) 是一種 AI 功能的資訊擷取平臺,可協助開發人員建置豐富的搜尋體驗和結合大型語言模型的 AI 應用程式與企業數據。

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

  • 將不同的內容類型合併成單一可搜尋的索引。 若要填入索引,您可以推送包含內容的 JSON 檔,或者如果您的數據已經在 Azure 中,請建立索引器以自動提取數據。
  • 將技能集附加至索引器,以從影像和大型文字檔建立可搜尋的內容。 技能集利用 AI 服務的 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 --service-name <mysearch> --resource-group <mysearch-rg>

一旦您擁有 API 金鑰,您可以使用它,如下所示:

const {
  SearchClient,
  SearchIndexClient,
  SearchIndexerClient,
  AzureKeyCredential,
} = require("@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>"));

在國家雲端中驗證

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

  • Audience 中設定 SearchClientOptions
const {
  SearchClient,
  SearchIndexClient,
  SearchIndexerClient,
  AzureKeyCredential,
  KnownSearchAudience,
} = require("@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 在索引中描述。 每個欄位都有名稱、數據類型,以及其他元數據,例如是否可搜尋或可篩選。

分頁

一般而言,您只會想要一次 向用戶顯示搜尋結果的子集 。 若要支援此功能,您可以使用 topskipincludeTotalCount 參數,在搜尋結果頂端提供分頁體驗。

檔欄位編碼

索引中支持的數據類型會對應至 API 要求/回應中的 JSON 類型。 JS 用戶端連結庫會保留這些大部分相同,但有一些例外狀況:

  • Edm.DateTimeOffset 轉換成 JS Date
  • Edm.GeographyPointGeographyPoint 轉換成用戶端連結庫導出的類型。
  • 類型的特殊值 number (NaN、Infinity、-Infinity) 會串行化為 REST API 中的字串,但會由用戶端連結庫轉換回 number

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

範例

下列範例示範基本概念 - 請查看 我們的範例 以取得更多內容。

建立索引

const { SearchIndexClient, AzureKeyCredential } = require("@azure/search-documents");

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

async function main() {
  const result = await client.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(result);
}

main();

從索引擷取特定檔

特定檔案可由其主鍵值擷取:

const { SearchClient, AzureKeyCredential } = require("@azure/search-documents");

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

async function main() {
  const result = await client.getDocument("1234");
  console.log(result);
}

main();

將檔新增至索引

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

const { SearchClient, AzureKeyCredential } = require("@azure/search-documents");

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

async function main() {
  const uploadResult = await client.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}`);
  }
}

main();

對文件執行搜尋

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

const { SearchClient, AzureKeyCredential } = require("@azure/search-documents");

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

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

main();

如需使用 Lucene 語法的更進階搜尋,請指定 queryTypefull

const { SearchClient, AzureKeyCredential } = require("@azure/search-documents");

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

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

main();

使用 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> | null;
  parkingIncluded?: boolean | null;
  lastRenovationDate?: Date | null;
  rating?: number | null;
  rooms?: Array<{
    beds?: number | null;
    description?: string | null;
  } | null>;
}

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

async function main() {
  const searchResults = await client.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);
  }
}

main();

使用 OData 篩選進行查詢

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

const { SearchClient, AzureKeyCredential, odata } = require("@azure/search-documents");

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

async function main() {
  const baseRateMax = 200;
  const ratingMin = 4;
  const searchResults = await client.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);
  }
}

main();

使用向量查詢

您可以使用搜尋參數來查詢 vector 文字內嵌。

const { SearchClient, AzureKeyCredential, odata } = require("@azure/search-documents");

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

async function main() {
  const queryVector = [...]
  const searchResults = await searchClient.search("*", {
    vector: {
      fields: ["descriptionVector"],
      kNearestNeighborsCount: 3,
      value: queryVector,
    },
  });
  for await (const result of searchResults.results) {
    // These results are the nearest neighbors to the query vector
    console.log(result);
  }
}

main();

使用Facet進行查詢

Facet 可用來協助應用程式的使用者沿著預先設定的維度精簡搜尋。 Facet 語法 提供排序和貯體 Facet 值的選項。

const { SearchClient, AzureKeyCredential } = require("@azure/search-documents");

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

async function main() {
  const searchResults = await client.search("WiFi", {
    facets: ["category,count:3,sort:count", "rooms/baseRate,interval:100"],
  });
  console.log(searchResults.facets);
  // Output will look like:
  // {
  //   'rooms/baseRate': [
  //     { count: 16, value: 0 },
  //     { count: 17, value: 100 },
  //     { count: 17, value: 200 }
  //   ],
  //   category: [
  //     { count: 5, value: 'Budget' },
  //     { count: 5, value: 'Luxury' },
  //     { count: 5, value: 'Resort and Spa' }
  //   ]
  // }
}

main();

擷取結果時, facets 將會提供屬性,指出落在每個Facet貯體的結果數目。 這可用來推動精簡 (例如發出追蹤搜尋, Rating 篩選大於或等於 3 且小於 4.)

疑難排解

記錄

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

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

setLogLevel("info");

如需如何啟用記錄的詳細指示,可參閱 @azure/logger 套件文件

下一步

參與

如果您希望向此程式庫投稿,請參閱投稿指南,深入瞭解如何組建與測試程式碼。

此專案歡迎參與和提供建議。 大部分的參與都要求您同意「參與者授權合約 (CLA)」,宣告您有權且確實授與我們使用投稿的權利。 如需詳細資訊,請造訪 cla.microsoft.com

此專案已採用 Microsoft 開放原始碼執行程式代碼。如需詳細資訊,請參閱 管理辦法常見問題 ,或連絡 opencode@microsoft.com 任何其他問題或意見。

曝光數