JavaScript用Azure AI 検索クライアントライブラリ - バージョン13.1.0

Azure AI 検索(旧称「Azure Cognitive Search」)は、大規模な言語モデルとエンタープライズデータを組み合わせた豊かな検索体験や生成AIアプリの構築を支援するAI搭載の情報検索プラットフォームです。

Azure AI 検索 サービスは、次のアプリケーション シナリオに適しています。

  • さまざまなコンテンツ タイプを 1 つの検索可能なインデックスに統合します。 インデックスを設定するには、コンテンツを含む JSON ドキュメントをプッシュするか、データが既に Azure にある場合は、データを自動的にプルするインデクサーを作成します。
  • インデクサーにスキルセットをアタッチして、画像や非構造化ドキュメントから検索可能なコンテンツを作成します。 スキルセットは、組み込みの OCR、エンティティ認識、キー フレーズ抽出、言語検出、テキスト翻訳、センチメント分析のために、Azure AI Services の API を活用します。 データ インジェスト中にコンテンツの外部処理を統合するカスタム スキルを追加することもできます。
  • 検索クライアント アプリケーションで、商用 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 の例は samples/v13 で利用可能です。

現在サポートされている環境

  • LTS版の Node.js
  • Safari、Chrome、Microsoft Edge、Firefox の最新バージョン。

詳細については、Microsoft のサポート ポリシーを参照してください。

前提 条件

新しい検索サービスを作成するには、 Azure portal、 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 キーは、既存のロールの割り当てを必要としないため、簡単に始めることができます。

エンドポイントと API キーは、Azure portal の検索サービスから取得できます。 APIキーの取得方法については 、ドキュメント を参照してください。

または、次の Azure CLI コマンドを使用して、検索サービスから API キーを取得することもできます。

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

検索サービスへのアクセスに使用されるキーには、admin(読み取り/書き込み) キーとクエリ(読み取り専用) キーの 2 種類があります。 クライアント アプリでのアクセスと操作を制限することは、サービス上の検索資産を保護するために不可欠です。 クライアント アプリから送信されるクエリには、常に管理者キーではなくクエリ キーを使用します。

注:上記の例の 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>"),
);

National Cloud での認証

National Cloud で認証するには、クライアント設定に次の追加を行う必要があります。

  • AudienceをSearchClientOptions
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 ドキュメントの形式で検索可能なデータの永続的なストレージを提供する 1 つ以上のインデックスが含まれています。 (検索がまったく不習慣なら、インデックスとデータベーステーブルをごく大まかに類比することができます。)@azure/search-documentsクライアントライブラリは、これらのリソースに対する操作を4つの主要なクライアントタイプを通じて公開します。

注意:ブラウザの使用は、選択した検索操作およびリソースに CORS が設定されているかどうかによって異なります。 ファイルの知識ソースやナレッジベースはCORS設定を公開しますが、多くの管理操作は信頼できるサーバーサイドアプリケーション向けに設計されています。

TypeScript/JavaScript 固有の概念

書類

検索インデックス内に格納されている項目。 このドキュメントの形状は、 fields プロパティを使用してインデックスに記述されています。 各 SearchField には、名前、データ型、および検索可能またはフィルター処理可能かどうかなどの追加のメタデータがあります。

ページネーション

通常、一度にユーザーには 検索結果のサブセットのみを表示します 。 これをサポートするために、 top、 skip 、 includeTotalCount パラメーターを使用して、検索結果の上にページ エクスペリエンスを提供できます。

ドキュメント フィールドのエンコード

インデックスでサポートされているデータ型は、API リクエスト/レスポンスで JSON 型にマッピングされます。 JS クライアント ライブラリは、いくつかの例外を除き、ほとんど同じ状態を維持します。

  • Edm.DateTimeOffset JS Dateに変換されます。
  • Edm.GeographyPoint クライアントライブラリによってエクスポートされた GeographyPoint タイプに変換されます。
  • number型 (NaN、Infinity、-Infinity) の特殊値は、REST API では文字列としてシリアル化されますが、クライアントライブラリによってnumberに変換されます。

注意:データ型はインデックススキーマ内のフィールドタイプではなく値に基づいて変換されます。 つまり、フィールドの値としてISO8601日付文字列 (例: "2020-03-06T18:48:27.896Z") がある場合、スキーマに格納した方法に関係なく、日付に変換されます。

例

次の例は基本を示しています - 詳細については、 サンプルをご覧ください 。

以下の例は、クライアントのデフォルトである安定 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 リソース上の Cognitive Services OpenAI ユーザーを付与します。 展開名とモデル名は別々の設定です。展開名はカスタム名を持つことができます。 発信者はナレッジベースを管理するために Search Service Contributor を必要とします。

保存された命令、出力モード、推論の努力は、知識源を置き換えることなく更新できます。 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提供可能です。 発信者は 検索サービスコントリビューターが必要です。

組織範囲の共有グラントでは、userIds権限フィールドでorgLink:<tenantId>を使用します。 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);

ストリーム知識検索

型付きイテレーターは1つのSSE接続を使用し、フレーミングとハートビートを処理し、 response.completed または errorで停止します。 完了は、完全結果(200)または部分結果(206)を報告することができます。 リクエストをキャンセルするには controller.abort() に電話してください。 未知のイベント名は無視されます。トークンデルタイベントはこの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)を公開します。 アップロード前に必ず確認してください。他のナレッジソースの種類ではこの項目は報告されていません。 直接アップロードには Search Service Contributorが必要であり、検索サービスのマネージドIDには埋め込みリソース上の Cognitive Services OpenAI User が必要です。

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);
}

ファセットを使用したクエリ

ファセット は、アプリケーションユーザーが事前設定された寸法に沿って検索を絞り込むのに役立ちます。 ファセット構文では 、ファセット値をソートし、バケット化するオプションがあります。

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 プロパティが利用可能になります。 これは、絞り込みを促進するために使用できます (たとえば、3 以上 4 未満の Rating をフィルタリングするフォローアップ検索を発行します)。

トラブルシューティング

伐採

ログ記録を有効にすると、エラーに関する有用な情報を明らかにするのに役立ちます。 HTTP 要求と応答のログを表示するには、AZURE_LOG_LEVEL 環境変数を infoに設定します。 または、setLogLevelで @azure/logger を呼び出すことによって、実行時にログを有効にすることもできます。

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

setLogLevel("info");

ログを有効にする方法の詳細な手順については、 @azure/logger パッケージのドキュメントを参照してください。

次の手順

貢献

このライブラリに投稿する場合は、コードをビルドしてテストする方法の詳細については、 投稿ガイド をお読みください。

このプロジェクトは、投稿と提案を歓迎します。 ほとんどの投稿では、お客様が投稿を使用する権利を当社に付与する権利を有し、実際に行うことを宣言する共同作成者ライセンス契約 (CLA) に同意する必要があります。 詳細については、 cla.microsoft.com をご覧ください。

このプロジェクトは、「Microsoft のオープン ソースの倫理規定」を採用しています。 詳細については、行動規範に関する FAQ を参照するか、その他の質問やコメントを opencode@microsoft.com にお問い合わせください。