JavaScript 用 Azure AI Search クライアント ライブラリ - バージョン 12.0.0
Azure AI Search (旧称 "Azure Cognitive Search") は、開発者が豊富な検索エクスペリエンスを構築し、大規模な言語モデルとエンタープライズ データを組み合わせた生成型 AI アプリを構築するのに役立つ、AI を利用した情報取得プラットフォームです。
Azure AI Search は、次のアプリケーション シナリオに適しています。
- さまざまなコンテンツ タイプを 1 つの検索可能なインデックスに統合します。 インデックスを設定するには、コンテンツを含む JSON ドキュメントをプッシュするか、データが既に Azure にある場合は、データを自動的にプルするインデクサーを作成します。
- スキルセットをインデクサーにアタッチして、画像や大きなテキスト ドキュメントから検索可能なコンテンツを作成します。 スキルセットは、組み込みの OCR、エンティティ認識、キー フレーズ抽出、言語検出、テキスト翻訳、センチメント分析のために、AI サービスの API を活用します。 カスタム スキルを追加して、データ インジェスト中にコンテンツの外部処理を統合することもできます。
- 検索クライアント アプリケーションで、商用 Web 検索エンジンと同様のクエリ ロジックとユーザー エクスペリエンスを実装します。
クライアント ライブラリを使用して、次の @azure/search-documents 手順を実行します。
- ベクター、キーワード (keyword)、ハイブリッド クエリ フォームを使用してクエリを送信します。
- メタデータ、地理空間検索、ファセット ナビゲーション、またはフィルター条件に基づいて結果を絞り込むためのフィルター処理されたクエリを実装します。
- 検索インデックスを作成および管理します。
- 検索インデックス内のドキュメントをアップロードして更新します。
- Azure からインデックスにデータをプルするインデクサーを作成および管理します。
- AI エンリッチメントをデータ インジェストに追加するスキルセットを作成および管理します。
- 高度なテキスト分析または多言語コンテンツ用のアナライザーを作成および管理します。
- スコアリング プロファイルを使用して結果を最適化し、ビジネス ロジックや鮮度を考慮します。
主要リンク:
作業の開始
@azure/search-documents
パッケージのインストール
npm install @azure/search-documents
現在サポートされている環境
- Node.js の LTS バージョン
- Safari、Chrome、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 --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>"));
National Cloud での認証
National Cloud で認証するには、クライアント構成に次の追加を行う必要があります。
- で を設定する
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 Search Serviceには、JSON ドキュメントの形式で検索可能なデータの永続的なストレージを提供する 1 つ以上のインデックスが含まれています。 (検索を初めて使用する場合は、インデックスとデータベース テーブルの間で非常に大まかな類似を行うことができます)。クライアント ライブラリは@azure/search-documents、これらのリソースに対する操作を 3 つのメインクライアントの種類を通じて公開します。
SearchClient
次の場合に役立ちます。- ベクター クエリ、キーワード (keyword) クエリ、ハイブリッド クエリを使用したインデックス付きドキュメントの検索
- ベクター クエリ フィルター と テキスト クエリ フィルター
- 関連性を高めるためのセマンティック ランク付けプロファイルとスコアリング プロファイル
- インデックス内のドキュメントに基づいて部分的に型指定された検索語句をオートコンプリートする
- ユーザーの種類としてドキュメント内で最も一致する可能性の高いテキストを提案する
- インデックスからドキュメント ドキュメントを追加、更新、または削除する
SearchIndexClient
を使用すると、次のことを実行できます。SearchIndexerClient
を使用すると、次のことを実行できます。
注: 呼び出す API にはクロスオリジン リソース共有 (CORS) がサポートされていないため、これらのクライアントはブラウザーで機能できません。
TypeScript/JavaScript 固有の概念
Documents
検索インデックス内に格納されている項目。 このドキュメントの形状は、 を使用して Field
インデックスで説明されています。 各フィールドには、名前、データ型、および検索可能またはフィルター可能かどうかなどの追加のメタデータがあります。
改ページ位置の自動修正
通常は、 検索結果のサブセットを 一度にユーザーに表示する必要があります。 これをサポートするには、 パラメーターと includeTotalCount
パラメーターをtop
skip
使用して、検索結果の上にページングされたエクスペリエンスを提供できます。
ドキュメント フィールドのエンコード
インデックスでサポートされているデータ型は、API 要求/応答の JSON 型にマップされます。 JS クライアント ライブラリでは、これらのほとんどが同じ状態で保持されますが、一部の例外があります。
Edm.DateTimeOffset
は JSDate
に変換されます。Edm.GeographyPoint
は、クライアント ライブラリによってエクスポートされた型に変換されますGeographyPoint
。- 型の
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 構文を使用するより高度な検索の場合は、 を にfull
指定queryType
します。
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();
ファセットを使用したクエリ
ファセット は、アプリケーションのユーザーが事前に構成されたディメンションに沿って検索を絞り込むのに役立ちます。 ファセット構文 には、ファセット値の並べ替えとバケット化を行うオプションが用意されています。
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
各ファセット バケットに含まれる結果の数を示すプロパティを使用できます。 これは、絞り込みを促進するために使用できます (たとえば、 が 3 以上 4 未満であることをフィルター処理 Rating
するフォローアップ検索を発行します)。
トラブルシューティング
ログ記録
ログの記録を有効にすると、エラーに関する有用な情報を明らかにするのに役立つ場合があります。 HTTP 要求と応答のログを表示するには、環境変数 AZURE_LOG_LEVEL
を info
に設定します。 または、@azure/logger
で setLogLevel
を呼び出して、実行時にログ記録を有効にすることもできます。
import { setLogLevel } from "@azure/logger";
setLogLevel("info");
ログを有効にする方法の詳細については、@azure/logger パッケージに関するドキュメントを参照してください。
次の手順
共同作成
このライブラリに投稿する場合、コードをビルドしてテストする方法の詳細については、投稿ガイドを参照してください。
このプロジェクトでは、共同作成と提案を歓迎しています。 ほとんどの共同作成では、共同作成者使用許諾契約書 (CLA) にご同意いただき、ご自身の共同作成内容を使用する権利を Microsoft に供与する権利をお持ちであり、かつ実際に供与することを宣言していただく必要があります。 詳細については、「 cla.microsoft.com」を参照してください。
このプロジェクトでは、 Microsoft オープン ソースの行動規範が採用されています。詳細については、「 行動規範に 関する FAQ」を参照するか、追加の質問やコメントに問い合わせてください opencode@microsoft.com 。
関連プロジェクト
Azure SDK for JavaScript
フィードバック
https://aka.ms/ContentUserFeedback」を参照してください。
以下は間もなく提供いたします。2024 年を通じて、コンテンツのフィードバック メカニズムとして GitHub の issue を段階的に廃止し、新しいフィードバック システムに置き換えます。 詳細については、「フィードバックの送信と表示