对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
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!;
}

The embedded_movies collection is part of the sample datasets provided by Atlas. To set up a cluster and load this sample data, see the Get Started with the EF Core Provider guide.

要将 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);
});
}
}

注意

You cannot change or delete indexes by using the EF Core Provider after they are created. To change or delete an index, use the .NET/C# Driver. To learn more, see the MongoDB Search and MongoDB Vector Search Indexes guide in the .NET/C# Driver documentation.

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 命名空间包含用于配置二进制向量索引的 VectorQuantization 和 VectorSimilarity 枚举。

您可以使用 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();

To learn more about MongoDB Vector Search, see the MongoDB Vector Search documentation.

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