Azure AI Search (旧称 "Azure Cognitive Search") は、開発者が大規模な言語モデルとエンタープライズ データを組み合わせた豊富な検索エクスペリエンスと生成 AI アプリを構築するのに役立つ、AI を活用した情報検索プラットフォームです。
Azure AI Search サービスは、次のアプリケーション シナリオに適しています。
- さまざまなコンテンツ タイプを 1 つの検索可能なインデックスに統合します。 インデックスを設定するには、コンテンツを含む JSON ドキュメントをプッシュするか、データが既に Azure にある場合は、データを自動的にプルするインデクサーを作成します。
- インデクサーにスキルセットをアタッチして、画像や非構造化ドキュメントから検索可能なコンテンツを作成します。 スキルセットは、組み込みの OCR、エンティティ認識、キー フレーズ抽出、言語検出、テキスト翻訳、センチメント分析のために、Azure AI Services の API を活用します。 データ インジェスト中にコンテンツの外部処理を統合するカスタム スキルを追加することもできます。
- 検索クライアント アプリケーションで、商用 Web 検索エンジンやチャット スタイルのアプリに似たクエリ ロジックとユーザー エクスペリエンスを実装します。
@azure/search-documentsクライアントライブラリを使用して、次のことを行います。
- ベクター、キーワード、およびハイブリッド クエリ フォームを使用してクエリを送信します。
- メタデータ、地理空間検索、ファセット ナビゲーション、またはフィルター条件に基づいて結果を絞り込むためのフィルター処理されたクエリを実装します。
- 検索インデックスを作成および管理します。
- 検索インデックス内のドキュメントをアップロードおよび更新します。
- Azure からインデックスにデータをプルするインデクサーを作成および管理します。
- データ インジェストに AI エンリッチメントを追加するスキルセットを作成および管理します。
- 高度なテキスト分析または多言語コンテンツ用のアナライザーを作成および管理します。
- セマンティック ランク付けとスコアリング プロファイルを使用して結果を最適化し、ビジネス ロジックや鮮度を考慮します。
主要なリンク:
はじめ
@azure/search-documents パッケージをインストールする
npm install @azure/search-documents
現在サポートされている環境
- Node.js の LTS バージョン
- 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 ) のインスタンスを作成する必要があります。 クライアント オブジェクトをインスタンス化するには、 エンドポイント と 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,
} 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>"));
National Cloud での認証
National Cloud で認証するには、クライアント設定に次の追加を行う必要があります。
-
AudienceをSearchClientOptions
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 Search サービスには、JSON ドキュメントの形式で検索可能なデータの永続的なストレージを提供する 1 つ以上のインデックスが含まれています。 (検索が初めての場合は、インデックスとデータベーステーブルを非常に大まかに類推できます。@azure/search-documents クライアント ライブラリは、3 つの主要なクライアントの種類を通じて、これらのリソースに対する操作を公開します。
SearchClient次のことに役立ちます。- ベクトルクエリ、キーワードクエリ、およびハイブリッドクエリを使用したインデックス付きドキュメントの検索
- ベクター クエリ フィルター と テキスト クエリ フィルター
- 関連性を高めるためのセマンティック ランク付けとスコアリング プロファイル
- インデックス内のドキュメントに基づいて部分的に入力された検索語のオートコンプリート
- ユーザーが入力したときにドキュメント内の最も一致する可能性が高いテキストを提案する
- インデックスからのドキュメントドキュメントの追加、更新、または削除
SearchIndexClientを使用すると、次のことを実行できます。SearchIndexerClientを使用すると、次のことを実行できます。
注: これらのクライアントは、呼び出す API がクロスオリジンリソース共有 (CORS) をサポートしていないため、ブラウザーで機能できません。
TypeScript/JavaScript 固有の概念
書類
検索インデックス内に格納されている項目。 このドキュメントの形状は、 fields プロパティを使用してインデックスに記述されています。 各 SearchField には、名前、データ型、および検索可能またはフィルター処理可能かどうかなどの追加のメタデータがあります。
ページネーション
通常、一度にユーザーには 検索結果のサブセットのみを表示します 。 これをサポートするために、 top、 skip 、 includeTotalCount パラメーターを使用して、検索結果の上にページ エクスペリエンスを提供できます。
ドキュメント フィールドのエンコード
インデックスでサポートされているデータ型は、API 要求/応答の JSON 型にマップされます。 JS クライアント ライブラリは、いくつかの例外を除き、ほとんど同じ状態を維持します。
-
Edm.DateTimeOffsetはJSDateに変換されます。 -
Edm.GeographyPointは、クライアントライブラリによってエクスポートされたGeographyPoint型に変換されます。 -
number型 (NaN、Infinity、-Infinity) の特殊値は、REST API では文字列としてシリアル化されますが、クライアントライブラリによってnumberに変換されます。
注: データ型は、インデックススキーマのフィールド型ではなく、値に基づいて変換されます。 つまり、フィールドの値としてISO8601日付文字列 (例: "2020-03-06T18:48:27.896Z") がある場合、スキーマに格納した方法に関係なく、日付に変換されます。
例
次の例は基本を示しています - 詳細については、 サンプルをご覧ください 。
インデックスを作成する
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 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);
}
ファセットを使用したクエリ
ファセット は、アプリケーションのユーザーが事前構成されたディメンションに沿って検索を絞り込むのに役立つために使用されます。 ファセット構文は 、ファセット値をソートしてバケット化するオプションを提供します。
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 にお問い合わせください。
関連プロジェクト
- Microsoft Azure SDK for JavaScript の
Azure SDK for JavaScript