Docs 菜单
Docs 主页
/
Atlas
/

如何为向量搜索建立索引字段

您可以使用 vectorSearch 类型对字段进行索引以运行 $vectorSearch 查询。您可以为要查询的向量嵌入定义索引,以及为任何您希望用于预过滤数据的任何其他字段定义索引。过滤数据有助于缩小语义搜索范围,并确保在比较时(例如在多租户环境中)不考虑某些向量嵌入。

您可以使用Atlas 用户界面、 Atlas Administration API、 Atlas CLI、 或支持的MongoDB驱动程序来创建MongoDB Vectormongosh Search索引。

注意

您不能使用已弃用的 knnBeta 操作符来查询使用 vectorSearch 类型索引定义索引的字段。

vectorSearch 类型索引定义中,您可以仅使用单个元素对数组索引。您无法对文档数组内的嵌入字段或对象数组内的嵌入字段索引。您可以使用点表示法对文档内的嵌入字段索引。不能在同一索引定义中对同一嵌入字段进行多次索引。

在为嵌入索引之前,我们建议将嵌入转换为BSON BinData向量,子类型为float32int1int8,以便在 Atlas 集群中高效存储。要了解更多信息,请参阅如何将嵌入转换为 BSON 向量。

使用MongoDB Vector Search 索引时, Atlas 集群的空闲节点上的资源消耗可能会增加。这是由根本的mongot进程造成的,该进程执行MongoDB Vector Search 的各种基本操作。空闲节点上的 CPU 利用率可能因索引的数量、复杂性和大小而异。

要了解有关索引大小注意事项的更多信息,请参阅索引向量的内存需求。

您可以通过Atlas用户界面、 、 Atlas CLI、 Atlas Administrationmongosh API和以下MongoDB驱动程序创建和管理MongoDB Vector Search 索引:

MongoDB 驱动
版本

1.28.0 或更高

3.11.0 或更高

3.1.0 或更高

1.16.0 或更高

5.2.0 或更高

5.2.0 或更高

6.6.0 或更高

1.20.0 或更高

4.7 或更高

3.1.0 或更高

5.2.0 或更高

以下语法定义了 vectorSearch 索引类型:

1{
2 "fields":[
3 {
4 "type": "vector",
5 "path": "<field-to-index>",
6 "numDimensions": <number-of-dimensions>,
7 "similarity": "euclidean | cosine | dotProduct",
8 "quantization": "none | scalar | binary",
9 "hnswOptions": {
10 "maxEdges": <number-of-connected-neighbors>,
11 "numEdgeCandidates": <number-of-nearest-neighbors>
12 }
13 },
14 {
15 "type": "filter",
16 "path": "<field-to-index>"
17 },
18 ...
19 ]
20}

MongoDB Vector Search索引定义包含以下字段:

选项
类型
必要性
用途

fields

字段定义文档的数组

必需

要索引的向量和过滤字段的定义,每个文档一个定义。每个字段定义文档都为要索引的字段指定 typepath 和其他配置选项。

fields大量必须包含至少一个 vector 类型字段定义。您可以在大量中添加额外的 filter 类型字段定义,以对数据进行预过滤。

fields.
type

字符串

必需

用于为 $vectorSearch 的字段索引的字段类型。您可以指定以下值之一:

  • vector - 对于包含向量嵌入的字段。

  • filter - 用于筛选的附加字段。您可以使用过滤器过滤布尔值、日期、objectId、数值、字符串和 UUID 值,包括这些类型的数组。

要学习;了解更多信息,请参阅关于 vector 类型关于 filter 类型。

fields.
path

字符串

必需

要为其创建索引的字段名称。对于嵌套字段,使用点表示法来指定嵌入式字段的路径。

fields.
numDimensions

Int

必需

MongoDB Vector Search 在索引时和查询时实施的向量维度数。只能为 vector 类型字段设立此字段。您必须指定一个小于或等于 8192 的值。

对于索引量化向量或 BinData,您可以指定以下值之一:

  • 1int8 向量的 8192 进行摄取。

  • 用于摄取的 int1 向量的 8 倍数。

  • 18192(表示 binData(float32))和 array(float32) 向量(表示自动标量量化)。

  • binData(float32)array(float32) 向量的 8 的倍数,用于自动二进制量化。

您选择的嵌入模型决定了向量嵌入的维数,某些模型对于输出的维数有多个选项。要学习;了解更多信息,请参阅选择创建嵌入的方法。

fields.
similarity

字符串

必需

用于搜索前 K 个最近邻域的向量相似度函数。只能为 vector 类型字段设立此字段。

您可以指定以下值之一:

  • euclidean — 测量向量两端之间的距离。

  • cosine — 根据向量之间的角度测量相似度。

  • dotProduct - 测量类似于 cosine 的相似度,但考虑了向量的幅度。

要学习;了解更多信息,请参阅关于相似度函数。

fields.
quantization

字符串

Optional

向量的自动向量量化类型。仅当嵌入是 floatdouble 向量时才使用此设置。

您可以指定以下值之一:

  • none - 表示向量嵌入不会自动量化。 如果您有要摄取的预量化向量,请使用此设置。 如果省略,则为默认值。

  • scalar - 表示标量量化,将值转换为 1 字节整数。

  • binary - 表示二进制量化,将值转换为单个比特。要使用此值,numDimensions 必须是 8 的倍数。

    如果精度至关重要,请选择 nonescalar 而不是 binary

要学习;了解更多信息,请参阅向量量化。

fields.
hnswOptions

对象

Optional

用于构建 Hierarchical Navigable Small Worlds(分层可导航小世界) 图的参数。如果未指定,将使用 maxEdges 和 numEdgeCandidates 参数的默认值。

重要提示:这是作为“预览”功能提供的。修改默认值可能会对MongoDB Vector Search索引和查询产生负面影响。

fields.
hnswOptions.
maxEdges

Int

Optional

分层可导航小世界图中,一个节点最多可以拥有的边(或连接)数量。值可以在 1664 之间(含)。如果未指定,则默认值为 16。例如,对于值 16,在分层可导航小世界图的每一层,每个节点最多可以有十六个出边。

数字越大,召回率(搜索结果的准确性)越高,因为图表的连接性更好。但是,由于每个图表节点要评估的邻居数量较多,这会降低查询速度;由于每个节点存储更多连接,因此会增加 Hierarchical Navigable Small Worlds图表的内存;并且会减慢索引,因为MongoDB Vector Search 会评估更多邻居并进行调整添加到图表中的每个新节点。

fields.
hnswOptions.
numEdgeCandidates

Int

Optional

类似于查询时的 numCandidates,此参数控制要评估的最大节点数,以找到连接到新节点的最近邻居。值可以在 1003200 之间(含)。如果未指定,值默认为 100

较高的数值可以生成具有高质量连接的图,从而提升搜索质量(召回率),但也可能对查询延迟产生负面影响。

索引定义的 vector 字段必须包含以下类型之一的数字数组:

  • BSON double

  • BSON BinData vector 子类型 float32

  • BSON BinData vector 子类型 int1

  • BSON BinData vector 子类型 int8

注意

要了解有关生成带有子类型 float32int1int8BSON BinData 向量的更多信息,请参阅 如何引入预量化向量

您必须在 fields 数组中将向量字段作为 vector 类型进行索引。

以下语法定义了 vector 字段类型:

1{
2 "fields":[
3 {
4 "type": "vector",
5 "path": <field-to-index>,
6 "numDimensions": <number-of-dimensions>,
7 "similarity": "euclidean | cosine | dotProduct",
8 "quantization": "none | scalar | binary",
9 "hnswOptions": {
10 "maxEdges": <number-of-connected-neighbors>,
11 "numEdgeCandidates": <number-of-nearest-neighbors>
12 }
13 },
14 ...
15 ]
16}

MongoDB Vector Search 支持以下相似度函数:

  • euclidean — 测量向量两端之间的距离。您可以通过该值根据不同的维度衡量相似性。要了解更多信息,请参阅欧几里得。

  • cosine — 根据向量之间的角度测量相似度。 通过该值,您可以衡量不按幅度缩放的相似度。 不能将零幅度向量与 cosine 一起使用。 要衡量余弦相似度,我们建议您对向量进行归一化并改用 dotProduct

  • dotProduct - 与 cosine 类似的测量计算,但考虑了向量的幅度。如果对幅度进行归一化,则 cosinedotProduct 在衡量相似性方面几乎相同。

    要使用 dotProduct,您必须在索引时和查询时将向量标准化为单位长度。

下表显示了各种类型的相似度函数:

向量嵌入类型
euclidean
cosine
dotProduct

binData(int1)

binData(int8)

binData(float32)

array(float32)

用于向量摄取。

用于自动标量或二进制量化。

为获得最佳性能,请检查您的嵌入模型,以确定哪个相似度函数适合嵌入模型的培训进程。 如果没有任何指导,请从 dotProduct 开始。 将 fields.similarity 设置为 dotProduct 值可让您根据角度和幅度有效地衡量相似性。 dotProductcosine 消耗的计算资源更少,并且在向量为单位长度时非常高效。 但是,如果您的向量未标准化,请评估 euclidean 距离和 cosine 相似度的示例查询结果中的相似度分数,以确定哪一个对应于合理的结果。

您可以选择对附加字段建立索引,以便预先过滤您的数据。您可以使用过滤器过滤布尔值、日期、objectId、数值、字符串和 UUID 值,包括这些类型的数组。过滤数据有助于缩小语义搜索的范围,并确保不会考虑将所有向量进行比较。它减少了用于运行相似性比较的文档数量,从而可以降低查询延迟并提高搜索结果的准确性。

您必须使用 fields大量内的 filter 类型为要过滤的字段索引。

以下语法定义了 filter 字段类型:

1{
2 "fields":[
3 {
4 "type": "vector",
5 ...
6 },
7 {
8 "type": "filter",
9 "path": "<field-to-index>"
10 },
11 ...
12 ]
13}

注意

对数据进行预过滤不会影响MongoDB Vector Search 使用 进行$vectorSearchScore $vectorSearch查询返回的分数。

您可以通过Atlas用户界面、 Atlas管理API、 Atlas CLI,为任何类型的数据包含长度小于或等于 维度的向量嵌入的所有集合创建MongoDB Vector8192mongosh Search索引,以及Atlas 集群上的其他数据、 或支持的MongoDB驱动程序。

要创建MongoDB Vector Search索引,您必须拥有满足以下先决条件的Atlas 集群:

  • MongoDB 版本6.0.117.0.2或更高版本

  • 要为其创建MongoDB Vector Search索引的集合

注意

您可以使用 命令或驾驶员助手方法在所有Atlas 集群层上创建MongoDB Vector Searchmongosh 索引。有关支持的驾驶员版本的列表,请参阅支持的客户端。

您需要 或更高角色才能创建和管理MongoDB Vector SearchProject Data Access Admin 索引。

您创建的内容不能超过:

  • M0 集群上的 3 索引(无论类型是 search 还是 vector)。

  • 针对 Flex 集群的 10 个索引。

我们建议您在单个 M10+集群上创建不超过 2、500 个搜索索引。


➤ 使用选择语言下拉菜单选择要用于创建索引的客户端。


注意

该过程包括embedded_movies sample_mflix数据库中 集合的索引定义示例。如果将示例数据加载到集群上并为此集合创建示例MongoDB Vector Search$vectorSearch 索引,则可以对此集合运行示例 查询。要学习;了解有关可以运行的示例查询的详情,请参阅 $vectorSearch 示例。

要使用Atlas Administration API为集合创建MongoDB Vector Search索引,请使用所需参数向MongoDB Search indexes 端点发送 POST请求。

1curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \
2--header "Accept: application/json" \
3--header "Content-Type: application/json" \
4--include \
5--request POST "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes" \
6--data '
7 {
8 "database": "<name-of-database>",
9 "collectionName": "<name-of-collection>",
10 "type": "vectorSearch",
11 "name": "<index-name>",
12 "definition": {
13 "fields":[
14 {
15 "type": "vector",
16 "path": <field-to-index>,
17 "numDimensions": <number-of-dimensions>,
18 "similarity": "euclidean | cosine | dotProduct"
19 },
20 {
21 "type": "filter",
22 "path": "<field-to-index>"
23 },
24 ...
25 }
26 ]
27 }'

要学习;了解有关端点语法和参数的更多信息,请参阅创建一个MongoDB搜索索引。

例子

以下索引定义会将 plot_embedding_voyage_3_large 字段索引为 vector 类型。plot_embedding_voyage_3_large 字段包含使用 Voyage AI 的 voyage-3-large 嵌入模型创建的 2048 个向量维度嵌入。该索引使用 dotProduct 函数来衡量相似度。

以下索引定义仅对用于执行向量Atlas Search的向量嵌入字段进行索引。

1curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \
2--header "Accept: application/json" \
3--header "Content-Type: application/json" \
4--include \
5--request POST "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes" \
6--data '
7 {
8 "database": "sample_mflix",
9 "collectionName": "embedded_movies",
10 "type": "vectorSearch",
11 "name": "vector_index",
12 "definition: {
13 "fields":[
14 {
15 "type": "vector",
16 "path": "plot_embedding_voyage_3_large",
17 "numDimensions": 2048,
18 "similarity": "dotProduct"
19 }
20 ]
21 }
22 }'

此索引定义对以下字段进行索引:

  • 用于预过滤数据的 string 字段 (genres) 和数字字段 (year)。

  • 向量嵌入字段 (plot_embedding_voyage_3_large),用于针对预筛选数据执行向量Atlas Search 。

1curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \
2--header "Accept: application/json" \
3--header "Content-Type: application/json" \
4--include \
5--request POST "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes" \
6--data '
7 {
8 "database": "sample_mflix",
9 "collectionName": "embedded_movies",
10 "type": "vectorSearch",
11 "name": "vector_index",
12 "definition: {
13 "fields":[
14 {
15 "type": "vector",
16 "path": "plot_embedding_voyage_3_large",
17 "numDimensions": 2048,
18 "similarity": "dotProduct"
19 },
20 {
21 "type": "filter",
22 "path": "genres"
23 },
24 {
25 "type": "filter",
26 "path": "year"
27 }
28 ]
29 }
30 }'

要使用Atlas CLI v1.14.3 或更高版本为集合创建MongoDB Vector Search索引,请执行以下步骤:

1

您的索引定义应遵循以下格式:

1{
2 "database": "<name-of-database>",
3 "collectionName": "<name-of-collection>",
4 "type": "vectorSearch",
5 "name": "<index-name>",
6 "fields":[
7 {
8 "type": "vector",
9 "path": "<field-to-index>",
10 "numDimensions": <number-of-dimensions>,
11 "similarity": "euclidean | cosine | dotProduct"
12 },
13 {
14 "type": "filter",
15 "path": "<field-to-index>"
16 },
17 ...
18 ]
19}

例子

创建一个名为 vector-index.json 的文件。

2

<name-of-database>

包含要为其创建索引的集合的数据库。

<name-of-collection>

要为其创建索引的集合。

<index-name>

索引的名称。如果索引名称, MongoDB Vector Search 将索引命名为 vector_index

<number-of-dimensions>

MongoDB Vector Search 在索引时和查询时实施的向量维度数。

<field-to-index>

要索引的向量和筛选器字段。

例子

将以下索引定义复制并粘贴到 vector-index.json文件中。以下索引定义在MongoDB Vector Search索引中将 plot_embedding_voyage_3_large字段索引为 vector 类型,并将 genresyear 字段索引为 filter 类型。 plot_embedding_voyage_3_large字段包含使用 Voyage AI 的 voyage-3-large 嵌入模型创建的 2048 个向量维度嵌入。该索引指定使用 dotProduct 函数的相似性度量。

以下索引定义仅对用于执行向量Atlas Search的向量嵌入字段进行索引。

1{
2 "database": "sample_mflix",
3 "collectionName": "embedded_movies",
4 "type": "vectorSearch",
5 "name": "vector_index",
6 "fields": [
7 {
8 "type": "vector",
9 "path": "plot_embedding_voyage_3_large",
10 "numDimensions": 2048,
11 "similarity": "dotProduct"
12 }
13 ]
14}

此索引定义对以下字段进行索引:

  • 用于预过滤数据的 string 字段 (genres) 和数字字段 (year)。

  • 向量嵌入字段 (plot_embedding_voyage_3_large),用于针对预筛选数据执行向量Atlas Search 。

1{
2 "database": "sample_mflix",
3 "collectionName": "embedded_movies",
4 "type": "vectorSearch",
5 "name": "vector_index",
6 "fields":[
7 {
8 "type": "vector",
9 "path": "plot_embedding_voyage_3_large",
10 "numDimensions": 2048,
11 "similarity": "dotProduct"
12 },
13 {
14 "type": "filter",
15 "path": "genres"
16 },
17 {
18 "type": "filter",
19 "path": "year"
20 }
21 ]
22}
3
atlas clusters search indexes create --clusterName [cluster_name] --file [vector_index].json

在命令中,替换以下占位符值:

  • cluster_name 是包含要为其创建索引的集合的 Atlas 集群的名称。

  • vector_index 是包含MongoDB Vector Search索引 的索引定义的JSON文件的名称。

例子

atlas clusters search indexes create --clusterName [cluster_name] --file vector-index.json

要了解有关命令语法和参数的更多信息,请参阅 Atlas CLI 文档中的 Atlas 集群搜索索引创建命令。

1

警告: 导航优化正在进行中我们目前正在逐步推出改进的全新导航体验。如果以下步骤与您在 Atlas UI 中的视图不符,请参阅预览文档

  1. 如果尚未显示,请从导航栏上的 Organizations 菜单中选择包含所需项目的组织。

  2. 如果尚未显示,请从导航栏的Projects菜单中选择所需的项目。

  3. 如果尚未出现,请单击侧边栏中的 Clusters(集群)。

    会显示集群页面。

2

您可以从侧边栏、Data Explorer 或集群详细信息页面转到MongoDB搜索页面。

  1. 在侧边栏中,单击 Services 标题下的 Atlas Search

    如果没有集群,则请单击 Create cluster 来创建一个。要了解更多信息,请参阅创建集群

  2. 如果您的项目有多个集群,请从 Select cluster 下拉列表中选择要使用的集群,然后单击 Go to Atlas Search

    将显示 Atlas Search 页面。

  1. 单击集群的对应 Browse Collections 按钮。

  2. 展开数据库并选择集合。

  3. 单击该集合的 Search Indexes 标签页。

    将显示 Atlas Search 页面。

  1. 单击集群的名称。

  2. 单击 Atlas Search 标签页。

    将显示 Atlas Search 页面。

3
4

在页面上进行以下选择,然后单击 Next

Search Type

选择 Vector Search 索引类型。

Index Name and Data Source

指定以下信息:

  • Index Namevector_index 为默认索引名称。索引名称在命名空间中必须是唯一的,而无论索引类型为何。如果此集合已有名为 vector_index 的索引,则请输入其他名称。

  • Database and Collection:

    • 选择要为其创建索引的数据库。例如,sample_mflix

    • 选择要为其创建索引的集合。例如,embedded_movies

Configuration Method

For a guided experience, select Visual Editor.

To edit the raw index definition, select JSON Editor.

注意

默认下, MongoDB Search索引名为default 。如果保留此名称,则该索引将是任何未在运算符中指定其他 选项的MongoDB搜索查询的默认搜索索引。如果您要创建多个索引,我们建议您在所有索引之间保持一致的描述性命名约定。index

5

Atlas 会自动检测包含向量嵌入的字段及其相应的维度,并预填充最多三个向量字段。要配置该索引,请执行以下操作:

  1. 如有必要,请从 Path 下拉菜单中选择要索引的向量字段。

    选择 Add Another Field 以索引任意其他字段。

  2. Similarity Method 下拉菜单中为每个已索引字段指定相似性方法。

  3. (可选)单击 Advanced,然后从下拉菜单中选择 ScalarBinary 量化,以自动量化该字段中的嵌入。

  4. (可选)Filter Field 部分指定用于过滤该数据的您集合中的其他字段。

要学习;了解有关MongoDB Vector Search索引设置的更多信息,请参阅如何为向量搜索的字段编制索引。

例子

对于 embedded_movies 集合,plot_embedding_voyage_3_large 字段会显示。

要配置此索引,请从 Similarity Method 下拉菜单中选择 Dot Product

此索引定义仅对向量嵌入字段 (plot_embedding_voyage_3_large) 进行索引以执行向量搜索。

对于 embedded_movies 集合,plot_embedding_voyage_3_large 字段会显示。

要配置该索引,请执行以下操作:

  1. Similarity Method 下拉列表中选择 Dot Product

  2. 单击 Advanced,然后从下拉菜单中选择 Scalar 量化。

  3. Filter Field 部分,指定 genresyear 字段以按它们来过滤该数据。

此索引定义对以下字段进行索引:

  • 用于预过滤数据的 string 字段 (genres) 和数字字段 (year)。

  • 向量嵌入字段 (plot_embedding_voyage_3_large),用于针对预筛选数据执行向量Atlas Search 。

它还支持自动量化 (scalar),以高效处理嵌入。

MongoDB Vector Search索引类似于以下示例:

1{
2 "fields":[
3 {
4 "type": "vector",
5 "path": <field-to-index>,
6 "numDimensions": <number-of-dimensions>,
7 "similarity": "euclidean | cosine | dotProduct",
8 "quantization": "none | scalar | binary"
9 },
10 {
11 "type": "filter",
12 "path": "<field-to-index>"
13 },
14 ...
15 ]
16}

要了解有关索引中的字段的更多信息,请参阅如何对 Vector Search 字段建立索引

例子

以下索引定义会将 plot_embedding_voyage_3_large 字段索引为 vector 类型。plot_embedding_voyage_3_large 字段包含使用 Voyage AI 的 voyage-3-large 嵌入模型创建的 2048 个向量维度嵌入。该索引使用 dotProduct 函数来衡量相似度。

以下索引定义仅对用于执行向量Atlas Search的向量嵌入字段进行索引。

1{
2 "fields": [{
3 "type": "vector",
4 "path": "plot_embedding_voyage_3_large",
5 "numDimensions": 2048,
6 "similarity": "dotProduct"
7 }]
8}

此索引定义对以下字段进行索引:

  • 用于预过滤数据的 string 字段 (genres) 和数字字段 (year)。

  • 向量嵌入字段 (plot_embedding_voyage_3_large),用于针对预筛选数据执行向量Atlas Search 。

它还支持自动量化 (scalar),以高效处理嵌入。

1{
2 "fields": [{
3 "type": "vector",
4 "path": "plot_embedding_voyage_3_large",
5 "numDimensions": 2048,
6 "similarity": "dotProduct",
7 "quantization": "scalar"
8 },
9 {
10 "type": "filter",
11 "path": "genres"
12 },
13 {
14 "type": "filter",
15 "path": "year"
16 }]
17}
6
7

Atlas 会显示一个模态窗口,让您知道您的索引正在构建中。

8
9

新创建的索引会显示在 Atlas Search 标签页上。在构建索引期间,Status 字段显示为 Build in Progress。索引构建完成后,Status 字段将显示为 Active

注意

较大的集合需要较长的索引时间。索引构建完成后,您将收到电子邮件通知。

要使用 vmongosh2.1.2 或更高版本为集合创建MongoDB Vector Search索引,请执行以下步骤:

1

要学习;了解更多信息,请参阅通过mongosh连接到集群。

2

例子

use sample_mflix
switched to db sample_mflix
3

db.collection.createSearchIndex() 方法使用的语法如下:

1db.<collectionName>.createSearchIndex(
2 "<index-name>",
3 "vectorSearch", //index type
4 {
5 fields: [
6 {
7 "type": "vector",
8 "numDimensions": <number-of-dimensions>,
9 "path": "<field-to-index>",
10 "similarity": "euclidean | cosine | dotProduct"
11 },
12 {
13 "type": "filter",
14 "path": "<field-to-index>"
15 },
16 ...
17 ]
18 }
19);

例子

以下索引定义会将 plot_embedding_voyage_3_large 字段索引为 vector 类型。plot_embedding_voyage_3_large 字段包含使用 Voyage AI 的 voyage-3-large 嵌入模型创建的 2048 个向量维度嵌入。该索引使用 dotProduct 函数来衡量相似度。

以下索引定义仅对用于执行向量Atlas Search的向量嵌入字段进行索引。

1db.embedded_movies.createSearchIndex(
2 "vector_index",
3 "vectorSearch",
4 {
5 "fields": [
6 {
7 "type": "vector",
8 "path": "plot_embedding_voyage_3_large",
9 "numDimensions": 2048,
10 "similarity": "dotProduct",
11 "quantization": "scalar"
12 }
13 ]
14 }
15);

此索引定义对以下字段进行索引:

  • 用于预过滤数据的 string 字段 (genres) 和数字字段 (year)。

  • 向量嵌入字段 (plot_embedding_voyage_3_large),用于针对预筛选数据执行向量Atlas Search 。

1db.embedded_movies.createSearchIndex(
2 "vector_index",
3 "vectorSearch",
4 {
5 "fields": [
6 {
7 "type": "vector",
8 "path": "plot_embedding_voyage_3_large",
9 "numDimensions": 2048,
10 "similarity": "dotProduct"
11 },
12 {
13 "type": "filter",
14 "path": "genres"
15 },
16 {
17 "type": "filter",
18 "path": "year"
19 }
20 ]
21 }
22);

要使用C#驾驶员v 或更高版本为集合创建MongoDB Vector3.1.0 Search索引,请执行以下步骤:

1
1using MongoDB.Bson;
2using MongoDB.Driver;
3using System;
4using System.Threading;
5
6// Connect to your Atlas deployment
7private const string MongoConnectionString = "<connectionString>";
8var client = new MongoClient(MongoConnectionString);
9
10// Access your database and collection
11var database = client.GetDatabase("<databaseName>");
12var collection = database.GetCollection<BsonDocument>("<collectionName>");
13
14// Create your index model, then create the search index
15var name = "<indexName>";
16var type = SearchIndexType.VectorSearch;
17
18var definition = new BsonDocument
19{
20 { "fields", new BsonArray
21 {
22 new BsonDocument
23 {
24 { "type", "vector" },
25 { "path", "<fieldToIndex>" },
26 { "numDimensions", <numberOfDimensions> },
27 { "similarity", "euclidean | cosine | dotProduct" }
28 }
29 }
30 }
31};
32
33var model = new CreateSearchIndexModel(name, type, definition);
34
35var searchIndexView = collection.SearchIndexes;
36searchIndexView.CreateOne(model);
37Console.WriteLine($"New search index named {name} is building.");
38
39// Wait for initial sync to complete
40Console.WriteLine("Polling to check if the index is ready. This may take up to a minute.");
41bool queryable = false;
42while (!queryable)
43{
44 var indexes = searchIndexView.List();
45 foreach (var index in indexes.ToEnumerable())
46 {
47 if (index["name"] == name)
48 {
49 queryable = index["queryable"].AsBoolean;
50 }
51 }
52 if (!queryable)
53 {
54 Thread.Sleep(5000);
55 }
56}
57Console.WriteLine($"{name} is ready for querying.");
1using MongoDB.Bson;
2using MongoDB.Driver;
3using System;
4using System.Threading;
5
6// Connect to your Atlas deployment
7private const string MongoConnectionString = "<connectionString>";
8var client = new MongoClient(MongoConnectionString);
9
10// Access your database and collection
11var database = client.GetDatabase("<databaseName>");
12var collection = database.GetCollection<BsonDocument>("<collectionName>");
13
14// Create your index models and add them to an array
15var type = SearchIndexType.VectorSearch;
16
17var definitionOne = new BsonDocument
18{
19 { "fields", new BsonArray
20 {
21 new BsonDocument
22 {
23 { "type", "vector" },
24 { "path", "<fieldToIndex>" },
25 { "numDimensions", <numberOfDimensions> },
26 { "similarity", "euclidean | cosine | dotProduct" }
27 }
28 }
29 }
30};
31var modelOne = new CreateSearchIndexModel("<indexName>", type, definitionOne);
32
33var definitionTwo = new BsonDocument
34{
35 { "fields", new BsonArray
36 {
37 new BsonDocument
38 {
39 { "type", "vector" },
40 { "path", "<fieldToIndex>" },
41 { "numDimensions", <numberOfDimensions> },
42 { "similarity", "euclidean | cosine | dotProduct" }
43 }
44 }
45 }
46};
47var modelTwo = new CreateSearchIndexModel("<indexName>", type, definitionTwo);
48
49var models = new CreateSearchIndexModel[] { modelOne, modelTwo };
50
51// Create the search indexes
52var searchIndexView = collection.SearchIndexes;
53searchIndexView.CreateMany(models);
54
55Console.WriteLine($"New search indexes are building. This may take up to a minute.");

例子

创建一个名为 IndexService.cs 的文件。

2

<connectionString>

Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。

<databaseName>

包含要为其创建索引的集合的数据库。

<collectionName>

要为其创建索引的集合。

<indexName>

索引的名称。如果索引名称,则默认为 vector_index

<numberOfDimensions>

MongoDB Vector Search 在索引时和查询时实施的向量维度数。

<fieldToIndex>

要索引的向量和筛选器字段。

例子

将以下内容复制并粘贴到 IndexService.cs 中,并替换 <connectionString> 占位符值。以下索引定义在MongoDB Vector Search索引中将 plot_embedding_voyage_3_large字段索引为 vector 类型,将 genresyear 字段索引为 filter 类型。 plot_embedding_voyage_3_large字段包含使用 Voyage AI 的 voyage-3-large 嵌入模型创建的嵌入。索引定义指定了 2048 个向量维度,并使用 dotProduct 函数测量相似度。

以下索引定义仅对用于执行向量Atlas Search的向量嵌入字段 (plot_embedding_voyage_3_large) 编制索引。

1namespace query_quick_start;
2
3using MongoDB.Bson;
4using MongoDB.Driver;
5using System;
6using System.Threading;
7
8public class IndexService
9{
10 // Replace the placeholder with your Atlas connection string
11 private const string MongoConnectionString = "<connectionString>";
12 public void CreateVectorIndex()
13 {
14 try
15 {
16 // Connect to your Atlas cluster
17 var client = new MongoClient(MongoConnectionString);
18 var database = client.GetDatabase("sample_mflix");
19 var collection = database.GetCollection<BsonDocument>("embedded_movies");
20
21 var searchIndexView = collection.SearchIndexes;
22 var name = "vector_index";
23 var type = SearchIndexType.VectorSearch;
24
25 var definition = new BsonDocument
26 {
27 { "fields", new BsonArray
28 {
29 new BsonDocument
30 {
31 { "type", "vector" },
32 { "path", "plot_embedding_voyage_3_large" },
33 { "numDimensions", 2048 },
34 { "similarity", "dotProduct" },
35 { "quantization", "scalar" }
36 }
37 }
38 }
39 };
40
41 var model = new CreateSearchIndexModel(name, type, definition);
42
43 searchIndexView.CreateOne(model);
44 Console.WriteLine($"New search index named {name} is building.");
45
46 // Polling for index status
47 Console.WriteLine("Polling to check if the index is ready. This may take up to a minute.");
48 bool queryable = false;
49 while (!queryable)
50 {
51 var indexes = searchIndexView.List();
52 foreach (var index in indexes.ToEnumerable())
53 {
54 if (index["name"] == name)
55 {
56 queryable = index["queryable"].AsBoolean;
57 }
58 }
59 if (!queryable)
60 {
61 Thread.Sleep(5000);
62 }
63 }
64 Console.WriteLine($"{name} is ready for querying.");
65 }
66 catch (Exception e)
67 {
68 Console.WriteLine($"Exception: {e.Message}");
69 }
70 }
71}

此索引定义对以下字段进行索引:

  • 用于预过滤数据的 string 字段 (genres) 和数字字段 (year)。

  • 向量嵌入字段 (plot_embedding_voyage_3_large),用于针对预筛选数据执行向量Atlas Search 。

1namespace query_quick_start;
2
3using MongoDB.Bson;
4using MongoDB.Driver;
5using System;
6using System.Threading;
7
8public class IndexService
9{
10 // Replace the placeholder with your Atlas connection string
11 private const string MongoConnectionString = "<connection-string>";
12 public void CreateVectorIndex()
13 {
14 try
15 {
16 // Connect to your Atlas cluster
17 var client = new MongoClient(MongoConnectionString);
18 var database = client.GetDatabase("sample_mflix");
19 var collection = database.GetCollection<BsonDocument>("embedded_movies");
20
21 var searchIndexView = collection.SearchIndexes;
22 var name = "vector_index";
23 var type = SearchIndexType.VectorSearch;
24
25 var definition = new BsonDocument
26 {
27 { "fields", new BsonArray
28 {
29 new BsonDocument
30 {
31 { "type", "vector" },
32 { "path", "plot_embedding_voyage_3_large" },
33 { "numDimensions", 2048 },
34 { "similarity", "dotProduct" },
35 { "quantization", "scalar"}
36 },
37 new BsonDocument
38 {
39 {"type", "filter"},
40 {"path", "genres"}
41 },
42 new BsonDocument
43 {
44 {"type", "filter"},
45 {"path", "year"}
46 }
47 }
48 }
49 };
50
51 var model = new CreateSearchIndexModel(name, type, definition);
52
53 searchIndexView.CreateOne(model);
54 Console.WriteLine($"New search index named {name} is building.");
55
56 // Polling for index status
57 Console.WriteLine("Polling to check if the index is ready. This may take up to a minute.");
58 bool queryable = false;
59 while (!queryable)
60 {
61 var indexes = searchIndexView.List();
62 foreach (var index in indexes.ToEnumerable())
63 {
64 if (index["name"] == name)
65 {
66 queryable = index["queryable"].AsBoolean;
67 }
68 }
69 if (!queryable)
70 {
71 Thread.Sleep(5000);
72 }
73 }
74 Console.WriteLine($"{name} is ready for querying.");
75 }
76 catch (Exception e)
77 {
78 Console.WriteLine($"Exception: {e.Message}");
79 }
80 }
81}
3
using query_quick_start;
var indexService = new IndexService();
indexService.CreateVectorIndex();
4
dotnet run

要使用MongoDB Go驾驶员v 或更高版本为集合创建MongoDB Vector2.0 Search索引,请执行以下步骤:

1
1package main
2
3import (
4 "context"
5 "fmt"
6 "log"
7
8 "go.mongodb.org/mongo-driver/v2/bson"
9 "go.mongodb.org/mongo-driver/v2/mongo"
10 "go.mongodb.org/mongo-driver/v2/mongo/options"
11)
12
13func main() {
14 ctx := context.Background()
15
16 // Replace the placeholder with your Atlas connection string
17 const uri = "<connectionString>"
18
19 // Connect to your Atlas cluster
20 clientOptions := options.Client().ApplyURI(uri)
21 client, err := mongo.Connect(clientOptions)
22 if err != nil {
23 log.Fatalf("failed to connect to the server: %v", err)
24 }
25 defer func() { _ = client.Disconnect(ctx) }()
26
27 // Set the namespace
28 coll := client.Database("<databaseName>").Collection("<collectionName>")
29
30 // Define the index details
31 type vectorDefinitionField struct {
32 Type string `bson:"type"`
33 Path string `bson:"path"`
34 NumDimensions int `bson:"numDimensions"`
35 Similarity string `bson:"similarity"`
36 }
37
38 type vectorDefinition struct {
39 Fields []vectorDefinitionField `bson:"fields"`
40 }
41
42 indexName := "<indexName>"
43 opts := options.SearchIndexes().SetName(indexName).SetType("vectorSearch")
44
45 indexModel := mongo.SearchIndexModel{
46 Definition: vectorDefinition{
47 Fields: []vectorDefinitionField{{
48 Type: "vector",
49 Path: "<fieldToIndex>",
50 NumDimensions: <numberOfDimensions>,
51 Similarity: "euclidean | cosine | dotProduct"}},
52 },
53 Options: opts,
54 }
55
56 // Create the index
57 log.Println("Creating the index.")
58 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, indexModel)
59 if err != nil {
60 log.Fatalf("failed to create the search index: %v", err)
61 }
62
63 // Await the creation of the index.
64 log.Println("Polling to confirm successful index creation.")
65 log.Println("NOTE: This may take up to a minute.")
66 searchIndexes := coll.SearchIndexes()
67 var doc bson.Raw
68 for doc == nil {
69 cursor, err := searchIndexes.List(ctx, options.SearchIndexes().SetName(searchIndexName))
70 if err != nil {
71 fmt.Errorf("failed to list search indexes: %w", err)
72 }
73
74 if !cursor.Next(ctx) {
75 break
76 }
77
78 name := cursor.Current.Lookup("name").StringValue()
79 queryable := cursor.Current.Lookup("queryable").Boolean()
80 if name == searchIndexName && queryable {
81 doc = cursor.Current
82 } else {
83 time.Sleep(5 * time.Second)
84 }
85 }
86
87 log.Println("Name of Index Created: " + searchIndexName)
88}

注意

程序化创建索引

MongoDB Go驾驶员从 v1.16.0 开始支持编程式MongoDB Vector Search索引管理,但前面的代码显示的是 v2.x驾驶员的语法。

2

<connectionString>

Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。

<databaseName>

包含要为其创建索引的集合的数据库。

<collectionName>

要为其创建索引的集合。

<indexName>

索引的名称。如果索引名称,则默认为 vector_index

<numberOfDimensions>

MongoDB Vector Search 在索引时和查询时实施的向量维度数。

<fieldToIndex>

要索引的向量和筛选器字段。

例子

将以下内容复制并粘贴到 create-index.go文件中,并替换 <connectionString> 占位符值。以下索引定义在MongoDB Vector Search索引中将 plot_embedding_voyage_3_large``字段索引为 vector 类型,将 genresyear 字段索引为 filter 类型。 plot_embedding_voyage_3_large``字段包含使用 Voyage AI 的 voyage-3-large 嵌入模型创建的嵌入。索引定义指定了 2048 个向量维度,并使用 dotProduct 函数测量相似度。

以下索引定义仅对用于执行向量Atlas Search的向量嵌入字段 (plot_embedding_voyage_3_large``) 编制索引。

1package main
2
3import (
4 "context"
5 "fmt"
6 "log"
7 "time"
8
9 "go.mongodb.org/mongo-driver/v2/bson"
10 "go.mongodb.org/mongo-driver/v2/mongo"
11 "go.mongodb.org/mongo-driver/v2/mongo/options"
12)
13
14func main() {
15 ctx := context.Background()
16
17 // Replace the placeholder with your Atlas connection string
18 const uri = "<connectionString>"
19
20 // Connect to your Atlas cluster
21 clientOptions := options.Client().ApplyURI(uri)
22 client, err := mongo.Connect(clientOptions)
23 if err != nil {
24 log.Fatalf("failed to connect to the server: %v", err)
25 }
26 defer func() { _ = client.Disconnect(ctx) }()
27
28 // Set the namespace
29 coll := client.Database("sample_mflix").Collection("embedded_movies")
30
31 // Define the index details
32 type vectorDefinitionField struct {
33 Type string `bson:"type"`
34 Path string `bson:"path"`
35 NumDimensions int `bson:"numDimensions"`
36 Similarity string `bson:"similarity"`
37 Quantization string `bson:"quantization"`
38 }
39
40 type vectorDefinition struct {
41 Fields []vectorDefinitionField `bson:"fields"`
42 }
43
44 indexName := "vector_index"
45 opts := options.SearchIndexes().SetName(indexName).SetType("vectorSearch")
46
47 indexModel := mongo.SearchIndexModel{
48 Definition: vectorDefinition{
49 Fields: []vectorDefinitionField{{
50 Type: "vector",
51 Path: "plot_embedding_voyage_3_large",
52 NumDimensions: 2048,
53 Similarity: "dotProduct",
54 Quantization: "scalar"}},
55 },
56 Options: opts,
57 }
58
59 // Create the index
60 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, indexModel)
61 if err != nil {
62 log.Fatalf("failed to create the search index: %v", err)
63 }
64 log.Println("New search index named " + searchIndexName + " is building.")
65
66 // Await the creation of the index.
67 log.Println("Polling to check if the index is ready. This may take up to a minute.")
68 searchIndexes := coll.SearchIndexes()
69 var doc bson.Raw
70 for doc == nil {
71 cursor, err := searchIndexes.List(ctx, options.SearchIndexes().SetName(searchIndexName))
72 if err != nil {
73 fmt.Errorf("failed to list search indexes: %w", err)
74 }
75
76 if !cursor.Next(ctx) {
77 break
78 }
79
80 name := cursor.Current.Lookup("name").StringValue()
81 queryable := cursor.Current.Lookup("queryable").Boolean()
82 if name == searchIndexName && queryable {
83 doc = cursor.Current
84 } else {
85 time.Sleep(5 * time.Second)
86 }
87 }
88
89 log.Println(searchIndexName + " is ready for querying.")
90}

此索引定义对以下字段进行索引:

  • 用于预过滤数据的 string 字段 (genres) 和数字字段 (year)。

  • 向量嵌入字段 (plot_embedding_voyage_3_large``),用于针对预筛选数据执行向量Atlas Search 。

1package main
2
3import (
4 "context"
5 "fmt"
6 "log"
7 "time"
8
9 "go.mongodb.org/mongo-driver/v2/bson"
10 "go.mongodb.org/mongo-driver/v2/mongo"
11 "go.mongodb.org/mongo-driver/v2/mongo/options"
12)
13
14func main() {
15 ctx := context.Background()
16
17 // Replace the placeholder with your Atlas connection string
18 const uri = "<connectionString>"
19
20 // Connect to your Atlas cluster
21 clientOptions := options.Client().ApplyURI(uri)
22 client, err := mongo.Connect(clientOptions)
23 if err != nil {
24 log.Fatalf("failed to connect to the server: %v", err)
25 }
26 defer func() { _ = client.Disconnect(ctx) }()
27
28 // Set the namespace
29 coll := client.Database("sample_mflix").Collection("embedded_movies")
30 indexName := "vector_index"
31 opts := options.SearchIndexes().SetName(indexName).SetType("vectorSearch")
32
33 type vectorDefinitionField struct {
34 Type string `bson:"type"`
35 Path string `bson:"path"`
36 NumDimensions int `bson:"numDimensions"`
37 Similarity string `bson:"similarity"`
38 Quantization string `bson:"quantization"`
39 }
40
41 type filterField struct {
42 Type string `bson:"type"`
43 Path string `bson:"path"`
44 }
45
46 type indexDefinition struct {
47 Fields []vectorDefinitionField `bson:"fields"`
48 }
49
50 vectorDefinition := vectorDefinitionField{
51 Type: "vector",
52 Path: "plot_embedding_voyage_3_large",
53 NumDimensions: 2048,
54 Similarity: "dotProduct",
55 Quantization: "scalar"}
56 genreFilterDefinition := filterField{"filter", "genres"}
57 yearFilterDefinition := filterField{"filter", "year"}
58
59 indexModel := mongo.SearchIndexModel{
60 Definition: bson.D{{Key: "fields", Value: [3]interface{}{
61 vectorDefinition,
62 genreFilterDefinition,
63 yearFilterDefinition}}},
64 Options: opts,
65 }
66
67 // Create the index
68 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, indexModel)
69 if err != nil {
70 log.Fatalf("failed to create the search index: %v", err)
71 }
72 log.Println("New search index named " + searchIndexName + " is building.")
73
74 // Await the creation of the index.
75 log.Println("Polling to check if the index is ready. This may take up to a minute.")
76 searchIndexes := coll.SearchIndexes()
77 var doc bson.Raw
78 for doc == nil {
79 cursor, err := searchIndexes.List(ctx, options.SearchIndexes().SetName(searchIndexName))
80 if err != nil {
81 fmt.Errorf("failed to list search indexes: %w", err)
82 }
83
84 if !cursor.Next(ctx) {
85 break
86 }
87
88 name := cursor.Current.Lookup("name").StringValue()
89 queryable := cursor.Current.Lookup("queryable").Boolean()
90 if name == searchIndexName && queryable {
91 doc = cursor.Current
92 } else {
93 time.Sleep(5 * time.Second)
94 }
95 }
96
97 log.Println(searchIndexName + " is ready for querying.")
98}
3
go run create-index.go

要使用MongoDB Java驾驶员v 或更高版本为集合创建MongoDB Vector5.2.0 Search索引,请执行以下步骤:

1
1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoDatabase;
5import com.mongodb.client.model.SearchIndexModel;
6import com.mongodb.client.model.SearchIndexType;
7import org.bson.Document;
8import org.bson.conversions.Bson;
9
10import java.util.Arrays;
11import java.util.Collections;
12import java.util.List;
13
14public class VectorIndex {
15
16 public static void main(String[] args) {
17
18 // Replace the placeholder with your Atlas connection string
19 String uri = "<connectionString>";
20
21 // Connect to your Atlas cluster
22 try (MongoClient mongoClient = MongoClients.create(uri)) {
23
24 // Set the namespace
25 MongoDatabase database = mongoClient.getDatabase("<databaseName>");
26 MongoCollection<Document> collection = database.getCollection("<collectionName>");
27
28 // Define the index details
29 String indexName = "<indexName>";
30 Bson definition = new Document(
31 "fields",
32 Arrays.asList(
33 new Document("type", "vector")
34 .append("path", "<fieldToIndex>")
35 .append("numDimensions", <numberOfDimensions>)
36 .append("similarity", "euclidean | cosine | dotProduct"),
37 new Document("type", "filter")
38 .append("path", "<fieldToIndex>"),
39 ...));
40
41 // Define the index model
42 SearchIndexModel indexModel = new SearchIndexModel(
43 indexName,
44 definition,
45 SearchIndexType.vectorSearch()
46 );
47
48 // Create the index using the defined model
49 List<String> result = collection.createSearchIndexes(Collections.singletonList(indexModel));
50 System.out.println("Successfully created vector index named: " + result.get(0));
51 System.out.println("It may take up to a minute for the index to leave the BUILDING status and become queryable.");
52
53 // Wait for index to build and become queryable
54 System.out.println("Polling to confirm the index has left the BUILDING status.");
55 // No special handling in case of a timeout. Custom handling can be implemented.
56 waitForIndex(collection, indexName);
57 }
58 }
59
60 /**
61 * Polls the collection to check whether the specified index is ready to query.
62 */
63 public static <T> boolean waitForIndex(final MongoCollection<T> collection, final String indexName) {
64 long startTime = System.nanoTime();
65 long timeoutNanos = TimeUnit.SECONDS.toNanos(60);
66 while (System.nanoTime() - startTime < timeoutNanos) {
67 Document indexRecord = StreamSupport.stream(collection.listSearchIndexes().spliterator(), false)
68 .filter(index -> indexName.equals(index.getString("name")))
69 .findAny().orElse(null);
70 if (indexRecord != null) {
71 if ("FAILED".equals(indexRecord.getString("status"))) {
72 throw new RuntimeException("Search index has FAILED status.");
73 }
74 if (indexRecord.getBoolean("queryable")) {
75 System.out.println(indexName + " index is ready to query");
76 return true;
77 }
78 }
79 try {
80 Thread.sleep(100); // busy-wait, avoid in production
81 } catch (InterruptedException e) {
82 Thread.currentThread().interrupt();
83 throw new RuntimeException(e);
84 }
85 }
86 return false;
87 }
88}
2

<connectionString>

Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。

<databaseName>

包含要为其创建索引的集合的数据库。

<collectionName>

要为其创建索引的集合。

<indexName>

索引的名称。如果索引名称,则默认为 vector_index

<numberOfDimensions>

MongoDB Vector Search 在索引时和查询时实施的向量维度数。

<fieldToIndex>

要索引的向量和筛选器字段。

以下是索引定义示例:

  • 在MongoDB Vector Search索引中,将 plot_embedding_voyage_3_large字段作为 vector 类型进行索引,并将 genresyear 字段作为 filter 类型进行索引。

  • plot_embedding_voyage_3_large 字段指定为向量嵌入字段,其中包含使用 Voyage AI 的 voyage-3-large 嵌入模型创建的嵌入。

  • 指定 2048 向量维度并使用 dotProduct 函数衡量相似性。

此索引定义仅对向量嵌入字段 (plot_embedding_voyage_3_large) 进行索引以执行向量搜索。

将以下内容复制并粘贴到您创建的文件中,然后替换 <connectionString> 占位符值。

1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoDatabase;
5import com.mongodb.client.model.SearchIndexModel;
6import com.mongodb.client.model.SearchIndexType;
7import org.bson.Document;
8import org.bson.conversions.Bson;
9
10import java.util.Collections;
11import java.util.List;
12
13public class VectorIndex {
14
15 public static void main(String[] args) {
16
17 // Replace the placeholder with your Atlas connection string
18 String uri = "<connectionString>";
19
20 // Connect to your Atlas cluster
21 try (MongoClient mongoClient = MongoClients.create(uri)) {
22
23 // Set the namespace
24 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
25 MongoCollection<Document> collection = database.getCollection("embedded_movies");
26
27 // Define the index details
28 String indexName = "vector_index";
29 Bson definition = new Document(
30 "fields",
31 Collections.singletonList(
32 new Document("type", "vector")
33 .append("path", "plot_embedding_voyage_3_large")
34 .append("numDimensions", 2048)
35 .append("similarity", "dotProduct")
36 .append("quantization", "scalar")));
37
38 // Define the index model
39 SearchIndexModel indexModel = new SearchIndexModel(
40 indexName,
41 definition,
42 SearchIndexType.vectorSearch());
43
44 // Create the index using the defined model
45 List<String> result = collection.createSearchIndexes(Collections.singletonList(indexModel));
46 System.out.println("Successfully created vector index named: " + result.get(0));
47 System.out.println("It may take up to a minute for the index to leave the BUILDING status and become queryable.");
48
49 // Wait for index to build and become queryable
50 System.out.println("Polling to confirm the index has left the BUILDING status.");
51 // No special handling in case of a timeout. Custom handling can be implemented.
52 waitForIndex(collection, indexName);
53 }
54 }
55
56 /**
57 * Polls the collection to check whether the specified index is ready to query.
58 */
59 public static <T> boolean waitForIndex(final MongoCollection<T> collection, final String indexName) {
60 long startTime = System.nanoTime();
61 long timeoutNanos = TimeUnit.SECONDS.toNanos(60);
62 while (System.nanoTime() - startTime < timeoutNanos) {
63 Document indexRecord = StreamSupport.stream(collection.listSearchIndexes().spliterator(), false)
64 .filter(index -> indexName.equals(index.getString("name")))
65 .findAny().orElse(null);
66 if (indexRecord != null) {
67 if ("FAILED".equals(indexRecord.getString("status"))) {
68 throw new RuntimeException("Search index has FAILED status.");
69 }
70 if (indexRecord.getBoolean("queryable")) {
71 System.out.println(indexName + " index is ready to query");
72 return true;
73 }
74 }
75 try {
76 Thread.sleep(100); // busy-wait, avoid in production
77 } catch (InterruptedException e) {
78 Thread.currentThread().interrupt();
79 throw new RuntimeException(e);
80 }
81 }
82 return false;
83 }
84}

此索引定义对以下字段进行索引:

  • 用于预过滤数据的 string 字段 (genres) 和数字字段 (year)。

  • 向量嵌入字段 (plot_embedding_voyage_3_large),用于针对预筛选数据执行向量Atlas Search 。

将以下内容复制并粘贴到您创建的文件中,然后替换 <connectionString> 占位符值。

1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoDatabase;
5import com.mongodb.client.model.SearchIndexModel;
6import com.mongodb.client.model.SearchIndexType;
7import org.bson.Document;
8import org.bson.conversions.Bson;
9
10import java.util.Arrays;
11import java.util.Collections;
12import java.util.List;
13
14public class VectorIndex {
15
16 public static void main(String[] args) {
17
18 // Replace the placeholder with your Atlas connection string
19 String uri = "<connectionString>";
20
21 // Connect to your Atlas cluster
22 try (MongoClient mongoClient = MongoClients.create(uri)) {
23
24 // Set the namespace
25 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
26 MongoCollection<Document> collection = database.getCollection("embedded_movies");
27
28 // Define the index details with the filter fields
29 String indexName = "vector_index";
30 Bson definition = new Document(
31 "fields",
32 Arrays.asList(
33 new Document("type", "vector")
34 .append("path", "plot_embedding_voyage_3_large")
35 .append("numDimensions", 2048)
36 .append("similarity", "dotProduct")
37 .append("quantization", "scalar"),
38 new Document("type", "filter")
39 .append("path", "genres"),
40 new Document("type", "filter")
41 .append("path", "year")));
42
43 // Define the index model
44 SearchIndexModel indexModel = new SearchIndexModel(
45 indexName,
46 definition,
47 SearchIndexType.vectorSearch());
48
49 // Create the index using the defined model
50 List<String> result = collection.createSearchIndexes(Collections.singletonList(indexModel));
51 System.out.println("Successfully created vector index named: " + result.get(0));
52 System.out.println("It may take up to a minute for the index to leave the BUILDING status and become queryable.");
53
54 // Wait for index to build and become queryable
55 System.out.println("Polling to confirm the index has left the BUILDING status.");
56 // No special handling in case of a timeout. Custom handling can be implemented.
57 waitForIndex(collection, indexName);
58 }
59 }
60
61 /**
62 * Polls the collection to check whether the specified index is ready to query.
63 */
64 public static <T> boolean waitForIndex(final MongoCollection<T> collection, final String indexName) {
65 long startTime = System.nanoTime();
66 long timeoutNanos = TimeUnit.SECONDS.toNanos(60);
67 while (System.nanoTime() - startTime < timeoutNanos) {
68 Document indexRecord = StreamSupport.stream(collection.listSearchIndexes().spliterator(), false)
69 .filter(index -> indexName.equals(index.getString("name")))
70 .findAny().orElse(null);
71 if (indexRecord != null) {
72 if ("FAILED".equals(indexRecord.getString("status"))) {
73 throw new RuntimeException("Search index has FAILED status.");
74 }
75 if (indexRecord.getBoolean("queryable")) {
76 System.out.println(indexName + " index is ready to query");
77 return true;
78 }
79 }
80 try {
81 Thread.sleep(100); // busy-wait, avoid in production
82 } catch (InterruptedException e) {
83 Thread.currentThread().interrupt();
84 throw new RuntimeException(e);
85 }
86 }
87 return false;
88 }
89}
3

从 IDE 运行文件以创建索引。

要使用MongoDB节点驾驶员v 或更高版本为集合创建MongoDB Vector6.6.0 Search索引,请执行以下步骤:

1
1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas deployment
4const uri = "<connectionString>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 const database = client.db("<databaseName>");
11 const collection = database.collection("<collectionName>");
12
13 // define your MongoDB Vector Search index
14 const index = {
15 name: "<indexName>",
16 type: "vectorSearch",
17 definition: {
18 "fields": [
19 {
20 "type": "vector",
21 "numDimensions": <numberOfDimensions>,
22 "path": "<fieldToIndex>",
23 "similarity": "euclidean | cosine | dotProduct"
24 },
25 {
26 "type": "filter",
27 "path": "<fieldToIndex>"
28 },
29 ...
30 ]
31 }
32 }
33
34 // run the helper method
35 const result = await collection.createSearchIndex(index);
36 console.log(`New search index named ${result} is building.`);
37 // wait for the index to be ready to query
38 console.log("Polling to check if the index is ready. This may take up to a minute.")
39 let isQueryable = false;
40 while (!isQueryable) {
41 const cursor = collection.listSearchIndexes();
42 for await (const index of cursor) {
43 if (index.name === result) {
44 if (index.queryable) {
45 console.log(`${result} is ready for querying.`);
46 isQueryable = true;
47 } else {
48 await new Promise(resolve => setTimeout(resolve, 5000));
49 }
50 }
51 }
52 }
53 } finally {
54 await client.close();
55 }
56}
57run().catch(console.dir);

例子

创建一个名为 vector-index.js 的文件。

2

<connectionString>

Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。

<databaseName>

包含要为其创建索引的集合的数据库。

<collectionName>

要为其创建索引的集合。

<indexName>

索引的名称。如果索引名称,则默认为 vector_index

<numberOfDimensions>

MongoDB Vector Search 在索引时和查询时实施的向量维度数。

<fieldToIndex>

要索引的向量和筛选器字段。

例子

将以下内容复制并粘贴到 vector-index.js文件中,并替换 <connectionString> 占位符值。以下索引定义在MongoDB Vector Search索引中将 plot_embedding_voyage_3_large字段索引为 vector 类型,将 genresyear 字段索引为 filter 类型。 plot_embedding_voyage_3_large字段包含使用 Voyage AI 的 voyage-3-large 嵌入模型创建的嵌入。索引定义指定了 2048 个向量维度,并使用 dotProduct 函数测量相似度。

以下索引定义仅对用于执行向量Atlas Search的向量嵌入字段 (plot_embedding_voyage_3_large) 编制索引。

1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas deployment
4const uri = "<connectionString>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 const database = client.db("sample_mflix");
11 const collection = database.collection("embedded_movies");
12
13 // define your MongoDB Vector Search index
14 const index = {
15 name: "vector_index",
16 type: "vectorSearch",
17 definition: {
18 "fields": [
19 {
20 "type": "vector",
21 "numDimensions": 2048,
22 "path": "plot_embedding_voyage_3_large",
23 "similarity": "dotProduct",
24 "quantization": "scalar"
25 }
26 ]
27 }
28 }
29
30 // run the helper method
31 const result = await collection.createSearchIndex(index);
32 console.log(`New search index named ${result} is building.`);
33
34 // wait for the index to be ready to query
35 console.log("Polling to check if the index is ready. This may take up to a minute.")
36 let isQueryable = false;
37 while (!isQueryable) {
38 const cursor = collection.listSearchIndexes();
39 for await (const index of cursor) {
40 if (index.name === result) {
41 if (index.queryable) {
42 console.log(`${result} is ready for querying.`);
43 isQueryable = true;
44 } else {
45 await new Promise(resolve => setTimeout(resolve, 5000));
46 }
47 }
48 }
49 }
50 } finally {
51 await client.close();
52 }
53}
54run().catch(console.dir);

此索引定义对以下字段进行索引:

  • 用于预过滤数据的 string 字段 (genres) 和数字字段 (year)。

  • 向量嵌入字段 (plot_embedding_voyage_3_large),用于针对预筛选数据执行向量Atlas Search 。

1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas deployment
4const uri = "<connectionString>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 const database = client.db("sample_mflix");
11 const collection = database.collection("embedded_movies");
12
13 // define your MongoDB Vector Search index
14 const index = {
15 name: "vector_index",
16 type: "vectorSearch",
17 definition: {
18 "fields": [
19 {
20 "type": "vector",
21 "numDimensions": 2048,
22 "path": "plot_embedding_voyage_3_large",
23 "similarity": "dotProduct",
24 "quantization": "scalar"
25 },
26 {
27 "type": "filter",
28 "path": "genres"
29 },
30 {
31 "type": "filter",
32 "path": "year"
33 }
34 ]
35 }
36 }
37
38 // run the helper method
39 const result = await collection.createSearchIndex(index);
40 console.log(`New search index named ${result} is building.`);
41
42 // wait for the index to be ready to query
43 console.log("Polling to check if the index is ready. This may take up to a minute.")
44 let isQueryable = false;
45 while (!isQueryable) {
46 const cursor = collection.listSearchIndexes();
47 for await (const index of cursor) {
48 if (index.name === result) {
49 if (index.queryable) {
50 console.log(`${result} is ready for querying.`);
51 isQueryable = true;
52 } else {
53 await new Promise(resolve => setTimeout(resolve, 5000));
54 }
55 }
56 }
57 }
58 } finally {
59 await client.close();
60 }
61}
62run().catch(console.dir);
3
node <file-name>.js

例子

node vector_index.js

将此示例的可运行版本用作Python笔记本。

要使用PyMongo驾驶员v 或更高版本为集合创建MongoDB Vector Search4.7 索引,请执行以下步骤:

1
1import pymongo
2from pymongo.mongo_client import MongoClient
3from pymongo.operations import SearchIndexModel
4
5# Connect to your Atlas deployment
6uri = "<connectionString>"
7client = MongoClient(uri)
8
9# Access your database and collection
10database = client["<databaseName>"]
11collection = database["<collectionName>"]
12
13# Create your index model, then create the search index
14search_index_model = SearchIndexModel(
15 definition={
16 "fields": [
17 {
18 "type": "vector",
19 "numDimensions": <numberofDimensions>,
20 "path": "<fieldToIndex>",
21 "similarity": "euclidean | cosine | dotProduct"
22 },
23 {
24 "type": "filter",
25 "path": "<fieldToIndex>"
26 },
27 ...
28 ]
29 },
30 name="<indexName>",
31 type="vectorSearch"
32)
33
34result = collection.create_search_index(model=search_index_model)
35print("New search index named " + result + " is building.")
36
37# Wait for initial sync to complete
38print("Polling to check if the index is ready. This may take up to a minute.")
39predicate=None
40if predicate is None:
41 predicate = lambda index: index.get("queryable") is True
42
43while True:
44 indices = list(collection.list_search_indexes(result))
45 if len(indices) and predicate(indices[0]):
46 break
47 time.sleep(5)
48print(result + " is ready for querying.")
49
50client.close()

要学习;了解更多信息,请参阅 create_search_index() 方法。

1from pymongo.mongo_client import MongoClient
2from pymongo.operations import SearchIndexModel
3
4def create_indexes():
5 # Connect to your Atlas deployment
6 uri = "<connectionString>"
7 client = MongoClient(uri)
8
9 # Access your database and collection
10 database = client["<databaseName>"]
11 collection = database["<collectionName>"]
12
13 # Create your index models and add them to an array
14 first_model = SearchIndexModel(
15 definition={
16 "fields": [
17 {
18 "type": "vector",
19 "numDimensions": <numberOfDimensions>,
20 "path": "<fieldToIndex>",
21 "similarity": "euclidean | cosine | dotProduct"
22 },
23 {
24 "type": "filter",
25 "path": "<fieldToIndex>"
26 },
27 ...
28 ]
29 },
30 name="<indexName>",
31 type="vectorSearch"
32 )
33
34 second_model = SearchIndexModel(
35 definition={
36 "fields": [
37 {
38 "type": "vector",
39 "numDimensions": <numberOfDimensions>,
40 "path": "<fieldToIndex>",
41 "similarity": "euclidean | cosine | dotProduct"
42 },
43 {
44 "type": "filter",
45 "path": "<fieldToIndex>"
46 },
47 ...
48 ]
49 },
50 name="<index name>",
51 type="vectorSearch"
52 )
53
54 ...
55
56 idx_models = [first_model, second_model, ...]
57
58 # Create the search indexes
59 result = collection.create_search_indexes(models=idx_models)
60 print(result)
61
62 client.close()

要学习;了解更多信息,请参阅 create_search_indexes() 方法。

例子

创建一个名为 vector-index.py 的文件。

2

<connectionString>

Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。

<databaseName>

包含要为其创建索引的集合的数据库。

<collectionName>

要为其创建索引的集合。

<indexName>

索引的名称。如果索引名称,则默认为 vector_index

<numberOfDimensions>

MongoDB Vector Search 在索引时和查询时实施的向量维度数。

<fieldToIndex>

要索引的向量和筛选器字段。

例子

将以下内容复制并粘贴到 vector-index.py 中,并替换 <connectionString> 占位符值。以下索引定义在MongoDB Vector Search索引中将 plot_embedding_voyage_3_large字段索引为 vector 类型,将 genresyear 字段索引为 filter 类型。 plot_embedding_voyage_3_large字段包含使用 Voyage AI 的 voyage-3-large 嵌入模型创建的嵌入。索引定义指定了 2048 个向量维度,并使用 dotProduct 函数测量相似度。

以下索引定义仅对用于执行向量Atlas Search的向量嵌入字段 (plot_embedding_voyage_3_large) 编制索引。

1from pymongo.mongo_client import MongoClient
2from pymongo.operations import SearchIndexModel
3import time
4
5# Connect to your Atlas deployment
6uri = "<connectionString>"
7client = MongoClient(uri)
8
9# Access your database and collection
10database = client["sample_mflix"]
11collection = database["embedded_movies"]
12
13# Create your index model, then create the search index
14search_index_model = SearchIndexModel(
15 definition={
16 "fields": [
17 {
18 "type": "vector",
19 "path": "plot_embedding_voyage_3_large",
20 "numDimensions": 2048,
21 "similarity": "dotProduct",
22 "quantization": "scalar"
23 }
24 ]
25 },
26 name="vector_index",
27 type="vectorSearch"
28)
29
30result = collection.create_search_index(model=search_index_model)
31print("New search index named " + result + " is building.")
32
33# Wait for initial sync to complete
34print("Polling to check if the index is ready. This may take up to a minute.")
35predicate=None
36if predicate is None:
37 predicate = lambda index: index.get("queryable") is True
38
39while True:
40 indices = list(collection.list_search_indexes(result))
41 if len(indices) and predicate(indices[0]):
42 break
43 time.sleep(5)
44print(result + " is ready for querying.")
45
46client.close()

此索引定义对以下字段进行索引:

  • 用于预过滤数据的 string 字段 (genres) 和数字字段 (year)。

  • 向量嵌入字段 (plot_embedding_voyage_3_large),用于针对预筛选数据执行向量Atlas Search 。

1from pymongo.mongo_client import MongoClient
2from pymongo.operations import SearchIndexModel
3import time
4
5# Connect to your Atlas deployment
6uri = "<connectionString>"
7client = MongoClient(uri)
8
9# Access your database and collection
10database = client["sample_mflix"]
11collection = database["embedded_movies"]
12
13# Create your index model, then create the search index
14search_index_model = SearchIndexModel(
15 definition={
16 "fields": [
17 {
18 "type": "vector",
19 "path": "plot_embedding_voyage_3_large",
20 "numDimensions": 2048,
21 "similarity": "dotProduct",
22 "quantization": "scalar"
23 },
24 {
25 "type": "filter",
26 "path": "genres"
27 },
28 {
29 "type": "filter",
30 "path": "year"
31 }
32 ]
33 },
34 name="vector_index",
35 type="vectorSearch"
36)
37
38result = collection.create_search_index(model=search_index_model)
39print("New search index named " + result + " is building.")
40
41# Wait for initial sync to complete
42print("Polling to check if the index is ready. This may take up to a minute.")
43predicate=None
44if predicate is None:
45 predicate = lambda index: index.get("queryable") is True
46
47while True:
48 indices = list(collection.list_search_indexes(result))
49 if len(indices) and predicate(indices[0]):
50 break
51 time.sleep(5)
52print(result + " is ready for querying.")
53
54client.close()
3
python <file-name>.py

例子

python vector-index.py

您可以从Atlas用户界面、 Atlas管理API、 Atlas CLI、 或支持的MongoDB驱动程序查看所有集合的MongoDB Vector Searchmongosh 索引。

您需要 或更高角色才能查看MongoDB Vector SearchProject Search Index Editor 索引。

注意

您可以使用 命令或驾驶员辅助方法检索所有Atlas 集群层上的MongoDB Vector Searchmongosh 索引。有关支持的驾驶员版本的列表,请参阅支持的客户端。


➤ 使用选择语言下拉菜单设置本节中示例的语言。


要使用Atlas Administration API检索集合的所有MongoDB Vector Search检索,请向MongoDB Search indexes 端点发送 GET请求,其中包含数据库和集合的名称。

1curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \
2 --header "Accept: application/json" \
3 --include \
4 --request GET "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{databaseName}/{collectionName}"

要学习;了解有关端点语法和参数的更多信息,请参阅返回一个集合的所有MongoDB搜索索引。

要使用Atlas Administration API检索集合的一个MongoDB Vector Search检索,请向MongoDB Search indexes 端点发送 GET请求,索引附带要检索的索引的唯一ID或名称(第 4 行)。

1curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \
2 --header "Accept: application/json" \
3 --include \
4 --request GET "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{indexId} | https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{databaseName}/{collectionName}/{indexName|indexId}"

要了解有关端点的语法和参数的更多信息,请参阅按名称获取一个按 ID 获取一个。

要使用Atlas CLI返回集合的MongoDB Vector Search 索引,请执行以下步骤:

1

clusterName

Atlas 集群的名称。

db

Atlas 集群上包含您已编制索引的集合的数据库名称。

collection

数据库中索引集合的名称。

projectId

项目的唯一标识符。

2
atlas clusters search indexes list --clusterName [cluster_name] --db <db-name> --collection <collection-name>

在命令中,替换以下占位符值:

  • cluster-name - 包含索引集合的 Atlas 集群的名称。

  • db-name - 包含要检索其索引的集合的数据库名称。

  • collection-name - 要检索其索引的集合的名称。

要了解有关命令语法和参数的更多信息,请参阅 Atlas CLI 文档中的 Atlas 集群搜索索引列表命令。

1

警告: 导航优化正在进行中我们目前正在逐步推出改进的全新导航体验。如果以下步骤与您在 Atlas UI 中的视图不符,请参阅预览文档

  1. 如果尚未显示,请从导航栏上的 Organizations 菜单中选择包含所需项目的组织。

  2. 如果尚未显示,请从导航栏的Projects菜单中选择所需的项目。

  3. 如果尚未出现,请单击侧边栏中的 Clusters(集群)。

    会显示集群页面。

2

您可以从侧边栏、Data Explorer 或集群详细信息页面转到MongoDB搜索页面。

  1. 在侧边栏中,单击 Services 标题下的 Atlas Search

    如果没有集群,则请单击 Create cluster 来创建一个。要了解更多信息,请参阅创建集群

  2. 如果您的项目有多个集群,请从 Select cluster 下拉列表中选择要使用的集群,然后单击 Go to Atlas Search

    将显示 Atlas Search 页面。

  1. 单击集群的对应 Browse Collections 按钮。

  2. 展开数据库并选择集合。

  3. 单击该集合的 Search Indexes 标签页。

    将显示 Atlas Search 页面。

  1. 单击集群的名称。

  2. 单击 Atlas Search 标签页。

    将显示 Atlas Search 页面。

此页面会显示页面上索引的以下详细信息:

名称

标识索引的标签。

索引类型

指示MongoDB Search 或MongoDB Vector Search索引的标签。值包括:

  • search 用于MongoDB Search 索引。

  • vectorSearch 用于MongoDB Vector Search 索引。

索引字段

包含此索引索引的字段的列表。

状态

集群主节点 (primary node in the replica set)节点上索引的当前状态。 有关有效值,请参阅索引状态。

size

主节点上索引的大小。

文档 (Document)

已建立索引的文档数与集合中文档总数的比值。

所需内存

运行向量搜索查询所需的大致内存量。

操作

可以对索引执行的操作。 您可以:

您无法在Search Tester 用户用户界面中针对vectorSearch 类型的索引运行查询。如果单击Query 按钮, MongoDB Vector Search 将显示示例$vectorSearch ,您可以在Atlas用户用户界面中以及使用其他支持的客户端复制、修改和运行该示例。

要使用 查看集合的MongoDB Vectormongosh Search索引,请执行以下步骤:

1

要学习;了解更多信息,请参阅通过mongosh连接到集群。

2
3

db.collection.getSearchIndexes() 方法使用的语法如下:

1db.<collectionName>.getSearchIndexes( "<index-name>" );

要使用C#驾驶员 或更高版本查看集合的MongoDB Vector Search3.1.0 索引,请执行以下步骤:

1
1namespace query_quick_start;
2
3using MongoDB.Bson;
4using MongoDB.Driver;
5
6public class IndexService
7{
8 private const string MongoConnectionString = "<connectionString>";
9 // Other class methods here...
10 public void ViewSearchIndexes()
11 {
12 try
13 {
14 // Connect to your Atlas deployment
15 var client = new MongoClient(MongoConnectionString);
16
17 // Access your database and collection
18 var database = client.GetDatabase("<databaseName>");
19 var collection = database.GetCollection<BsonDocument>("<collectionName>");
20
21 // Get a list of the collection's search indexes and print them
22 var searchIndexView = collection.SearchIndexes;
23 var indexes = searchIndexView.List();
24
25 foreach (var index in indexes.ToEnumerable())
26 {
27 Console.WriteLine(index);
28 }
29 }
30 catch (Exception e)
31 {
32 Console.WriteLine($"Exception: {e.Message}");
33 }
34 }
35}
2

<connectionString>

您的Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。

<databaseName>

包含该集合的数据库名称。

<collectionName>

集合的名称。

3
using query_quick_start;
var indexService = new IndexService();
indexService.ViewSearchIndexes();
4
dotnet run

要使用MongoDB Go驾驶员v 或更高版本查看集合的MongoDB Vector2.0 Search索引,请执行以下步骤:

1
1package main
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "log"
8
9 "go.mongodb.org/mongo-driver/v2/bson"
10 "go.mongodb.org/mongo-driver/v2/mongo"
11 "go.mongodb.org/mongo-driver/v2/mongo/options"
12)
13
14func main() {
15 ctx := context.Background()
16
17 // Replace the placeholder with your Atlas connection string
18 const uri = "<connectionString>"
19
20 // Connect to your Atlas cluster
21 clientOptions := options.Client().ApplyURI(uri)
22 client, err := mongo.Connect(clientOptions)
23 if err != nil {
24 log.Fatalf("failed to connect to the server: %v", err)
25 }
26 defer func() { _ = client.Disconnect(ctx) }()
27
28 // Set the namespace
29 coll := client.Database("<databaseName>").Collection("<collectionName>")
30
31 // Specify the options for the index to retrieve
32 indexName := "<indexName>"
33 opts := options.SearchIndexes().SetName(indexName)
34
35 // Get the index
36 cursor, err := coll.SearchIndexes().List(ctx, opts)
37 if err != nil {
38 log.Fatalf("failed to get the index: %v", err)
39 }
40
41 // Print the index details to the console as JSON
42 var results []bson.M
43 if err := cursor.All(ctx, &results); err != nil {
44 log.Fatalf("failed to unmarshal results to bson: %v", err)
45 }
46 res, err := json.Marshal(results)
47 if err != nil {
48 log.Fatalf("failed to marshal results to json: %v", err)
49 }
50 fmt.Println(string(res))
51}
2

<connectionString>

您的Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。

<databaseName>

包含该集合的数据库。

<collectionName>

要检索其索引的集合。

<indexName>

如果您想检索特定索引,请提供索引的名称。要返回集合中的所有索引,请省略此值,并在创建搜索索引选项时删除对 SetName() 方法的调用。

3
go run get-index.go

要使用MongoDB Java驾驶员v 或更高版本查看集合的MongoDB Vector5.2.0 Search索引,请执行以下步骤:

1
1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoDatabase;
5import org.bson.Document;
6
7public class ViewVectorIndex {
8
9 public static void main(String[] args) {
10
11 // Replace the placeholder with your Atlas connection string
12 String uri = "<connectionString>";
13
14 // Connect to your Atlas cluster
15 try (MongoClient mongoClient = MongoClients.create(uri)) {
16
17 // Set the namespace
18 MongoDatabase database = mongoClient.getDatabase("<databaseName>");
19 MongoCollection<Document> collection = database.getCollection("<collectionName>");
20
21 // Specify the options for the index to retrieve
22 String indexName = "<indexName>";
23
24 // Get the index and print details to the console as JSON
25 try {
26 Document listSearchIndex = collection.listSearchIndexes().name(indexName).first();
27 if (listSearchIndex != null) {
28 System.out.println("Index found: " + listSearchIndex.toJson());
29 } else {
30 System.out.println("Index not found.");
31 }
32 } catch (Exception e) {
33 throw new RuntimeException("Error finding index: " + e);
34 }
35
36 } catch (Exception e) {
37 throw new RuntimeException("Error connecting to MongoDB: " + e);
38 }
39 }
40}
2

<connectionString>

您的Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。

<databaseName>

包含该集合的数据库。

<collectionName>

要检索其索引的集合。

<indexName>

如果要检索特定索引,请输入索引的名称。 要返回集合上的所有索引,请省略此值。

3

从 IDE 运行该文件以检索指定的索引。

要使用MongoDB节点驾驶员v 或更高版本查看集合的MongoDB Vector6.6.0 Search索引,请执行以下步骤:

1
1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas deployment
4const uri = "<connectionString>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 const database = client.db("<databaseName>");
11 const collection = database.collection("<collectionName>");
12
13 // run the helper method
14 const result = await collection.listSearchIndexes("<indexName>").toArray();
15 console.log(result);
16 } finally {
17 await client.close();
18 }
19}
20run().catch(console.dir);
2

<connectionString>

您的Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。

<databaseName>

包含该集合的数据库。

<collectionName>

要检索其索引的集合。

<indexName>

如果要检索特定索引,请输入索引的名称。 要返回集合上的所有索引,请省略此值。

3
node <file-name>.js

要使用PyMongo驾驶员v 或更高版本查看集合的MongoDB Vector Search4.7 索引,请执行以下步骤:

1
1from pymongo.mongo_client import MongoClient
2
3# Connect to your Atlas deployment
4uri = "<connectionString>"
5client = MongoClient(uri)
6
7# Access your database and collection
8database = client["<databaseName>"]
9collection = database["<collectionName>"]
10
11# Get a list of the collection's search indexes and print them
12cursor = collection.list_search_indexes()
13for index in cursor:
14 print(index)

要了解更多信息,请参阅 list_search_indexes() 方法。

2

<connectionString>

您的Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。

<databaseName>

包含该集合的数据库名称。

<collectionName>

集合的名称。

3
python <file-name>.py

您可以通过Atlas用户界面、 Atlas管理API、 Atlas CLI、mongosh 或支持的MongoDB驱动程序更改现有MongoDB Vector Search索引的索引定义。您无法重命名索引或更改索引类型。如果需要更改索引名称或类型,则必须创建新索引并删除旧索引。

重要

编辑索引后, MongoDB Vector Search 会重建索引。重建索引时,您可以使用旧索引定义继续运行向量搜索查询。当索引完成重建后,旧索引将被自动替换。此进程类似于MongoDB Search 索引。要学习;了解更多信息,请参阅创建和更新MongoDB搜索索引。

您必须具有 或更高角色才能编辑MongoDB VectorProject Search Index Editor Search索引。

注意

您可以使用 命令或驾驶员助手方法来编辑所有Atlas 集群层上的MongoDB Vector Searchmongosh 索引。有关支持的驾驶员版本的列表,请参阅支持的客户端。


➤ 使用选择语言下拉菜单选择要用于编辑索引的客户端。


要使用Atlas Administration API编辑集合的MongoDB Vector Search索引,请向MongoDB Search indexes 端点发送 PATCH请求,并附带要编辑的索引的唯一ID或名称(第 4 行)。

1curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest --include \
2 --header "Accept: application/json" \
3 --header "Content-Type: application/json" \
4 --request PATCH "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{indexId} | https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{databaseName}/{collectionName}/{indexName|indexId}" \
5 --data'
6 {
7 "database": "<name-of-database>",
8 "collectionName": "<name-of-collection>",
9 "type": "vectorSearch",
10 "name": "<index-name>",
11 "definition": {
12 "fields":[
13 {
14 "type": "vector",
15 "path": <field-to-index>,
16 "numDimensions": <number-of-dimensions>,
17 "similarity": "euclidean | cosine | dotProduct"
18 },
19 {
20 "type": "filter",
21 "path": "<field-to-index>"
22 },
23 ...
24 }
25 ]
26 }'

要了解有关端点的语法和参数的更多信息,请参阅按名称更新一个按 ID 更新一个。

要使用Atlas CLI编辑集合的MongoDB Vector Search索引,请执行以下步骤:

1

您的索引定义应遵循以下格式:

1{
2 "database": "<name-of-database>",
3 "collectionName": "<name-of-collection>",
4 "type": "vectorSearch",
5 "name": "<index-name>",
6 "fields":[
7 {
8 "type": "vector",
9 "path": "<field-to-index>",
10 "numDimensions": <number-of-dimensions>,
11 "similarity": "euclidean | cosine | dotProduct"
12 },
13 {
14 "type": "filter",
15 "path": "<field-to-index>"
16 },
17 ...
18 ]
19}
2

<name-of-database>

包含要为其创建索引的集合的数据库。

<name-of-collection>

要为其创建索引的集合。

<index-name>

索引的名称。如果索引名称, MongoDB Vector Search 将索引命名为 vector_index

<number-of-dimensions>

MongoDB Vector Search 在索引时和查询时实施的向量维度数。

<field-to-index>

要索引的向量和筛选器字段。

3
atlas clusters search indexes update <indexId> --clusterName [cluster_name] --file [vector-_index].json

在命令中,替换以下占位符值:

  • cluster_name - 包含要更新索引的集合的 Atlas 集群的名称。

  • vector_index - JSON文件的名称,该文件包含MongoDB Vector Search索引的修改后的索引定义。

要了解有关命令语法和参数的更多信息,请参阅 Atlas CLI 文档中的 atlas clusters search indexes update 命令。

1

警告: 导航优化正在进行中我们目前正在逐步推出改进的全新导航体验。如果以下步骤与您在 Atlas UI 中的视图不符,请参阅预览文档

  1. 如果尚未显示,请从导航栏上的 Organizations 菜单中选择包含所需项目的组织。

  2. 如果尚未显示,请从导航栏的Projects菜单中选择所需的项目。

  3. 如果尚未出现,请单击侧边栏中的 Clusters(集群)。

    会显示集群页面。

2

您可以从侧边栏、Data Explorer 或集群详细信息页面转到MongoDB搜索页面。

  1. 在侧边栏中,单击 Services 标题下的 Atlas Search

    如果没有集群,则请单击 Create cluster 来创建一个。要了解更多信息,请参阅创建集群

  2. 如果您的项目有多个集群,请从 Select cluster 下拉列表中选择要使用的集群,然后单击 Go to Atlas Search

    将显示 Atlas Search 页面。

  1. 单击集群的对应 Browse Collections 按钮。

  2. 展开数据库并选择集合。

  3. 单击该集合的 Search Indexes 标签页。

    将显示 Atlas Search 页面。

  1. 单击集群的名称。

  2. 单击 Atlas Search 标签页。

    将显示 Atlas Search 页面。

3
  1. 找到要编辑的 vectorSearch 类型索引。

  2. 在该索引的 Actions 列中,单击

  3. 选择Edit With Visual Editor以获得引导体验,或选择Edit With JSON Editor以编辑原始索引定义。

  4. 检查当前配置设置,并根据需要进行编辑。

    要学习;了解有关MongoDB Vector Search索引中字段的更多信息,请参阅如何为向量搜索的字段创建索引。

  5. 单击 Save(保存)以应用更改。

索引状态从 Active 更改为 Building。在此状态下,您可以继续使用旧索引,因为在更新后的索引可供使用之前, MongoDB Vector Search 不会删除旧索引。一旦状态返回到 Active,则修改后的索引就可以使用了。

要使用 编辑集合的MongoDB Vectormongosh Search索引,请执行以下步骤:

1

要学习;了解更多信息,请参阅通过mongosh连接到集群。

2
3

db.collection.updateSearchIndex() 方法使用的语法如下:

1db.<collectionName>.updateSearchIndex(
2 "<index-name>",
3 {
4 fields: [
5 {
6 "type": "vector",
7 "numDimensions": <number-of-dimensions>,
8 "path": "<field-to-index>",
9 "similarity": "euclidean | cosine | dotProduct"
10 },
11 {
12 "type": "filter",
13 "path": "<field-to-index>"
14 },
15 ...
16 ]
17 }
18);

要使用C#驾驶员 或更高版本更新集合的MongoDB Vector3.1.0 Search索引,请执行以下步骤:

1
1namespace query_quick_start;
2
3using MongoDB.Bson;
4using MongoDB.Driver;
5
6public class IndexService
7{
8 private const string MongoConnectionString = "<connectionString>";
9 // Other class methods here...
10 public void EditVectorIndex()
11 {
12 try
13 {
14 // Connect to your Atlas deployment
15 var client = new MongoClient(MongoConnectionString);
16
17 // Access your database and collection
18 var database = client.GetDatabase("<databaseName>");
19 var collection = database.GetCollection<BsonDocument>("<collectionName>");
20
21 var definition = new BsonDocument
22 {
23 { "fields", new BsonArray
24 {
25 new BsonDocument
26 {
27 { "type", "vector" },
28 { "path", "<fieldToIndex>" },
29 { "numDimensions", <numberOfDimensions> },
30 { "similarity", "euclidean | cosine | dotProduct" }
31 }
32 }
33 }
34 };
35
36 // Update your search index
37 var searchIndexView = collection.SearchIndexes;
38 searchIndexView.Update(name, definition);
39 }
40 catch (Exception e)
41 {
42 Console.WriteLine($"Exception: {e.Message}");
43 }
44 }
45}
2

<connectionString>

Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。

<databaseName>

包含要为其创建索引的集合的数据库。

<collectionName>

要为其创建索引的集合。

<indexName>

索引的名称。如果索引名称,则默认为 vector_index

<numberOfDimensions>

MongoDB Vector Search 在索引时和查询时实施的向量维度数。

<fieldToIndex>

要索引的向量和筛选器字段。

3
using query_quick_start;
var indexService = new IndexService();
indexService.EditVectorIndex();
4
dotnet run

要使用MongoDB Go驾驶员v 或更高版本更新集合的MongoDB Vector2.0 Search索引,请执行以下步骤:

1
1package main
2
3import (
4 "context"
5 "fmt"
6 "log"
7
8 "go.mongodb.org/mongo-driver/v2/mongo"
9 "go.mongodb.org/mongo-driver/v2/mongo/options"
10)
11
12func main() {
13 ctx := context.Background()
14
15 // Replace the placeholder with your Atlas connection string
16 const uri = "<connection-string>"
17
18 // Connect to your Atlas cluster
19 clientOptions := options.Client().ApplyURI(uri)
20 client, err := mongo.Connect(clientOptions)
21 if err != nil {
22 log.Fatalf("failed to connect to the server: %v", err)
23 }
24 defer func() { _ = client.Disconnect(ctx) }()
25
26 // Set the namespace
27 coll := client.Database("<databaseName>").Collection("<collectionName>")
28 indexName := "<indexName>"
29
30 type vectorDefinitionField struct {
31 Type string `bson:"type"`
32 Path string `bson:"path"`
33 NumDimensions int `bson:"numDimensions"`
34 Similarity string `bson:"similarity"`
35 }
36
37 type vectorDefinition struct {
38 Fields []vectorDefinitionField `bson:"fields"`
39 }
40
41 definition := vectorDefinition{
42 Fields: []vectorDefinitionField{{
43 Type: "vector",
44 Path: "<fieldToIndex>",
45 NumDimensions: <numberOfDimensions>,
46 Similarity: "euclidean | cosine | dotProduct"}},
47 }
48 err = coll.SearchIndexes().UpdateOne(ctx, indexName, definition)
49
50 if err != nil {
51 log.Fatalf("failed to update the index: %v", err)
52 }
53
54 fmt.Println("Successfully updated the search index")
55}
2

<connectionString>

Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。

<databaseName>

包含要为其创建索引的集合的数据库。

<collectionName>

要为其创建索引的集合。

<indexName>

索引的名称。如果索引名称,则默认为 vector_index

<numberOfDimensions>

MongoDB Vector Search 在索引时和查询时实施的向量维度数。

<fieldToIndex>

要索引的向量和筛选器字段。

3
go run edit-index.go

要使用MongoDB Java驾驶员v 或更高版本编辑集合的MongoDB Vector5.2.0 Search索引,请执行以下步骤:

1
1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoDatabase;
5import org.bson.Document;
6import org.bson.conversions.Bson;
7
8import java.util.Collections;
9
10public class EditVectorIndex {
11
12 public static void main(String[] args) {
13
14 // Replace the placeholder with your Atlas connection string
15 String uri = "<connectionString>";
16
17 // Connect to your Atlas cluster
18 try (MongoClient mongoClient = MongoClients.create(uri)) {
19
20 // Set the namespace
21 MongoDatabase database = mongoClient.getDatabase("<databaseName>");
22 MongoCollection<Document> collection = database.getCollection("<collectionName>");
23
24 // Define the index changes
25 String indexName = "<indexName>";
26 Bson definition = new Document(
27 "fields",
28 Collections.singletonList(
29 new Document("type", "vector")
30 .append("path", "<fieldToIndex>")
31 .append("numDimensions", "<numberOfDimensions>")
32 .append("similarity", "euclidean | cosine | dotProduct")
33 .append("quantization", "none | scalar | binary")));
34
35 // Update the index
36 collection.updateSearchIndex(indexName, definition);
37 System.out.println("Successfully updated the index");
38 }
39 }
40}
2

<connectionString>

Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。

<databaseName>

包含要为其创建索引的集合的数据库。

<collectionName>

要为其创建索引的集合。

<indexName>

索引的名称。如果索引名称,则默认为 vector_index

<numberOfDimensions>

MongoDB Vector Search 在索引时和查询时实施的向量维度数。

<fieldToIndex>

要索引的向量和筛选器字段。

3

从 IDE 运行该文件以使用更改更新索引。

要使用MongoDB节点驾驶员v 或更高版本更新集合的MongoDB Vector6.6.0 Search索引,请执行以下步骤:

1
1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas deployment
4const uri = "<connection-string>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 const database = client.db("<databaseName>");
11 const collection = database.collection("<collectionName>");
12
13 // define your MongoDB Search index
14 const index = {
15 name: "<indexName>",
16 type: "vectorSearch",
17 //updated search index definition
18 definition: {
19 "fields": [
20 {
21 "type": "vector",
22 "numDimensions": <numberOfDimensions>,
23 "path": "<field-to-index>",
24 "similarity": "euclidean | cosine | dotProduct"
25 },
26 {
27 "type": "filter",
28 "path": "<fieldToIndex>"
29 },
30 ...
31 ]
32 }
33 }
34
35 // run the helper method
36 await collection.updateSearchIndex("<index-name>", index);
37 } finally {
38 await client.close();
39 }
40}
41run().catch(console.dir);
2

<connectionString>

Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。

<databaseName>

包含要为其创建索引的集合的数据库。

<collectionName>

要为其创建索引的集合。

<indexName>

索引的名称。如果索引名称,则默认为 vector_index

<numberOfDimensions>

MongoDB Vector Search 在索引时和查询时实施的向量维度数。

<fieldToIndex>

要索引的向量和筛选器字段。

3
node <file-name>.js

要使用PyMongo驾驶员v 或更高版本更新集合的MongoDB Vector4.7 Search索引,请执行以下步骤:

1
1from pymongo.mongo_client import MongoClient
2
3# Connect to your Atlas deployment
4uri = "<connectionString>"
5client = MongoClient(uri)
6
7# Access your database and collection
8database = client["<databaseName>"]
9collection = database["<collectionName>"]
10
11definition = {
12 "fields": [
13 {
14 "type": "vector",
15 "numDimensions": <numberofDimensions>,
16 "path": "<fieldToIndex>",
17 "similarity": "euclidean | cosine | dotProduct",
18 "quantization": " none | scalar | binary "
19 },
20 {
21 "type": "filter",
22 "path": "<fieldToIndex>"
23 },
24 ...
25 ]
26}
27
28# Update your search index
29collection.update_search_index("<indexName>", definition)

要了解更多信息,请参阅 update_search_index() 方法。

2

<connectionString>

Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。

<databaseName>

包含要为其创建索引的集合的数据库。

<collectionName>

要为其创建索引的集合。

<indexName>

索引的名称。如果索引名称,则默认为 vector_index

<numberOfDimensions>

MongoDB Vector Search 在索引时和查询时实施的向量维度数。

<fieldToIndex>

要索引的向量和筛选器字段。

3
python <file-name>.py

您可以随时从Atlas用户界面、 Atlas管理API、 Atlas CLI、 或支持的MongoDB驱动程序中删除MongoDB Vectormongosh Search索引。

您必须具有 或更高角色才能删除MongoDB VectorProject Search Index Editor Search索引。

注意

您可以使用 命令或驾驶员辅助方法删除所有Atlas 集群层上的MongoDB Vector Searchmongosh 索引。有关支持的驾驶员版本的列表,请参阅支持的客户端。


➤ 使用选择语言下拉菜单选择要用于删除索引的客户端。


要使用Atlas Administration API删除集合的MongoDB Vector Search索引,请使用要删除的索引的唯一ID或名称向MongoDB Search indexes 端点发送 DELETE请求。

1curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \
2 --header "Accept: application/json" \
3 --include \
4 --request DELETE "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{indexId} | https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{databaseName}/{collectionName}/{indexName|indexId}"

要了解有关端点的语法和参数的更多信息,请参阅按名称删除一个搜索索引按 ID 删除一个搜索索引。

要使用Atlas CLI删除集合的MongoDB Vector Search索引,请执行以下步骤:

1

<indexId>

要删除的索引的唯一标识符。

<clusterName>

Atlas 集群的名称。

<projectId>

项目的唯一标识符。

2
atlas clusters search indexes delete <indexId> [options]

在命令中,将 indexId 占位符值替换为要删除的索引的唯一标识符。

要了解有关命令语法和参数的更多信息,请参阅 Atlas CLI 文档中的 atlas clusters search indexes delete 命令。

1

警告: 导航优化正在进行中我们目前正在逐步推出改进的全新导航体验。如果以下步骤与您在 Atlas UI 中的视图不符,请参阅预览文档

  1. 如果尚未显示,请从导航栏上的 Organizations 菜单中选择包含所需项目的组织。

  2. 如果尚未显示,请从导航栏的Projects菜单中选择所需的项目。

  3. 如果尚未出现,请单击侧边栏中的 Clusters(集群)。

    会显示集群页面。

2

您可以从侧边栏、Data Explorer 或集群详细信息页面转到MongoDB搜索页面。

  1. 在侧边栏中,单击 Services 标题下的 Atlas Search

    如果没有集群,则请单击 Create cluster 来创建一个。要了解更多信息,请参阅创建集群

  2. 如果您的项目有多个集群,请从 Select cluster 下拉列表中选择要使用的集群,然后单击 Go to Atlas Search

    将显示 Atlas Search 页面。

  1. 单击集群的对应 Browse Collections 按钮。

  2. 展开数据库并选择集合。

  3. 单击该集合的 Search Indexes 标签页。

    将显示 Atlas Search 页面。

  1. 单击集群的名称。

  2. 单击 Atlas Search 标签页。

    将显示 Atlas Search 页面。

3
  1. 找到要删除的 vectorSearch 类型索引。

  2. 从该索引的 Actions 下拉列表中,单击 Delete Index

  3. 单击确认窗口中的 Drop Index

要使用 删除集合的MongoDB Vectormongosh Search索引,请执行以下步骤:

1

要学习;了解更多信息,请参阅通过mongosh连接到集群。

2
3

db.collection.dropSearchIndex() 方法使用的语法如下:

1db.<collectionName>.dropSearchIndex( "<index-name>" );

要使用C#驾驶员 或更高版本删除集合的MongoDB Vector3.1.0 Search索引,请执行以下步骤:

1
1namespace query_quick_start;
2
3using MongoDB.Bson;
4using MongoDB.Driver;
5
6public class IndexService
7{
8 private const string MongoConnectionString = "<connectionString>";
9 // Other class methods here...
10 public void DeleteVectorIndex()
11 {
12 try
13 {
14 // Connect to your Atlas deployment
15 var client = new MongoClient(MongoConnectionString);
16
17 // Access your database and collection
18 var database = client.GetDatabase("<databaseName>");
19 var collection = database.GetCollection<BsonDocument>("<collectionName>");
20
21 // Delete your search index
22 var searchIndexView = collection.SearchIndexes;
23 var name = "vector_index";
24 searchIndexView.DropOne(name);
25
26 Console.WriteLine($"Dropping search index named {name}. This may take up to a minute.");
27 }
28 catch (Exception e)
29 {
30 Console.WriteLine($"Exception: {e.Message}");
31 }
32 }
33}
2

<connectionString>

您的Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。

<databaseName>

包含该集合的数据库名称。

<collectionName>

集合的名称。

<indexName>

要删除的索引名称。

3
using query_quick_start;
var indexService = new IndexService();
indexService.DeleteVectorIndex();
4
dotnet run

要使用MongoDB Go驾驶员v 或更高版本删除集合的MongoDB Vector2.0 Search索引,请执行以下步骤:

1
1package main
2
3import (
4 "context"
5 "fmt"
6 "log"
7
8 "go.mongodb.org/mongo-driver/v2/mongo"
9 "go.mongodb.org/mongo-driver/v2/mongo/options"
10)
11
12func main() {
13 ctx := context.Background()
14
15 // Replace the placeholder with your Atlas connection string
16 const uri = "<connectionString>"
17
18 // Connect to your Atlas cluster
19 clientOptions := options.Client().ApplyURI(uri)
20 client, err := mongo.Connect(clientOptions)
21 if err != nil {
22 log.Fatalf("failed to connect to the server: %v", err)
23 }
24 defer func() { _ = client.Disconnect(ctx) }()
25
26 // Set the namespace
27 coll := client.Database("<databaseName>").Collection("<collectionName>")
28 indexName := "<indexName>"
29
30 err = coll.SearchIndexes().DropOne(ctx, indexName)
31 if err != nil {
32 log.Fatalf("failed to delete the index: %v", err)
33 }
34
35 fmt.Println("Successfully deleted the Vector Search index")
36}
2

<connectionString>

您的Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。

<databaseName>

包含要创建索引的集合的数据库。

<collectionName>

要为其创建索引的集合。

<indexName>

索引的名称。如果索引名称,则默认为 vector_index

3
go run delete-index.go

要使用MongoDB Java驾驶员v 或更高版本删除集合的MongoDB Vector5.2.0 Search索引,请执行以下步骤:

1
1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoDatabase;
5import org.bson.Document;
6
7public class DeleteIndex {
8
9 public static void main(String[] args) {
10
11 // Replace the placeholder with your Atlas connection string
12 String uri = "<connectionString>";
13
14 // Connect to your Atlas cluster
15 try (MongoClient mongoClient = MongoClients.create(uri)) {
16
17 // Set the namespace
18 MongoDatabase database = mongoClient.getDatabase("<databaseName>");
19 MongoCollection<Document> collection = database.getCollection("<collectionName>");
20
21 // Specify the index to delete
22 String indexName = "<indexName>";
23
24 try {
25 collection.dropSearchIndex(indexName);
26 } catch (Exception e) {
27 throw new RuntimeException("Error deleting index: " + e);
28 }
29
30 } catch (Exception e) {
31 throw new RuntimeException("Error connecting to MongoDB: " + e);
32 }
33 }
34}
2

<connectionString>

您的Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。

<databaseName>

包含要创建索引的集合的数据库。

<collectionName>

要为其创建索引的集合。

<indexName>

索引的名称。如果索引名称,则默认为 vector_index

3

从 IDE 运行该文件以删除指定的索引。

要使用MongoDB节点驾驶员v 或更高版本删除集合的MongoDB Vector6.6.0 Search索引,请执行以下步骤:

1
1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas deployment
4const uri = "<connectionString>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 const database = client.db("<databaseName>");
11 const collection = database.collection("<collectionName>");
12
13 // run the helper method
14 await collection.dropSearchIndex("<indexName>");
15
16 } finally {
17 await client.close();
18 }
19}
20run().catch(console.dir);
2

<connectionString>

您的Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。

<databaseName>

包含要创建索引的集合的数据库。

<collectionName>

要为其创建索引的集合。

<indexName>

索引的名称。如果索引名称,则默认为 vector_index

3
node <file-name>.js

要使用PyMongo驾驶员v 或更高版本删除集合的MongoDB Vector4.7 Search索引,请执行以下步骤:

1
1from pymongo.mongo_client import MongoClient
2
3# Connect to your Atlas deployment
4uri = "<connectionString>"
5client = MongoClient(uri)
6
7# Access your database and collection
8database = client["<databaseName>"]
9collection = database["<collectionName>"]
10
11# Delete your search index
12collection.drop_search_index("<indexName>")

要了解更多信息,请参阅 drop_search_index()方法。

2

<connectionString>

您的Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。

<databaseName>

包含该集合的数据库名称。

<collectionName>

集合的名称。

<indexName>

要删除的索引名称。

3
python <file-name>.py

创建MongoDB Vector Search索引时,Status 列会显示集群主节点 (primary node in the replica set)节点上索引的当前状态。单击状态下方的 View status details 链接,可查看集群所有节点上索引的状态。

Status 列显示为 Active时,索引已准备就绪,可供使用。在其他状态下,对索引的查询可能会返回不完整的结果。

状态
说明

未启动

Atlas 尚未开始构建索引。

初始化同步(Resumable Initial Sync)

Atlas 正在构建索引或在编辑后重新构建索引。当该索引处于以下状态时:

  • 对于新索引,在索引构建完成之前, MongoDB Vector Search 不会提供服务查询服务。

  • 对于现有索引,可继续使用旧索引进行现有查询和新查询,直到索引重建完成。

活跃的

索引已准备就绪。

正在恢复

复制遇到错误。当当前复制点在 mongod oplog上不再可用时,通常会出现此状态。您仍然可以查询现有索引,直到它更新并且其状态变为 Active。使用 View status details 模式窗口中的错误来解决问题。要学习;了解更多信息,请参阅修复问题。

已失败

Atlas无法构建索引。使用 View status details 模式窗口中的错误来解决问题。要学习;了解更多信息,请参阅修复问题。

正在删除

Atlas 正在从集群节点中删除索引。

当 Atlas 构建索引时以及构建完成后,Documents 列会显示已完成索引的文档的百分比和数量。该列还会显示集合中的文档总数。

后退

创建嵌入

获得技能徽章

免费掌握“向量搜索基础知识”!

了解详情

在此页面上