deepskill

azure-search-documents-ts

azure-search-documents-ts

授权

使用 Azure AI Search JavaScript SDK(@azure/search-documents)构建搜索应用,用于创建或管理索引、实现向量或混合搜索、语义排序,以及通过知识库实现代理检索。

↓ 0 下载 ↗ 0 分享点击

介绍来源: author · microsoft · 3f5b461b2314e01c400564051e92469114c5b68f 参考来源

作者原文

Build search applications using Azure AI Search SDK for JavaScript (@azure/search-documents). Use when creating/managing indexes, implementing vector/hybrid search, semantic ranking, or building agentic retrieval with knowledge bases.

SkillPi 解读

能完成的任务
azure-search-documents-ts
适合谁
按原作者介绍判断适用范围。
输入和输出
以完整原文为准,云端传输需由使用者确认。
软件、账号及付费要求
本包是 azure-search-documents-ts 的 Microsoft Azure SDK 文档与示例,不含已验证的可执行安装程序。使用示例前核对 SDK 包名、版本、Azure 租户/订阅和实际终结点,仅授予本任务所需的最小权限;不把管理员凭据或真实机密写进示例、日志或提交。示例连接的云服务可能接收所选文本、文档、音频、消息、日志或其他输入并产生费用;确认数据范围、脱敏及费用后再连接。创建、更新、删除资源、密钥/权限变更或发送消息须由用户逐项确认,在测试资源上验证,避免生产数据覆盖与不可逆操作。文档中的占位终结点和样例输入必须替换并核对;网站仅核对固定源版本、完整附件和静态/病毒库证据,未运行 SDK、验证外部服务兼容性或授权任何云访问。
限制与区别
原作者介绍原样保留,中文为对应翻译。文档示例未经本站运行;版本、兼容性和效果为作者陈述。
实测状态
未测试

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

  • 安装或获取外部依赖

    使用官方来源并锁定版本,在隔离环境检查安装脚本。当前文档检查不覆盖后续下载的代码。

    主文档提及 · 第 18 行
  • 账号、密钥或授权

    使用专用、最小权限账号,不把密钥粘贴到公开内容或命令日志;核对接收数据的服务与租户。

    主文档提及 · 第 27, 34, 38, 39, 40 行
文档引用的域名或地址

这些地址可能用于文档链接或示例,不是已批准的联网清单。使用前核对实际目的地及发送的数据。

  • learn.microsoft.com

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

caution · 静态证据核验,不代表运行安全保证。

本包是 azure-search-documents-ts 的 Microsoft Azure SDK 文档与示例,不含已验证的可执行安装程序。使用示例前核对 SDK 包名、版本、Azure 租户/订阅和实际终结点,仅授予本任务所需的最小权限;不把管理员凭据或真实机密写进示例、日志或提交。示例连接的云服务可能接收所选文本、文档、音频、消息、日志或其他输入并产生费用;确认数据范围、脱敏及费用后再连接。创建、更新、删除资源、密钥/权限变更或发送消息须由用户逐项确认,在测试资源上验证,避免生产数据覆盖与不可逆操作。文档中的占位终结点和样例输入必须替换并核对;网站仅核对固定源版本、完整附件和静态/病毒库证据,未运行 SDK、验证外部服务兼容性或授权任何云访问。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。

原始 SKILL.md

---
name: azure-search-documents-ts
description: Build search applications using Azure AI Search SDK for JavaScript (@azure/search-documents). Use when creating/managing indexes, implementing vector/hybrid search, semantic ranking, or building agentic retrieval with knowledge bases.
license: MIT
metadata:
  author: Microsoft
  version: "1.0.0"
  package: '@azure/search-documents'
---

# Azure AI Search SDK for TypeScript

Build search applications with vector, hybrid, and semantic search capabilities.

## Installation

```bash
npm install @azure/search-documents @azure/identity
```

## Environment Variables

```bash
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
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
```

## Authentication

```typescript
import { SearchClient, SearchIndexClient } from "@azure/search-documents";
import { DefaultAzureCredential, ManagedIdentityCredential } from "@azure/identity";

const endpoint = process.env.AZURE_SEARCH_ENDPOINT!;
const indexName = process.env.AZURE_SEARCH_INDEX_NAME!;
// Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
const credential = new DefaultAzureCredential({requiredEnvVars: ["AZURE_TOKEN_CREDENTIALS"]});
// Or use a specific credential directly in production:
// See https://learn.microsoft.com/javascript/api/overview/azure/identity-readme?view=azure-node-latest#credential-classes
// const credential = new ManagedIdentityCredential();

// For searching
const searchClient = new SearchClient(endpoint, indexName, credential);

// For index management
const indexClient = new SearchIndexClient(endpoint, credential);
```

## Core Workflow

### Create Index with Vector Field

```typescript
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);
```

### Index Documents

```typescript
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);
console.log(`Indexed ${result.results.length} documents`);
```

### Full-Text Search

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

### Vector Search

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

### Hybrid Search (Text + Vector)

```typescript
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,
});
```

### Semantic Search

```typescript
// 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}`);
}
```

## Filtering and Facets

```typescript
// 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}`);
  }
}
```

## Autocomplete and Suggestions

```typescript
// 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 Operations

```typescript
// 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 });
```

## Key Types

```typescript
import {
  SearchClient,
  SearchIndexClient,
  SearchIndexerClient,
  SearchIndex,
  SearchField,
  SearchOptions,
  VectorSearch,
  SemanticSearch,
  SearchIterator,
} from "@azure/search-documents";
```

## Best Practices

1. **Use hybrid search** - Combine vector + text for best results
2. **Enable semantic ranking** - Improves relevance for natural language queries
3. **Batch document uploads** - Use `uploadDocuments` with arrays, not single docs
4. **Use filters for security** - Implement document-level security with filters
5. **Index incrementally** - Use `mergeOrUploadDocuments` for updates
6. **Monitor query performance** - Use `includeTotalCount: true` sparingly in production

版权与许可声明

    MIT License

    Copyright (c) Microsoft Corporation.

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE