使用矢量存储提供程序进行矢量搜索

Microsoft.Extensions.VectorData 库在其矢量存储抽象中提供矢量搜索功能。 这些功能包括筛选和其他许多选项。

该方法 SearchAsync 执行相似性搜索,返回其矢量属性最类似于给定值的记录。 假设你有一个已包含数据的集合,下面是使用 Qdrant 显示矢量搜索的最小示例:

// Create a Qdrant VectorStore object and get a VectorStoreCollection for a collection that already contains records
VectorStore vectorStore = new QdrantVectorStore(new QdrantClient("localhost"), ownsClient: true);
VectorStoreCollection<ulong, Hotel> collection = vectorStore.GetCollection<ulong, Hotel>("skhotels");

// Get the 3 hotels whose vector property is most similar to the query text
IAsyncEnumerable<VectorSearchResult<Hotel>> results = collection.SearchAsync("Big rooms with a view", top: 3);

// Inspect the returned hotels and their similarity scores
await foreach (VectorSearchResult<Hotel> record in results)
{
    Console.WriteLine("Found hotel description: " + record.Record.Description);
    Console.WriteLine("Found record score: " + record.Score);
}

有关嵌入生成的详细信息,请参阅 矢量属性和嵌入生成。

结果数和跳过结果数

SearchAsync 具有一个强制 top 参数,用于控制从搜索返回的最大记录数。 始终考虑实际需要多少条顶级记录,因为过度提取可以减少应用程序性能:

IAsyncEnumerable<VectorSearchResult<Hotel>> searchResult = collection.SearchAsync("Big rooms with a view", top: 3);

此外,还可以选择跳过记录。 例如,以下搜索在跳过 40 后返回 20 个最相关的产品:

IAsyncEnumerable<VectorSearchResult<Product>> results = collection.SearchAsync(
    "Green socks",
    top: 20,
    new() { Skip = 40 });

top 和 Skip 可用于执行分页,以通过单独的调用来检索大量结果。 但是,此方法可能无法在数据库上表现良好,因为它仍必须查找并处理跳过的记录。 有关详细信息,请参阅数据库文档。

元数据筛选

VectorSearchOptions<TRecord>.Filter使用选项在应用矢量搜索之前筛选所选集合中的记录。 这具有多个优势:

  • 降低延迟和处理成本,因为筛选后剩余的记录需要与搜索向量进行比较,因此必须进行更少的矢量比较。
  • 限制结果集。 例如,可以通过排除用户不应访问的数据或仅在特定类别的产品内搜索来实现访问控制。

对于要用于筛选的字段,许多向量存储要求先为这些字段编制索引。 有关如何对数据属性启用索引的详细信息,请参阅 Data 属性。

筛选器使用基于数据模型类型的 LINQ 表达式表示。 支持的 LINQ 表达式集因每个数据库支持的功能而异,但所有数据库都支持广泛的通用表达式,例如相等、不等于 and和 or。

class Glossary
{
    // ...

    // Category is marked as indexed, since you want to filter using this property.
    [VectorStoreData(IsIndexed = true)]
    public required string Category { get; set; }

    // Tags is marked as indexed, since you want to filter using this property.
    [VectorStoreData(IsIndexed = true)]
    public required List<string> Tags { get; set; }
}

IAsyncEnumerable<VectorSearchResult<Glossary>> results = collection.SearchAsync(
    "Some term",
    top: 3,
    new()
    {
        Filter = r => r.Category == "External Definitions" && r.Tags.Contains("memory")
    });

在结果中包含向量

默认情况下,搜索结果中不包含矢量属性,从而减少数据传输。 可以配置搜索以包括它们:

IAsyncEnumerable<VectorSearchResult<Product>> results = collection.SearchAsync(
    "Green socks",
    top: 3,
    new() { IncludeVectors = true });

指定向量属性

在大多数情况下,数据模型中只定义了一个向量属性,并 SearchAsync 自动搜索该属性。 但是,定义多个向量属性时,必须指定应使用哪一个:

class Product
{
    // ...

    // Multiple vector properties:
    [VectorStoreVector(1536)]
    public ReadOnlyMemory<float> DescriptionEmbedding { get; set; }

    [VectorStoreVector(1536)]
    public ReadOnlyMemory<float> FeatureListEmbedding { get; set; }
}

IAsyncEnumerable<VectorSearchResult<Hotel>> results = collection.SearchAsync(
    "I'm looking for a product with a specific feature.",
    top: 3,
    new() { VectorProperty = r => r.FeatureListEmbedding });

混合搜索将矢量相似性搜索与传统关键字搜索相结合,并行执行并返回两个结果集的组合。 这可以提高搜索质量,因为关键字匹配可以捕获矢量相似性可能错过的确切字词匹配,反之亦然。

注释

混合搜索仅适用于支持混合搜索的数据库。 只有这些数据库的提供程序实现 IKeywordHybridSearchable<TRecord> 接口。

若要使用混合搜索,数据模型需要通过以下方式 IsFullTextIndexed启用全文搜索的字符串字段:

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

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

    [VectorStoreVector(1536)]
    public string DescriptionEmbedding { get; set; }
}

然后调用 HybridSearchAsync,传递搜索文本和关键字:

var hybridCollection = (IKeywordHybridSearchable<Hotel>)collection;

IAsyncEnumerable<VectorSearchResult<Hotel>> results = hybridCollection.HybridSearchAsync(
    "I'm looking for a hotel where customer happiness is the priority.",
    ["happiness", "hotel", "customer"],
    top: 3);

用于向量搜索(top、Skip、Filter、IncludeVectors、VectorProperty)的所有选项也可通过HybridSearchOptions<TRecord>进行混合搜索。

此外,混合搜索还支持用于 AdditionalProperty 指定要定位的全文搜索属性的选项。 如果数据模型只有一个属性, IsFullTextIndexed = true则会自动使用它;如果有多个属性,则必须指定以下属性:

IAsyncEnumerable<VectorSearchResult<Hotel>> results = hybridCollection.HybridSearchAsync(
    "I'm looking for a hotel where customer happiness is the priority.",
    ["happiness", "hotel", "customer"],
    top: 3,
    new()
    {
        VectorProperty = r => r.DescriptionEmbedding,
        AdditionalProperty = r => r.Description
    });