Appearance
使用 .NET 构建 Azure AI Search 混合搜索应用
通过 Azure.Search.Documents SDK,开发者可以在 .NET 应用中快速集成企业级搜索能力,支持从简单的关键词匹配到复杂的向量与语义混合检索。
为什么需要这个技能
在构建现代 AI 应用(如 RAG 检索增强生成)时,传统的关键词搜索往往无法处理语义上的相似性,而纯向量搜索在处理精确术语(如产品型号)时效果不佳。
Azure AI Search 提供了“混合搜索”能力,允许将全文搜索、向量搜索和语义重排序(Semantic Ranking)结合在一起。掌握该 SDK 能让你在 C# 环境下高效地定义索引、管理文档并实现高相关性的搜索结果。
适用场景
- 智能知识库:构建支持自然语言问答的企业内部文档检索系统。
- 电商搜索:结合分类过滤(Facets)、排序和关键词匹配实现精准商品搜索。
- RAG 管道:作为 LLM 的检索层,通过向量和语义搜索提供高质量的上下文。
- 海量数据索引:需要快速上传、更新和删除大规模结构化/半结构化文档。
核心工作流
1. 环境配置与初始化
安装必要的 NuGet 包并配置身份验证。推荐在生产环境中使用 DefaultAzureCredential 以提高安全性。
bash
dotnet add package Azure.Search.Documents
dotnet add package Azure.Identitycsharp
using Azure.Identity;
using Azure.Search.Documents;
var credential = new DefaultAzureCredential();
var client = new SearchClient(
new Uri(Environment.GetEnvironmentVariable("SEARCH_ENDPOINT")),
Environment.GetEnvironmentVariable("SEARCH_INDEX_NAME"),
credential);2. 定义索引结构
利用 FieldBuilder 和模型特性(Attributes)定义字段,包括可搜索、可过滤、可排序以及向量字段。
csharp
public class Hotel
{
[SimpleField(IsKey = true, IsFilterable = true)]
public string HotelId { get; set; }
[SearchableField(IsSortable = true)]
public string HotelName { get; set; }
[VectorSearchField(VectorSearchDimensions = 1536, VectorSearchProfileName = "vector-profile")]
public ReadOnlyMemory<float>? DescriptionVector { get; set; }
}3. 实现混合搜索
将关键词查询与向量查询结合,并启用语义搜索配置,以获得最佳的排序效果。
csharp
var vectorQuery = new VectorizedQuery(embedding)
{
KNearestNeighborsCount = 5,
Fields = { "descriptionVector" }
};
var options = new SearchOptions
{
QueryType = SearchQueryType.Semantic,
SemanticSearch = new SemanticSearchOptions
{
SemanticConfigurationName = "my-semantic-config"
},
VectorSearch = new VectorSearchOptions
{
Queries = { vectorQuery }
}
};
var results = await searchClient.SearchAsync<Hotel>("luxury beachfront", options);下载和安装
下载 azure-search-documents-dotnet 中文版 Skill ZIP
解压后将目录放入你的 AI 工具 skills 文件夹,重启工具后即可使用。具体路径参考内附的 USAGE.zh.md。
你可能还需要
暂无推荐