对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

运行MongoDB Vector Search 查询

In this guide, you can learn how to use Django MongoDB Backend to perform MongoDB Vector Search queries. This feature allows you to perform a semantic search on your documents. A semantic search is a type of search that locates information that is similar in meaning, but not necessarily identical, to your provided search term or phrase.

The examples in this guide use the MovieWithEmbeddings model, which represents the sample_mflix.embedded_movies collection from the Atlas sample datasets. The MovieWithEmbeddings model class has the following definition:

from django.db import models
from django_mongodb_backend.fields import ArrayField
class MovieWithEmbeddings(models.Model):
title = models.CharField(max_length=200)
runtime = models.IntegerField(default=0)
plot_embedding = ArrayField(models.FloatField(), size=1536, null=True, blank=True)
class Meta:
db_table = "embedded_movies"
managed = False
def __str__(self):
return self.title

MovieWithEmbeddings 模型包括一个内部 Meta 类(用于指定模型元数据)和一个 __str__() 方法(用于定义模型的字符串表示形式)。 要学习;了解这些模型功能,请参阅创建模型指南中的定义模型。

您可以使用Python交互式Shell来运行代码示例。 要进入Shell ,请从项目的根目录运行以下命令:

python manage.py shell

进入Python Shell后,请确保导入以下模型和模块:

from <your application name>.models import MovieWithEmbeddings

要学习;了解如何创建使用Movie 模型和Python交互式Shell与MongoDB文档交互的 Django应用程序,请访问 Django MongoDB后端入门教程。

重要

查询要求

在执行MongoDB Vector Search 查询之前,您必须在集合上创建 Vector Search索引。要学习如何使用 Django MongoDB 后端创建向量搜索搜索索引,请参阅创建索引指南中的向量搜索搜索索引。

您可以使用 Django MongoDB 后端根据数据的语义进行查询。MongoDB 向量搜索查询根据查询向量,或表示搜索术语或短语含义的数字数组返回结果。MongoDB将此查询向量与存储在文档向量字段中的向量进行比较。

To specify your Vector Search criteria, create an instance of the SearchVector expression class provided by the django_mongodb_backend.expressions module. This expression corresponds to the $vectorSearch MongoDB pipeline stage. Pass the following arguments to the SearchVector() constructor:

  • path:要查询的字段。

  • query_vector:表示搜索条件的数字大量。要学习;了解有关查询向量的更多信息,请参阅MongoDB Atlas文档中的向量。

  • limit:要返回的最大结果数。

  • num_candidates:(可选)查询要考虑的文档数量。

  • exact:(可选) 布尔值,表示是否执行精确最近邻 (ENN)搜索。默认值为 False。要学习有关精确最近邻 (ENN) 搜索的更多信息,请参阅MongoDB Atlas文档中的精确最近邻 (ENN) 搜索。

  • filter:(可选)应用查询结果的过滤。

然后,通过将 SearchVector 实例传递给 Django 的 QuerySet API 中的 annotate 方法来运行向量搜索查询。以下代码显示了执行向量搜索查询的事务语法:

from django_mongodb_backend.expressions import SearchVector
Model.objects.annotate(
score=SearchVector(
path="<field name>",
query_vector=[<vector values>],
limit=<number>,
num_candidates=<number>,
exact=<boolean>,
filter=<filter expression>
)
)

此示例对 sample_mflix.embedded_movies集合运行MongoDB Vector Search查询。该查询执行以下操作:

  • 查询 plot_embedding 向量字段。

  • 将结果限制为 5 个文档。

  • Specifies an Approximate Nearest Neighbor (ANN) vector search that considers 150 candidates. To learn more about ANN searches, see ANN Search in the MongoDB Atlas documentation.

vector_values = [float(i % 10) * 0.1 for i in range(1536)]
MovieWithEmbeddings.objects.annotate(
score=SearchVector(
path="plot_embedding",
query_vector=vector_values,
limit=5,
num_candidates=150,
exact=False,
)
)

提示

The preceding code example passes an arbitrary vector to the query_vector argument. To learn how to generate a vector that represents the meaning of a search term or phrase, see How to Create Vector Embeddings Manually in the MongoDB Atlas documentation.

MongoDB为向量搜索查询中返回的每个文档分配一个相关性分数。结果设立包含的文档按相关性分数从高到低排序。

要在查询结果中包含此分数,可以使用 Django 的 QuerySet API中的 values() 方法。将 score字段作为参数传递给 values() 方法。

以下示例展示了如何运行与前面的示例相同的向量搜索查询,并打印文档的向量搜索相关性分数:

vector_values = [float(i % 10) * 0.1 for i in range(1536)]
MovieWithEmbeddings.objects.annotate(
score=SearchVector(
path="plot_embedding",
query_vector=vector_values,
limit=5,
num_candidates=150,
exact=False,
)
).values("title", "score")

要了解有关MongoDB Vector Search 的更多信息,请参阅MongoDB Atlas文档中的以下资源: