Azure 搜索文档 TypeScript SDK

azure-search-documents-ts
分类编程
作者Agentic Awesome Skills 社区
许可MIT
评分4.50/5
使用5.4K

Azure AI Search TypeScript SDK

构建具备向量、混合和语义搜索能力的搜索应用程序。

安装

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

环境变量

bash
AZURE_SEARCH_ENDPOINT=https://<service-name>.search.windows.net
AZURE_SEARCH_INDEX_NAME=my-index
AZURE_SEARCH_ADMIN_KEY=<admin-key>  # 如果使用 Entra ID 则为可选

身份验证

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

// 用于搜索
const searchClient = new SearchClient(endpoint, indexName, credential);

// 用于索引管理
const indexClient = new SearchIndexClient(endpoint, credential);

核心工作流

创建包含向量字段的索引

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

索引文档

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(已索引 ${result.results.length} 个文档);

全文搜索

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

向量搜索

typescript
const queryVector = await getEmbedding("useful tool"); // 您的 embedding 函数

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

混合搜索 (文本 + 向量)

typescript
const queryVector = await getEmbedding("useful tool");

const results = await searchClient.search("tool", {
vectorSearchOptions: {
queries: [
{
kind: "vector",
vector: queryV


ector,
fields: ["embedding"],
kNearestNeighborsCount: 50,
},
],
},
select: ["id", "title", "description"],
top: 10,
});
code
### 语义搜索 (Semantic Search)
typescript
// 索引必须包含语义配置
const index: SearchIndex = {
name: "products",
fields: [...],
semanticSearch: {
configurations: [
{
name: "semantic-config",
prioritizedFields: {
titleField: { name: "title" },
contentFields: [{ name: "description" }],
},
},
],
},
};

// 使用语义排序进行搜索
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});
}

code
## 过滤与分面 (Filtering and Facets)
typescript
// 过滤语法
const results = await searchClient.search("*", {
filter: "category eq 'Electronics' and price lt 100",
facets: ["category,count:10", "brand"],
});

// 访问分面结果
for (const [facetName, facetResults] of Object.entries(results.facets || {})) {
console.log(${facetName}:);
for (const facet of facetResults) {
console.log( ${facet.value}: ${facet.count});
}
}

code
## 自动完成与建议 (Autocomplete and Suggestions)
typescript
// 在索引中创建建议器 (Suggester)
const index: SearchIndex = {
name: "products",
fields: [...],
suggesters: [
{ name: "sg", sourceFields: ["title", "description"] },
],
};

// 自动完成
const autocomplete = await searchClient.autocomplete("wid", "sg", {
mode: "twoTerms",
top: 5,
});

// 建议
const suggestions = await searchClient.suggest("wid", "sg", {
select: ["title"],
top: 5,
});

code
## 批量操作 (Batch Operations)
typescript
// 批量上传、合并、删除
const batch = [
{ upload: { id: "1", title: "New Item" } },
{ merge: { id: "2", title: "Updated Title" } },
{ delete: { id: "3" } },
];

const result = await searchClient.indexDocuments({ actions: batch });

code
## 关键类型 (Key Types)
typescript
import {
SearchClient,
SearchIndexClient,
SearchIndexerClient,
SearchIndex,
SearchField,
SearchOptions,
VectorSearch,
SemanticSearch,
SearchIterator,
} from "@azure/search-documents";
``

最佳实践

1. 使用混合搜索 - 结合向量搜索和文本搜索以获得最佳结果。
2. 启用语义排序 - 提高自然语言查询的相关性。
3. 批量上传文档 - 使用数组形式的
uploadDocuments,而非单个文档。
4. 使用过滤器实现安全控制 - 通过过滤器实现文档级安全访问。
5. 增量索引 - 使用
mergeOrUploadDocuments 进行更新。
6. 监控查询性能 - 在生产环境中谨慎使用
includeTotalCount: true`。

适用场景

本技能适用于执行概述中描述的工作流或操作。

局限性

  • 仅在任务明确符合上述范围时使用此技能。
  • 不要将输出视为特定环境验证、测试或专家评审的替代方案。
  • 如果缺少必要的输入、权限、安全边界或成功标准,请停止并请求澄清。