Appearance
使用 Azure AI Search SDK 构建向量与混合搜索应用
解决复杂数据的检索难题:通过 Azure AI Search SDK 实现从传统全文检索到现代向量搜索(Vector Search)和语义搜索(Semantic Search)的升级,提升 AI 应用(如 RAG)的召回精度。
为什么需要这个技能
传统的关键词搜索在面对自然语言查询时经常失效,因为它们依赖于精确的词汇匹配,无法理解用户的真实意图。
通过引入向量搜索,我们可以将文档转换为数学向量,实现“语义层面的相似性”检索;而混合搜索(Hybrid Search)则结合了关键词的精确度和向量的泛化能力,再加上语义重排序(Semantic Ranking),能够极大地提升搜索结果的相关性,是构建企业级知识库和 AI 问答系统的核心底层能力。
适用场景
- 构建 RAG 架构:为 LLM 提供高质量的上下文增强检索。
- 电商产品搜索:实现基于属性过滤、分类聚合与语义相似性的商品查找。
- 企业文档中心:在海量非结构化数据中实现快速、精准的知识定位。
- 智能补全系统:利用 Suggester 实现搜索框的自动完成和建议功能。
核心工作流
1. 环境初始化与认证
首先安装依赖并配置环境变量,使用 DefaultAzureCredential 实现安全的身份验证。
bash
npm install @azure/search-documents @azure/identitytypescript
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);2. 构建索引(含向量字段)
定义索引结构,配置向量搜索算法(如 HNSW)和配置文件。
typescript
const index: SearchIndex = {
name: "products",
fields: [
{ name: "id", type: "Edm.String", key: true },
{ name: "title", type: "Edm.String", searchable: 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);3. 执行不同模式的搜索
- 全文搜索:基于关键词的传统检索。
- 向量搜索:基于 Embedding 向量的距离计算。
- 混合搜索:同时提交文本查询和向量查询,获取两者最优结合。
- 语义搜索:开启
queryType: "semantic",利用微软的语言模型对结果进行二次重排序。
typescript
// 混合搜索示例
const results = await searchClient.search("tool", {
vectorSearchOptions: {
queries: [{
kind: "vector",
vector: queryVector,
fields: ["embedding"],
kNearestNeighborsCount: 50,
}],
},
top: 10,
});下载和安装
下载 azure-search-documents-ts 中文版 Skill ZIP
解压后将目录放入你的 AI 工具 skills 文件夹,重启工具后即可使用。具体路径参考内附的 USAGE.zh.md。
你可能还需要
暂无推荐