基于Microsoft.Extensions.VectorData實(shi)現(xian)語義搜索(suo)
大家好,我是(shi)Edison。
上周水了一篇 Microsoft.Extensions.AI 的介紹文章,很多讀者反饋想要了解更多。很多時候,除了集成LLM實現聊天對話,還會有很多語義搜索和RAG的使用場景,那么今天就給大家介紹一下如何完成語義搜索。
Microsoft.Extensions.VectorData介紹
語義搜索正在改變應用程序查找和解釋數據的方式,它(ta)專注于語義(yi)關聯,而不僅僅是關鍵(jian)字匹(pi)配。
Microsoft.Extensions.VectorData 是一組 .NET代(dai)碼庫,旨(zhi)在管理(li)(li) .NET 應用程序中基于向量(liang)的(de)數(shu)據(ju)。這些庫為與向量(liang)存儲交互(hu)提供(gong)了一個統一的(de) C# 抽象(xiang)層(ceng),使開發人員能(neng)夠(gou)有效地處理(li)(li)嵌入并執行向量(liang)相似性查詢。

更多(duo)該代碼庫的內容請參考(kao):Luis 《》
在接下(xia)來的demo中,我們會使用以(yi)下(xia)工具(ju):
(1) Qdrant 作為 VectorStore
(2) Ollama 運行(xing) all-minilm 模型 作(zuo)為 Emedding生成器
ollama pull all-minilm
Qdrant向量搜索引擎
Qdrant是一個向量(liang)相似性(xing)搜(sou)索引(yin)擎,它提供了一個生產就緒的(de)(de)服務,擁(yong)有便捷的(de)(de) API來存儲、搜(sou)索和管理帶有額外(wai)負載(zai)的(de)(de)點(即向量(liang))。它非(fei)常適合需要高(gao)效相似性(xing)搜(sou)索的(de)(de)應用程序(xu)。我們可以在 Docker 容器中(zhong)運行 它,這也使它成為對(dui)開發人員友好的(de)(de)選(xuan)擇。
容器(qi)運行(xing)Qdrant:
docker run -p 6333:6333 -p 6334:6334 \ -v $(pwd)/qdrant_storage:/qdrant/storage \ qdrant/qdrant
驗證Qdrant運行:訪問 server:6333/dashboard

開始DEMO案例
安裝NuGet包:
Microsoft.Extensions.AI (preview)
Microsoft.Extensions.Ollama (preivew)
Microsoft.Extensions.AI.OpenAI (preivew)
Microsoft.Extensions.VectorData.Abstractions (preivew)
Microsoft.SemanticKernel.Connectors.Qdrant (preivew)
這(zhe)里(li)我們假設(she)做(zuo)一個CloudService的語義搜索,分下面一些步(bu)驟來實現(xian)它(ta)。
Step1. 配置文件appsettings.json:
{ "Embedding": { "EndPoint": "//localhost:11434", "Model": "all-minilm" }, "Qdrant": { "Host": "edt-dev-server", "Port": 6334 } }
Step2. 加載配(pei)置:
var config = new ConfigurationBuilder() .AddJsonFile($"appsettings.json") .Build();
Step3. 初始化Embedding生成器:這里我們(men)使(shi)用的是本地的Ollama運行all-minilm模(mo)型來(lai)做。
var generator = new OllamaEmbeddingGenerator(new Uri(config["Embedding:EndPoint"]), config["Embedding:Model"]);
此外,我(wo)們也可以使用OpenAI的Embedding服務:
var generator = new OpenAIClient(new ApiKeyCredential(config["OneAPI:ApiKey"]), new OpenAIClientOptions() { Endpoint = new Uri(config["OneAPI:EndPoint"]) }) .AsEmbeddingGenerator(modelId: config["Embedding:ModelId"]);
Step4. 初始化Qdrant向量存儲:
var vectorStore = new QdrantVectorStore(new QdrantClient(config["Qdrant:Host"], int.Parse(config["Qdrant:Port"]))); // Get the collection if it exist in qdrant var cloudServicesStore = vectorStore.GetCollection<ulong, CloudService>("cloudServices"); // Create the collection if it doesn't exist yet. await cloudServicesStore.CreateCollectionIfNotExistsAsync();
Step5. 插(cha)入測試數據:
// Define the test data var cloudServices = new List<CloudService>() { new CloudService { Key=1, Name="Azure App Service", Description="Host .NET, Java, Node.js, and Python web applications and APIs in a fully managed Azure service. You only need to deploy your code to Azure. Azure takes care of all the infrastructure management like high availability, load balancing, and autoscaling." }, new CloudService { Key=2, Name="Azure Service Bus", Description="A fully managed enterprise message broker supporting both point to point and publish-subscribe integrations. It's ideal for building decoupled applications, queue-based load leveling, or facilitating communication between microservices." }, new CloudService { Key=3, Name="Azure Blob Storage", Description="Azure Blob Storage allows your applications to store and retrieve files in the cloud. Azure Storage is highly scalable to store massive amounts of data and data is stored redundantly to ensure high availability." }, new CloudService { Key=4, Name="Microsoft Entra ID", Description="Manage user identities and control access to your apps, data, and resources.." }, new CloudService { Key=5, Name="Azure Key Vault", Description="Store and access application secrets like connection strings and API keys in an encrypted vault with restricted access to make sure your secrets and your application aren't compromised." }, new CloudService { Key=6, Name="Azure AI Search", Description="Information retrieval at scale for traditional and conversational search applications, with security and options for AI enrichment and vectorization." } }; // Insert test data into the collection in qdrant foreach (var service in cloudServices) { service.Vector = await generator.GenerateEmbeddingVectorAsync(service.Description); await cloudServicesStore.UpsertAsync(service); }
其中(zhong),CloudService的定義(yi)如下:
public class CloudService { [VectorStoreRecordKey] public ulong Key { get; set; } [VectorStoreRecordData] public string Name { get; set; } [VectorStoreRecordData] public string Description { get; set; } [VectorStoreRecordVector(384, DistanceFunction.CosineSimilarity)] public ReadOnlyMemory<float> Vector { get; set; } }
Step6. 生成查(cha)詢Emedding并從(cong)Qdrant中執(zhi)行(xing)查(cha)詢:
// Generate query embedding var query = "Which Azure service should I use to store my Word documents?"; var queryEmbedding = await generator.GenerateEmbeddingVectorAsync(query); // Query from vector data store var searchOptions = new VectorSearchOptions() { Top = 1, // Only return the Top 1 record from Qdrant VectorPropertyName = "Vector" }; var results = await cloudServicesStore.VectorizedSearchAsync(queryEmbedding, searchOptions); await foreach (var result in results.Results) { Console.WriteLine($"Name: {result.Record.Name}"); Console.WriteLine($"Description: {result.Record.Description}"); Console.WriteLine($"Vector match score: {result.Score}"); Console.WriteLine(); }
首先,驗證(zheng)下Qdrant中(zhong)是否新增了(le)數據(ju):

其次,查看運行結(jie)果顯(xian)示:返(fan)回(hui)(hui)最匹配(pei)的一個數據返(fan)回(hui)(hui),因為我們設置的Top1記錄。

完整的代碼示(shi)例請參(can)考該示(shi)例代碼的。
小結
本(ben)(ben)(ben)文介紹了Microsoft.Extensions.Vector的(de)基本(ben)(ben)(ben)概念 和 基本(ben)(ben)(ben)使用,結合Embedding Model(如(ru)all-minilm) 和 VectorStore(如(ru)Qdrant),我(wo)們可(ke)以快速(su)實現語(yu)義搜索,而不僅僅是(shi)關鍵字匹(pi)配。
如果(guo)你也是.NET程序員(yuan)希望參與AI應(ying)用的開發,那就快快了解和(he)使(shi)用基于Microsoft.Extensioins.AI的生態組(zu)件庫吧。
參考內容
Eddie Chen,《探索Microsoft.Extensions.VectorData與Qdrant和Azure AI搜索的使用》
Luis,《Introducting Microsoft.Extensions.VectorData》
路(lu)邊(bian)石,《Microsoft.Extensions.AI.OpenAI官(guan)方代碼示例(li)》
推(tui)薦內(nei)容(rong)

作者:
出處:
本文(wen)版權歸作(zuo)者和(he)博客園共有,歡迎轉載(zai),但未經作(zuo)者同意必須保留此段聲明,且在文(wen)章頁面明顯(xian)位置給出(chu)原文(wen)鏈接。

本文介紹了Microsoft.Extensions.Vector的基本概念 和 基本使用,結合Embedding Model(如all-minilm) 和 VectorStore(如Qdrant),我們可以快速實現語義搜索,而不僅僅是關鍵字匹配。如果你也是.NET程序員希望參與AI應用的開發,那就快快了解和使用基于Microsoft.Extensioins.AI的生態組件庫吧。