azure-search-documents-ts について
Azure AI Search SDK を使って検索アプリを構築する TypeScript スキルです。全文、ベクトル、ハイブリッド、セマンティック検索と、インデックスやドキュメントの操作を扱います。
主な機能
- 01ベクトルフィールド付きインデックスの作成
- 02ドキュメントの登録と更新
- 03全文検索とベクトル検索
- 04ハイブリッド検索とセマンティック検索
- 05フィルター、ファセット、自動補完、候補表示
- 06インデックスの一括操作
活用シーン
- 01製品検索インデックスの作成
- 02ドキュメント群の登録と更新
- 03テキストとベクトル検索の組み合わせ
- 04結果の絞り込みとファセット取得
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ sickn33/ agentic-awesome-skills --skill azure-search-documents-tsインストール後、Claude Code で/azure-search-documents-tsを入力して読み込まれたか確認します。
詳細
Azure AI Search SDK for TypeScript
ベクトル検索、ハイブリッド検索、セマンティック検索機能を備えた検索アプリケーションを構築します。
インストール
npm install @azure/search-documents @azure/identity
環境変数
AZURE_SEARCH_ENDPOINT=https://<service-name>.search.windows.net
AZURE_SEARCH_INDEX_NAME=my-index
AZURE_SEARCH_ADMIN_KEY=<admin-key> # Optional if using Entra ID
認証
import { SearchClient, SearchIndexClient } from "@azure/search-documents";
import { DefaultAzureCredential } from "@azure/identity";
const endpoint = process.env.AZURE_SEARCH_ENDPOINT!;
const indexName = process.env.AZURE_SEARCH_INDEX_NAME!;
const credential = new DefaultAzureCredential();
// For searching
const searchClient = new SearchClient(endpoint, indexName, credential);
// For index management
const indexClient = new SearchIndexClient(endpoint, credential);
バージョン、スキーマ、認可
コードスニペットはプレースホルダーを含む独立した断片であり、そのまま実行できる完全なプログラムではありません。使用前に、インストール済み SDK の型、実際のインデックススキーマ、埋め込みモデルと次元数を確認してください。ドキュメントのセキュリティフィルターは、認証済みの ID に基づいてサーバー側で設定してください。クライアントから渡されたフィルターをアクセス制御として信頼してはいけません。インデックスの作成・更新、またはレコードのアップロード・削除には、対象に対する適切な認可が必要です。また、有料サービスの状態が変わる可能性があります。
コアワークフロー
ベクトルフィールドを含むインデックスの作成
import { SearchIndex, SearchField, VectorSearch } from "@azure/search-documents";
const index: SearchIndex = {
name: "products",
fields: [
{ name: "id", type: "Edm.String", key: true },
{ name: "title", type: "Edm.String", searchable: true },
{ name: "description", type: "Edm.String", searchable: true },
{ name: "category", type: "Edm.String", filterable: true, facetable: true },
{
name: "embedding",
type: "Collection(Edm.Single)",
searchable: true,
vectorSearchDimensions: 1536,
vectorSearchProfileName: "vector-profile",
},
],
vectorSearch: {
algorithms: [
{ name: "hnsw-algorithm", kind: "hnsw" },
],
profiles: [
{ name: "vector-profile", algorithmConfigurationName: "hnsw-algorithm" },
],
},
};
await indexClient.createOrUpdateIndex(index);
ドキュメントのインデックス作成
const documents = [
{ id: "1", title: "Widget", description: "A useful widget", category: "Tools", embedding: [...] },
{ id: "2", title: "Gadget", description: "A cool gadget", category: "Electronics", embedding: [...] },
];
const result = await searchClient.uploadDocuments(documents);
const failures = result.results.filter((item) => !item.succeeded);
if (failures.length) throw new Error(`Indexing failed for ${failures.length} documents`);
console.log(`Indexed ${result.results.length} documents`);
全文検索
const results = await searchClient.search("widget", {
select: ["id", "title", "description"],
filter: "category eq 'Tools'",
orderBy: ["title asc"],
top: 10,
});
for await (const result of results.results) {
console.log(`${result.document.title}: ${result.score}`);
}
ベクトル検索
const queryVector = await getEmbedding("useful tool"); // Your embedding function
const results = await searchClient.search("*", {
vectorSearchOptions: {
queries: [
{
kind: "vector",
vector: queryVector,
fields: ["embedding"],
kNearestNeighborsCount: 10,
},
],
},
select: ["id", "title", "description"],
});
for await (const result of results.results) {
console.log(`${result.document.title}: ${result.score}`);
}
ハイブリッド検索(テキスト+ベクトル)
const queryVector = await getEmbedding("useful tool");
const results = await searchClient.search("tool", {
vectorSearchOptions: {
queries: [
{
kind: "vector",
vector: queryVector,
fields: ["embedding"],
kNearestNeighborsCount: 50,
},
],
},
select: ["id", "title", "description"],
top: 10,
});
セマンティック検索
// Index must have semantic configuration
const index: SearchIndex = {
name: "products",
fields: [...],
semanticSearch: {
configurations: [
{
name: "semantic-config",
prioritizedFields: {
titleField: { name: "title" },
contentFields: [{ name: "description" }],
},
},
],
},
};
// Search with semantic ranking
const results = await searchClient.search("best tool for the job", {
queryType: "semantic",
semanticSearchOptions: {
configurationName: "semantic-config",
captions: { captionType: "extractive" },
answers: { answerType: "extractive", count: 3 },
},
select: ["id", "title", "description"],
});
for await (const result of results.results) {
console.log(`${result.document.title}`);
console.log(` Caption: ${result.captions?.[0]?.text}`);
console.log(` Reranker Score: ${result.rerankerScore}`);
}
フィルターとファセット
// Filter syntax
const results = await searchClient.search("*", {
filter: "category eq 'Electronics' and price lt 100",
facets: ["category,count:10", "brand"],
});
// Access facets
for (const [facetName, facetResults] of Object.entries(results.facets || {})) {
console.log(`${facetName}:`);
for (const facet of facetResults) {
console.log(` ${facet.value}: ${facet.count}`);
}
}
オートコンプリートと候補表示
// Create suggester in index
const index: SearchIndex = {
name: "products",
fields: [...],
suggesters: [
{ name: "sg", sourceFields: ["title", "description"] },
],
};
// Autocomplete
const autocomplete = await searchClient.autocomplete("wid", "sg", {
mode: "twoTerms",
top: 5,
});
// Suggestions
const suggestions = await searchClient.suggest("wid", "sg", {
select: ["title"],
top: 5,
});
バッチ操作
// Batch upload, merge, delete
const batch = [
{ upload: { id: "1", title: "New Item" } },
{ merge: { id: "2", title: "Updated Title" } },
{ delete: { id: "3" } },
];
const result = await searchClient.indexDocuments({ actions: batch });
主な型
import {
SearchClient,
SearchIndexClient,
SearchIndexerClient,
SearchIndex,
SearchField,
SearchOptions,
VectorSearch,
SemanticSearch,
SearchIterator,
} from "@azure/search-documents";
ベストプラクティス
- ハイブリッド検索を使用する - ベクトル検索とテキスト検索を組み合わせて、最適な結果を得ます
- セマンティックランキングを有効にする - 自然言語クエリに対する関連性が向上します
- ドキュメントをまとめてアップロードする - 単一のドキュメントではなく、配列を指定して
uploadDocumentsを使用します - セキュリティにはフィルターを使用する - フィルターを使ってドキュメントレベルのセキュリティを実装します
- インデックスを段階的に更新する - 更新には
mergeOrUploadDocumentsを使用します - クエリのパフォーマンスを監視する - 本番環境では
includeTotalCount: trueを必要な場合に限って使用します
使用する場面
このスキルは、概要で説明されているワークフローまたはアクションを実行する場合に適用できます。
制限事項
- このスキルは、タスクが上記の範囲に明確に当てはまる場合にのみ使用してください。
- 出力を、環境固有の検証、テスト、または専門家によるレビューの代わりとして扱わないでください。
- 必要な入力、権限、安全上の境界、または成功基準が不明な場合は、作業を中断して確認してください。
コメント
Markdown 対応