在 .NET AI 应用中使用矢量存储

📦 Microsoft。Extensions.VectorData.Abstractions (MEVD) 包提供统一的 API,用于处理 .NET 中的矢量存储。 可以使用相同的代码跨不同的向量数据库提供商存储和搜索向量表示。

本文介绍如何使用库的主要功能。

先决条件

安装软件包

安装矢量数据库的提供程序包。 Microsoft.Extensions.VectorData.Abstractions 包作为可传递依赖项自动引入。 以下示例使用内存中提供程序进行开发和测试:

dotnet package add Microsoft.SemanticKernel.Connectors.InMemory --prerelease

对于生产方案,请将 Microsoft.SemanticKernel.Connectors.InMemory 替换为数据库的提供程序。 有关可用提供程序,请参阅 开箱即用的矢量存储提供程序。 (尽管在提供程序包名称中包含“SemanticKernel”,但这些提供程序与语义内核无关,并且可以在.NET(包括代理框架)中使用。

定义数据模型

定义一个.NET类来表示要存储在向量存储中的记录。 根据属性是表示主键、常规数据还是向量数据,使用属性对类中的属性进行批注。 下面是一个简单示例:

public class Hotel
{
    [VectorStoreKey]
    public ulong HotelId { get; set; }

    [VectorStoreData(IsIndexed = true)]
    public required string HotelName { get; set; }

    [VectorStoreData(IsFullTextIndexed = true)]
    public required string Description { get; set; }

    [VectorStoreVector(Dimensions: 4, DistanceFunction = DistanceFunction.CosineSimilarity, IndexKind = IndexKind.Hnsw)]
    public ReadOnlyMemory<float>? DescriptionEmbedding { get; set; }

    [VectorStoreData(IsIndexed = true)]
    public required string[] Tags { get; set; }
}

作为使用属性的替代方案,你可以通过程序来定义架构VectorStoreCollectionDefinition。 如果要对不同配置使用相同的数据模型,或者无法向数据模型类添加属性,此方法非常有用。

有关详细信息,请参阅 “定义数据模型”。

创建矢量存储

为所选数据库创建实现的 VectorStore 实例。 以下示例创建内存中向量存储:

// Create an in-memory vector store (no external service required).
// For production, replace this with a connector for your preferred database.
var vectorStore = new InMemoryVectorStore();

获取集合

GetCollection调用VectorStore以获取类型化的VectorStoreCollection<TKey,TRecord>引用。 然后调用 EnsureCollectionExistsAsync 以创建集合(如果尚不存在):

// Get a reference to a collection named "hotels".
VectorStoreCollection<int, Hotel> collection =
    vectorStore.GetCollection<int, Hotel>("hotels");

// Ensure the collection exists in the database.
await collection.EnsureCollectionExistsAsync();

集合名称映射到数据库的基础存储概念(例如,SQL Server中的表、Azure AI 搜索中的索引或 Cosmos DB 中的容器)。

更新或插入记录

用于 UpsertAsync 在集合中插入或更新记录。 如果已存在具有相同键的记录,则会更新该记录:

// Upsert records into the collection.
// In a real app, generate embeddings using an IEmbeddingGenerator.
// The CreateFakeEmbedding helper at the bottom of this file generates
// placeholder vectors for demonstration purposes only.
var hotels = new List<Hotel>
{
    new()
    {
        HotelId = 1,
        HotelName = "Seaside Retreat",
        Description = "A peaceful hotel on the coast with stunning ocean views.",
        DescriptionEmbedding = CreateFakeEmbedding(1),
        Tags = ["beach", "ocean", "relaxation"]
    },
    new()
    {
        HotelId = 2,
        HotelName = "Mountain Lodge",
        Description = "A cozy lodge in the mountains with hiking trails nearby.",
        DescriptionEmbedding = CreateFakeEmbedding(2),
        Tags = ["mountain", "hiking", "nature"]
    },
    new()
    {
        HotelId = 3,
        HotelName = "City Centre Hotel",
        Description = "A modern hotel in the heart of the city, close to attractions.",
        DescriptionEmbedding = CreateFakeEmbedding(3),
        Tags = ["city", "business", "urban"]
    }
};

foreach (Hotel h in hotels)
{
    await collection.UpsertAsync(h);
}

重要

建议在实际应用中,在存储记录之前 让 MEVD 生成嵌入。

获取记录

使用 GetAsync 通过键检索单个记录。 若要检索多个记录,请传递一个 IEnumerable<TKey> 到 GetAsync:

// Get a specific record by its key.
Hotel? hotel = await collection.GetAsync(1);
if (hotel is not null)
{
    Console.WriteLine($"Hotel: {hotel.HotelName}");
    Console.WriteLine($"Description: {hotel.Description}");
}

一次检索多个记录:

// Get multiple records by their keys.
IAsyncEnumerable<Hotel> hotelBatch = collection.GetAsync([1, 2, 3]);
await foreach (Hotel h in hotelBatch)
{
    Console.WriteLine($"Batch hotel: {h.HotelName}");
}

用于 SearchAsync 查找语义上类似于查询的记录。 传递查询的嵌入向量和要返回的结果数:

// Search for the top 2 hotels most similar to the query embedding.
IAsyncEnumerable<VectorSearchResult<Hotel>> searchResults =
    collection.SearchAsync(queryEmbedding, top: 2);

await foreach (VectorSearchResult<Hotel> result in searchResults)
{
    Console.WriteLine($"Found: {result.Record.HotelName} (score: {result.Score:F4})");
}

每个 VectorSearchResult<TRecord> 记录都包含匹配记录和相似性分数。 更高的分数表示更接近的语义匹配。

筛选搜索结果

用于 VectorSearchOptions<TRecord> 在矢量比较之前筛选搜索结果。 可以筛选任何带有IsIndexed = true标记的属性。

// Filter results before the vector comparison.
// Only properties marked with IsIndexed = true can be used in filters.
var searchOptions = new VectorSearchOptions<Hotel>
{
    Filter = h => h.HotelName == "Seaside Retreat"
};

IAsyncEnumerable<VectorSearchResult<Hotel>> filteredResults =
    collection.SearchAsync(queryEmbedding, top: 2, searchOptions);

await foreach (VectorSearchResult<Hotel> result in filteredResults)
{
    Console.WriteLine($"Filtered: {result.Record.HotelName} (score: {result.Score:F4})");
}

筛选器表示为 LINQ 表达式。 支持的操作因提供程序而异,但所有提供程序都支持常见的比较,例如相等、不相等和逻辑&&运算||。

使用 VectorSearchOptions 控制搜索行为

使用 VectorSearchOptions<TRecord> 控制矢量搜索行为的各个方面。

// Use VectorSearchOptions to control paging and vector inclusion.
var pagedOptions = new VectorSearchOptions<Hotel>
{
    Skip = 1,           // Skip the first result (useful for paging).
    IncludeVectors = false  // Don't include vector data in results (default).
};

IAsyncEnumerable<VectorSearchResult<Hotel>> pagedResults =
    collection.SearchAsync(queryEmbedding, top: 2, pagedOptions);

await foreach (VectorSearchResult<Hotel> result in pagedResults)
{
    Console.WriteLine($"Paged: {result.Record.HotelName}");
}

下表描述了可用选项:

选项 说明
Filter 用于在矢量比较之前筛选记录的 LINQ 表达式。
VectorProperty 要搜索的向量属性。 当数据模型具有多个矢量属性时是必需的。
Skip 返回前要跳过的结果数。 可用于分页。 默认值为 0。
IncludeVectors 是否在返回的记录中包含矢量数据。 省略向量可减少数据传输。 默认值为 false。

有关详细信息,请参阅 矢量搜索。

使用内置嵌入生成

在每次执行更新插入操作之前无需手动生成嵌入内容,您可以在矢量数据库或集合上配置 IEmbeddingGenerator。 执行此操作时,请将向量属性声明为 string 类型(源文本),并且存储会自动生成嵌入。

有关详细信息,请参阅 自动嵌入生成。

某些矢量存储支持 混合搜索,该搜索将矢量相似性与关键字匹配相结合。 与仅矢量搜索相比,此方法可以提高结果相关性。

若要使用混合搜索,请检查集合是否实现 IKeywordHybridSearchable<TRecord>。 只有支持此功能的数据库的提供程序才能实现此接口。

有关详细信息,请参阅 混合搜索。

删除记录

若要按键删除单个记录,请使用 DeleteAsync:

// Delete a record by its key.
await collection.DeleteAsync(3);

删除集合

若要从向量存储中删除整个集合,请使用 EnsureCollectionDeletedAsync:

// Delete the entire collection from the vector store.
await collection.EnsureCollectionDeletedAsync();

切换向量存储服务商

由于所有提供程序都实现相同的 VectorStore 抽象类,因此可以通过在启动时更改具体类型来切换它们。 在大多数情况下,集合和搜索代码保持不变。 但是,通常需要某些调整,例如,因为不同的数据库支持不同的数据类型。