对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
MongoDB Branding Shape
Click here >
Docs 菜单

运行Atlas Vector Search查询

您可以将 MongoDB 向量搜索与 EF Core 提供商一起使用,对存储在 Atlas 中的数据执行语义搜索。向量搜索基于语义含义而非关键字匹配来查询数据,从而可以检索到更相关的结果。您可以使用 MongoDB 向量搜索来支持语义搜索、混合搜索和检索增强生成 (RAG)等使用案例。

要学习;了解有关MongoDB Vector Search 的更多信息,请参阅Atlas文档中的MongoDB Vector Search 概述

本指南中的示例使用 sample_mflix数据库中的 embedded_movies集合。此集合中的文档使用以下 Movie 类作为模型:

public class Movie
{
public ObjectId Id { get; set; }
public string Title { get; set; } = null!;
public string Plot { get; set; } = null!;
public float[] PlotEmbedding { get; set; } = null!;
}

embedded_movies 集合是 Atlas 提供的示例数据集的一部分。要设置集群并加载此示例数据,请参阅 快速入门 指南。

要将 MongoDB 向量搜索与 EF Core 提供商一起使用,请在实体类上定义向量字段。使用 IsVectorIndex() 流畅 API 方法在该字段上配置向量索引。

以下示例定义了一个具有名为 PlotEmbedding 的向量字段的 Movie 实体,并在该字段上配置了向量索引。

public class MoviesDbContext : DbContext
{
public DbSet<Movie> Movies { get; init; } = null!;
public MoviesDbContext(DbContextOptions options) : base(options) { }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Movie>(entity =>
{
entity.ToCollection("embedded_movies");
entity.Property(m => m.Title).HasElementName("title");
entity.Property(m => m.Plot).HasElementName("plot");
entity.Property(m => m.PlotEmbedding).HasElementName("plot_embedding")
.HasBinaryVectorDataType(BinaryVectorDataType.Float32);
entity.HasIndex(m => m.PlotEmbedding, "vector_index")
.IsVectorIndex(VectorSimilarity.Cosine, 1536);
});
}
}

注意

创建索引后,您不能使用 EF Core 提供商更改或删除索引。要更改或删除索引,请使用 .NET/C# 驱动程序。要了解更多信息,请参阅 .NET/C# 驱动程序文档中的 MongoDB Search 和 MongoDB 向量搜索索引指南。

EF Core 提供商支持以下类型的向量嵌入:

EF Core 提供商支持以下数组类型作为向量嵌入:

  • float[]

  • double[]

  • Memory<float>ReadOnlyMemory<float>

  • Memory<double>ReadOnlyMemory<double>

EF Core 提供商支持以下二进制向量类型,与数组类型相比,这些类型可以减少存储并提高查询性能:

  • BinaryVectorFloat32 — 全精度 32 位浮点

  • BinaryVectorInt8 — 8 位量化整数

  • BinaryVectorPackedBit — 1位打包二进制值

.NET/C# 驱动程序的 MongoDB.Driver 命名空间包含用于配置二进制向量索引的 VectorQuantizationVectorSimilarity 枚举。

您可以使用 VectorSearch() 方法运行向量搜索查询。以下示例查询 embedded_movies 集合中具有与 "时间旅行冒险" 在语义上相似的 PlotEmbedding 字段值的电影,然后返回最多 10 个匹配文档。

// Replace queryVector with a 1536-dimension embedding vector from your model
float[] queryVector = new float[] { 0.1f, -0.2f, 0.3f, ... };
var results = context.Movies
.VectorSearch(m => m.PlotEmbedding, queryVector, limit: 10)
.ToList();

要了解有关 MongoDB Vector Search 的更多信息,请参阅 MongoDB Vector Search 文档。

有关 API 文档,请参阅以下资源: