您可以使用 vectorSearch
类型对字段进行索引以运行 $vectorSearch
查询。您可以为要查询的向量嵌入定义索引,以及为任何您希望用于预过滤数据的任何其他字段定义索引。过滤数据有助于缩小语义搜索范围,并确保在比较时(例如在多租户环境中)不考虑某些向量嵌入。
您可以使用Atlas用户界面、 Atlas管理API、 Atlas CLI、mongosh
或支持的MongoDB驱动程序来创建MongoDB Vector Search索引。
注意
您不能使用已弃用的 knnBeta 操作符来查询使用 vectorSearch
类型索引定义索引的字段。
Considerations
在 vectorSearch
类型索引定义中,您可以仅使用单个元素对数组索引。您无法对文档数组内的嵌入字段或对象数组内的嵌入字段索引。您可以使用点表示法对文档内的嵌入字段索引。不能在同一索引定义中对同一嵌入字段进行多次索引。
在对嵌入索引之前,我们建议您将嵌入转换为子类型为 、 或 的 BSON BinDatafloat32
int1
int8
向量,以便在集群中高效存储。要学习;了解更多信息,请参阅如何将嵌入转换为BSON向量。
使用MongoDB Vector Search 索引时, Atlas 集群的空闲节点上的资源消耗可能会增加。这是由根本的mongot进程造成的,该进程执行MongoDB Vector Search 的各种基本操作。空闲节点上的 CPU 利用率可能因索引的数量、复杂性和大小而异。
要了解有关索引大小注意事项的更多信息,请参阅索引向量的内存需求。
支持的客户端
您可以通过Atlas用户界面、mongosh
、 Atlas CLI、 Atlas管理API和以下MongoDB驱动程序:创建和管理MongoDB Vector Search 索引:
语法
以下语法定义了 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 索引字段
MongoDB Vector Search索引定义包含以下字段:
选项 | 类型 | 必要性 | 用途 |
---|---|---|---|
| 字段定义文档的数组 | 必需 | 要索引的向量和过滤字段的定义,每个文档一个定义。每个字段定义文档都为要索引的字段指定
|
fields. type | 字符串 | 必需 | 用于为
要学习;了解更多信息,请参阅关于 |
fields. path | 字符串 | 必需 | 要为其创建索引的字段名称。对于嵌套字段,使用点表示法来指定嵌入式字段的路径。 |
fields. numDimensions | Int | 必需 | MongoDB Vector Search 在索引时和查询时实施的向量维度数。只能为 对于索引量化向量或 BinData,您可以指定以下值之一:
您选择的嵌入模型决定了向量嵌入的维数,某些模型对于输出的维数有多个选项。要学习;了解更多信息,请参阅选择创建嵌入的方法。 |
fields. similarity | 字符串 | 必需 | 用于搜索前 K 个最近邻域的向量相似度函数。只能为 您可以指定以下值之一:
|
fields. quantization | 字符串 | Optional | 向量的自动向量量化类型。仅当嵌入是 您可以指定以下值之一:
|
fields. hnswOptions | 对象 | Optional | 用于构建 Hierarchical Navigable Small Worlds(分层可导航小世界) 图的参数。如果未指定,将使用 重要提示:这是作为“预览”功能提供的。修改默认值可能会对MongoDB Vector Search索引和查询产生负面影响。 |
fields. hnswOptions. maxEdges | Int | Optional | 在分层可导航小世界图中,一个节点最多可以拥有的边(或连接)数量。值可以在 数字越大,召回率(搜索结果的准确性)越高,因为图表的连接性更好。但是,由于每个图表节点要评估的邻居数量较多,这会降低查询速度;由于每个节点存储更多连接,因此会增加Hierarchical Navigable Small Worlds图表的内存;并且会减慢索引,因为MongoDB Vector Search 会评估更多邻居并进行调整添加到图表中的每个新节点。 |
fields. hnswOptions. numEdgeCandidates | Int | Optional | 类似于查询时的 较高的数值可以生成具有高质量连接的图,从而提升搜索质量(召回率),但也可能对查询延迟产生负面影响。 |
关于 vector
类型
索引定义的 vector
字段必须包含以下类型之一的数字数组:
您必须在 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
类似的测量计算,但考虑了向量的幅度。如果对幅度进行归一化,则cosine
和dotProduct
在衡量相似性方面几乎相同。要使用
dotProduct
,您必须在索引时和查询时将向量标准化为单位长度。
下表显示了各种类型的相似度函数:
向量嵌入类型 | euclidean | cosine | dotProduct |
---|---|---|---|
| √ | ||
| √ | √ | √ |
| √ | √ | √ |
| √ | √ | √ |
用于向量摄取。
用于自动标量或二进制量化。
为获得最佳性能,请检查您的嵌入模型,以确定哪个相似度函数适合嵌入模型的培训进程。 如果没有任何指导,请从 dotProduct
开始。 将 fields.similarity
设置为 dotProduct
值可让您根据角度和幅度有效地衡量相似性。 dotProduct
比 cosine
消耗的计算资源更少,并且在向量为单位长度时非常高效。 但是,如果您的向量未标准化,请评估 euclidean
距离和 cosine
相似度的示例查询结果中的相似度分数,以确定哪一个对应于合理的结果。
关于 filter
类型
您可以选择对附加字段建立索引,以便预先过滤您的数据。您可以使用过滤器过滤布尔值、日期、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
查询返回的分数。
创建MongoDB Vector Search 索引
您可以通过Atlas用户界面、 Atlas管理API 、 索引 Atlas CLI、8192mongosh
,或支持的MongoDB驱动程序。
先决条件
要创建MongoDB Vector Search索引,您的集群必须满足以下先决条件:
MongoDB 版本
6.0.11
、7.0.2
或更高版本要为其创建MongoDB Vector Search索引的集合
必需的访问权限
您需要 Project Data Access Admin
或更高角色才能创建和管理MongoDB Vector Search 索引。
索引限制
您创建的内容不能超过:
M0
集群上的 3 索引(无论类型是search
还是vector
)。针对 Flex 集群的 10 个索引。
我们建议您在单个 M10+
集群上创建不超过 2、500 个搜索索引。
步骤
➤ 使用选择语言下拉菜单选择要用于创建索引的客户端。
注意
该过程包括 sample_mflix
数据库中 embedded_movies
集合的索引定义示例。如果将示例数据加载到集群上并为此集合创建示例MongoDB Vector Search 索引,则可以对此集合运行示例$vectorSearch
查询。要学习;了解有关可以运行的示例查询的详情,请参阅 $vectorSearch 示例。
要使用Atlas API为集合创建MongoDB Vector Search索引,请使用所需参数向MongoDB Search indexes
端点发送 POST
请求。
1 curl --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的向量嵌入字段进行索引。
1 curl --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 。
1 curl --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索引,请执行以下步骤:
创建 .json
文件,并在文件中定义索引。
您的索引定义应遵循以下格式:
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
的文件。
替换以下占位符值并保存文件。
| 包含要为其创建索引的集合的数据库。 |
| 要为其创建索引的集合。 |
| 索引的名称。如果索引名称, MongoDB Vector Search 将索引命名为 |
| MongoDB Vector Search 在索引时和查询时实施的向量维度数。 |
| 要索引的向量和筛选器字段。 |
例子
将以下索引定义复制并粘贴到 vector-index.json
文件中。以下索引定义在MongoDB Vector Search索引中将 plot_embedding_voyage_3_large
字段索引为 vector
类型,并将 genres
和 year
字段索引为 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 }
运行以下命令以创建索引。
atlas clusters search indexes create --clusterName [cluster_name] --file [vector_index].json
在命令中,替换以下占位符值:
cluster_name
是集群的名称,该集合包含要为其创建索引的集合。vector_index
是包含MongoDB Vector Search索引 的索引定义的JSON文件的名称。
例子
atlas clusters search indexes create --clusterName [cluster_name] --file vector-index.json
要了解有关命令语法和参数的更多信息,请参阅 Atlas CLI 文档中的 Atlas 集群搜索索引创建命令。
开始您的索引配置。
在页面上进行以下选择,然后单击 Next。
Search Type | 选择 Vector Search 索引类型。 |
Index Name and Data Source | 指定以下信息:
|
Configuration Method | For a guided experience, select Visual Editor. To edit the raw index definition, select JSON Editor. |
重要提示:
默认下, MongoDB Search索引名为 default
。如果保留此名称,则该索引将是任何未在运算符中指定其他 index
选项的MongoDB搜索查询的默认搜索索引。如果您要创建多个索引,我们建议您在所有索引之间保持一致的描述性命名约定。
指定索引定义。
Atlas 会自动检测包含向量嵌入的字段及其相应的维度,并预填充最多三个向量字段。要配置该索引,请执行以下操作:
如有必要,请从 Path 下拉菜单中选择要索引的向量字段。
选择 Add Another Field 以索引任意其他字段。
在 Similarity Method 下拉菜单中为每个已索引字段指定相似性方法。
(可选)单击 Advanced,然后从下拉菜单中选择 Scalar 或 Binary 量化,以自动量化该字段中的嵌入。
(可选)在 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
字段会显示。
要配置该索引,请执行以下操作:
从 Similarity Method 下拉列表中选择 Dot Product。
单击 Advanced,然后从下拉菜单中选择 Scalar 量化。
在 Filter Field 部分,指定
genres
与year
字段以按它们来过滤该数据。
此索引定义对以下字段进行索引:
用于预过滤数据的 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 }
要使用mongosh
v2.1.2 或更高版本为集合创建MongoDB Vector Search索引,请执行以下步骤:
使用mongosh
连接到集群。
要学习;了解更多信息,请参阅通过mongosh连接到集群。
运行 db.collection.createSearchIndex()
方法。
db.collection.createSearchIndex()
方法使用的语法如下:
1 db.<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的向量嵌入字段进行索引。
1 db.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 。
1 db.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#驾驶员v3.1.0 或更高版本为集合创建MongoDB Vector Search索引,请执行以下步骤:
创建 .cs
文件,并在文件中定义索引。
1 using MongoDB.Bson; 2 using MongoDB.Driver; 3 using System; 4 using System.Threading; 5 6 // Connect to your Atlas deployment 7 private const string MongoConnectionString = "<connectionString>"; 8 var client = new MongoClient(MongoConnectionString); 9 10 // Access your database and collection 11 var database = client.GetDatabase("<databaseName>"); 12 var collection = database.GetCollection<BsonDocument>("<collectionName>"); 13 14 // Create your index model, then create the search index 15 var name = "<indexName>"; 16 var type = SearchIndexType.VectorSearch; 17 18 var 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 33 var model = new CreateSearchIndexModel(name, type, definition); 34 35 var searchIndexView = collection.SearchIndexes; 36 searchIndexView.CreateOne(model); 37 Console.WriteLine($"New search index named {name} is building."); 38 39 // Wait for initial sync to complete 40 Console.WriteLine("Polling to check if the index is ready. This may take up to a minute."); 41 bool queryable = false; 42 while (!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 } 57 Console.WriteLine($"{name} is ready for querying.");
1 using MongoDB.Bson; 2 using MongoDB.Driver; 3 using System; 4 using System.Threading; 5 6 // Connect to your Atlas deployment 7 private const string MongoConnectionString = "<connectionString>"; 8 var client = new MongoClient(MongoConnectionString); 9 10 // Access your database and collection 11 var database = client.GetDatabase("<databaseName>"); 12 var collection = database.GetCollection<BsonDocument>("<collectionName>"); 13 14 // Create your index models and add them to an array 15 var type = SearchIndexType.VectorSearch; 16 17 var 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 }; 31 var modelOne = new CreateSearchIndexModel("<indexName>", type, definitionOne); 32 33 var 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 }; 47 var modelTwo = new CreateSearchIndexModel("<indexName>", type, definitionTwo); 48 49 var models = new CreateSearchIndexModel[] { modelOne, modelTwo }; 50 51 // Create the search indexes 52 var searchIndexView = collection.SearchIndexes; 53 searchIndexView.CreateMany(models); 54 55 Console.WriteLine($"New search indexes are building. This may take up to a minute.");
例子
创建一个名为 IndexService.cs
的文件。
替换以下值并保存文件。
| Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。 |
| 包含要为其创建索引的集合的数据库。 |
| 要为其创建索引的集合。 |
| 索引的名称。如果索引名称,则默认为 |
| MongoDB Vector Search 在索引时和查询时实施的向量维度数。 |
| 要索引的向量和筛选器字段。 |
例子
将以下内容复制并粘贴到 IndexService.cs
中,并替换 <connectionString>
占位符值。以下索引定义在MongoDB Vector Search索引中将 plot_embedding_voyage_3_large
字段索引为 vector
类型,并将 genres
和 year
字段索引为 filter
类型。plot_embedding_voyage_3_large
字段包含使用 Voyage AI 的 voyage-3-large
嵌入模型创建的嵌入。索引定义指定了 2048
个向量维度,并使用 dotProduct
函数测量相似度。
以下索引定义仅对用于执行向量Atlas Search的向量嵌入字段 (plot_embedding_voyage_3_large
) 编制索引。
1 namespace query_quick_start; 2 3 using MongoDB.Bson; 4 using MongoDB.Driver; 5 using System; 6 using System.Threading; 7 8 public 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 。
1 namespace query_quick_start; 2 3 using MongoDB.Bson; 4 using MongoDB.Driver; 5 using System; 6 using System.Threading; 7 8 public 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 }
要使用MongoDB Go驾驶员 v2.0 或更高版本为集合创建MongoDB Vector Search索引,请执行以下步骤:
创建一个名为 create-index.go
的文件,并在文件中定义索引。
1 package main 2 3 import ( 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 13 func 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驾驶员。
替换以下值并保存文件。
| Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。 |
| 包含要为其创建索引的集合的数据库。 |
| 要为其创建索引的集合。 |
| 索引的名称。如果索引名称,则默认为 |
| MongoDB Vector Search 在索引时和查询时实施的向量维度数。 |
| 要索引的向量和筛选器字段。 |
例子
将以下内容复制并粘贴到 create-index.go
文件中,并替换 <connectionString>
占位符值。以下索引定义在MongoDB Vector Search索引中将 plot_embedding_voyage_3_large``
字段索引为 vector
类型,并将 genres
和 year
字段索引为 filter
类型。plot_embedding_voyage_3_large``
字段包含使用 Voyage AI 的 voyage-3-large
嵌入模型创建的嵌入。索引定义指定了 2048
个向量维度,并使用 dotProduct
函数测量相似度。
以下索引定义仅对用于执行向量Atlas Search的向量嵌入字段 (plot_embedding_voyage_3_large``
) 编制索引。
1 package main 2 3 import ( 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 14 func 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 。
1 package main 2 3 import ( 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 14 func 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 }
要使用MongoDB Java驾驶员 v5.2.0 或更高版本为集合创建MongoDB Vector Search索引,请执行以下步骤:
创建 .java
文件,并在文件中定义索引。
1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import com.mongodb.client.model.SearchIndexModel; 6 import com.mongodb.client.model.SearchIndexType; 7 import org.bson.Document; 8 import org.bson.conversions.Bson; 9 10 import java.util.Arrays; 11 import java.util.Collections; 12 import java.util.List; 13 14 public 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 }
替换以下值并保存文件。
| Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。 |
| 包含要为其创建索引的集合的数据库。 |
| 要为其创建索引的集合。 |
| 索引的名称。如果索引名称,则默认为 |
| MongoDB Vector Search 在索引时和查询时实施的向量维度数。 |
| 要索引的向量和筛选器字段。 |
以下是索引定义示例:
在MongoDB Vector Search索引中,将
plot_embedding_voyage_3_large
字段作为vector
类型进行索引,并将genres
和year
字段作为filter
类型进行索引。将
plot_embedding_voyage_3_large
字段指定为向量嵌入字段,其中包含使用 Voyage AI 的voyage-3-large
嵌入模型创建的嵌入。指定
2048
向量维度并使用dotProduct
函数衡量相似性。
此索引定义仅对向量嵌入字段 (plot_embedding_voyage_3_large
) 进行索引以执行向量搜索。
将以下内容复制并粘贴到您创建的文件中,然后替换 <connectionString>
占位符值。
1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import com.mongodb.client.model.SearchIndexModel; 6 import com.mongodb.client.model.SearchIndexType; 7 import org.bson.Document; 8 import org.bson.conversions.Bson; 9 10 import java.util.Collections; 11 import java.util.List; 12 13 public 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>
占位符值。
1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import com.mongodb.client.model.SearchIndexModel; 6 import com.mongodb.client.model.SearchIndexType; 7 import org.bson.Document; 8 import org.bson.conversions.Bson; 9 10 import java.util.Arrays; 11 import java.util.Collections; 12 import java.util.List; 13 14 public 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 }
要使用MongoDB节点驾驶员 v6.6.0 或更高版本为集合创建MongoDB Vector Search索引,请执行以下步骤:
创建 .js
文件,并在文件中定义索引。
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = "<connectionString>"; 5 6 const client = new MongoClient(uri); 7 8 async 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 } 57 run().catch(console.dir);
例子
创建一个名为 vector-index.js
的文件。
替换以下值并保存文件。
| Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。 |
| 包含要为其创建索引的集合的数据库。 |
| 要为其创建索引的集合。 |
| 索引的名称。如果索引名称,则默认为 |
| MongoDB Vector Search 在索引时和查询时实施的向量维度数。 |
| 要索引的向量和筛选器字段。 |
例子
将以下内容复制并粘贴到 vector-index.js
文件中,并替换 <connectionString>
占位符值。以下索引定义在MongoDB Vector Search索引中将 plot_embedding_voyage_3_large
字段索引为 vector
类型,并将 genres
和 year
字段索引为 filter
类型。plot_embedding_voyage_3_large
字段包含使用 Voyage AI 的 voyage-3-large
嵌入模型创建的嵌入。索引定义指定了 2048
个向量维度,并使用 dotProduct
函数测量相似度。
以下索引定义仅对用于执行向量Atlas Search的向量嵌入字段 (plot_embedding_voyage_3_large
) 编制索引。
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = "<connectionString>"; 5 6 const client = new MongoClient(uri); 7 8 async 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 } 54 run().catch(console.dir);
此索引定义对以下字段进行索引:
用于预过滤数据的 string 字段 (
genres
) 和数字字段 (year
)。向量嵌入字段 (
plot_embedding_voyage_3_large
),用于针对预筛选数据执行向量Atlas Search 。
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = "<connectionString>"; 5 6 const client = new MongoClient(uri); 7 8 async 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 } 62 run().catch(console.dir);
要使用PyMongo 驾驶员v4.7 或更高版本为集合创建MongoDB Vector Search 索引,请执行以下步骤:
创建 .py
文件,并在文件中定义索引。
1 from pymongo.mongo_client import MongoClient 2 from pymongo.operations import SearchIndexModel 3 import time 4 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 model, then create the search index 14 search_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 34 result = collection.create_search_index(model=search_index_model) 35 print("New search index named " + result + " is building.") 36 37 # Wait for initial sync to complete 38 print("Polling to check if the index is ready. This may take up to a minute.") 39 predicate=None 40 if predicate is None: 41 predicate = lambda index: index.get("queryable") is True 42 43 while True: 44 indices = list(collection.list_search_indexes(result)) 45 if len(indices) and predicate(indices[0]): 46 break 47 time.sleep(5) 48 print(result + " is ready for querying.") 49 50 client.close()
要学习;了解更多信息,请参阅 create_search_index() 方法。
1 from pymongo.mongo_client import MongoClient 2 from pymongo.operations import SearchIndexModel 3 4 def 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
的文件。
替换以下值并保存文件。
| Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。 |
| 包含要为其创建索引的集合的数据库。 |
| 要为其创建索引的集合。 |
| 索引的名称。如果索引名称,则默认为 |
| MongoDB Vector Search 在索引时和查询时实施的向量维度数。 |
| 要索引的向量和筛选器字段。 |
例子
将以下内容复制并粘贴到 vector-index.py
中,并替换 <connectionString>
占位符值。以下索引定义在MongoDB Vector Search索引中将 plot_embedding_voyage_3_large
字段索引为 vector
类型,并将 genres
和 year
字段索引为 filter
类型。plot_embedding_voyage_3_large
字段包含使用 Voyage AI 的 voyage-3-large
嵌入模型创建的嵌入。索引定义指定了 2048
个向量维度,并使用 dotProduct
函数测量相似度。
以下索引定义仅对用于执行向量Atlas Search的向量嵌入字段 (plot_embedding_voyage_3_large
) 编制索引。
1 from pymongo.mongo_client import MongoClient 2 from pymongo.operations import SearchIndexModel 3 import time 4 5 # Connect to your Atlas deployment 6 uri = "<connectionString>" 7 client = MongoClient(uri) 8 9 # Access your database and collection 10 database = client["sample_mflix"] 11 collection = database["embedded_movies"] 12 13 # Create your index model, then create the search index 14 search_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 30 result = collection.create_search_index(model=search_index_model) 31 print("New search index named " + result + " is building.") 32 33 # Wait for initial sync to complete 34 print("Polling to check if the index is ready. This may take up to a minute.") 35 predicate=None 36 if predicate is None: 37 predicate = lambda index: index.get("queryable") is True 38 39 while True: 40 indices = list(collection.list_search_indexes(result)) 41 if len(indices) and predicate(indices[0]): 42 break 43 time.sleep(5) 44 print(result + " is ready for querying.") 45 46 client.close()
此索引定义对以下字段进行索引:
用于预过滤数据的 string 字段 (
genres
) 和数字字段 (year
)。向量嵌入字段 (
plot_embedding_voyage_3_large
),用于针对预筛选数据执行向量Atlas Search 。
1 from pymongo.mongo_client import MongoClient 2 from pymongo.operations import SearchIndexModel 3 import time 4 5 # Connect to your Atlas deployment 6 uri = "<connectionString>" 7 client = MongoClient(uri) 8 9 # Access your database and collection 10 database = client["sample_mflix"] 11 collection = database["embedded_movies"] 12 13 # Create your index model, then create the search index 14 search_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 38 result = collection.create_search_index(model=search_index_model) 39 print("New search index named " + result + " is building.") 40 41 # Wait for initial sync to complete 42 print("Polling to check if the index is ready. This may take up to a minute.") 43 predicate=None 44 if predicate is None: 45 predicate = lambda index: index.get("queryable") is True 46 47 while True: 48 indices = list(collection.list_search_indexes(result)) 49 if len(indices) and predicate(indices[0]): 50 break 51 time.sleep(5) 52 print(result + " is ready for querying.") 53 54 client.close()
查看MongoDB Vector Search 索引
您可以从Atlas用户界面、 Atlas管理API、 Atlas CLI、mongosh
或支持的MongoDB驱动程序。查看所有集合的MongoDB Vector Search 索引。
必需的访问权限
您需要 Project Search Index Editor
或更高角色才能查看MongoDB Vector Search 索引。
步骤
➤ 使用选择语言下拉菜单设置本节中示例的语言。
要使用Atlas API检索集合的所有MongoDB Vector Search检索,请向MongoDB Search indexes
端点发送 GET
请求,其中包含数据库和集合的名称。
1 curl --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 API检索集合的一个MongoDB Vector Search检索,请向MongoDB Search indexes
端点发送 GET
请求,索引附带检索的索引的唯一ID或名称(第 4 行)。
1 curl --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 索引,请执行以下步骤:
运行以下命令来检索集合的索引。
atlas clusters search indexes list --clusterName [cluster_name] --db <db-name> --collection <collection-name>
在命令中,替换以下占位符值:
cluster-name
- 包含索引集合的集群的名称。db-name
- 包含要检索其索引的集合的数据库名称。collection-name
- 要检索其索引的集合的名称。
要了解有关命令语法和参数的更多信息,请参阅 Atlas CLI 文档中的 Atlas 集群搜索索引列表命令。
此页面会显示页面上索引的以下详细信息:
名称 | 标识索引的标签。 |
索引类型 | 指示MongoDB Search 或MongoDB Vector Search索引的标签。值包括:
|
索引字段 | 包含此索引索引的字段的列表。 |
状态 | 集群主节点 (primary node in the replica set)节点上索引的当前状态。 有关有效值,请参阅索引状态。 |
size | 主节点上索引的大小。 |
文档 (Document) | 已建立索引的文档数与集合中文档总数的比值。 |
所需内存 | 运行向量搜索查询所需的大致内存量。 |
操作 | 可以对索引执行的操作。 您可以: 您无法在 Search Tester 用户用户界面中针对 |
要使用 mongosh
查看集合的MongoDB Vector Search索引,请执行以下步骤:
使用mongosh
连接到集群。
要学习;了解更多信息,请参阅通过mongosh连接到集群。
运行 db.collection.getSearchIndexes()
方法。
db.collection.getSearchIndexes()
方法使用的语法如下:
1 db.<collectionName>.getSearchIndexes( "<index-name>" );
要使用C# 驾驶员3.1.0 或更高版本查看集合的MongoDB Vector Search 索引,请执行以下步骤:
创建 .cs
文件并使用 .List()
方法检索集合的索引。
1 namespace query_quick_start; 2 3 using MongoDB.Bson; 4 using MongoDB.Driver; 5 6 public 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 }
替换以下值并保存文件。
| 您的Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。 |
| 包含该集合的数据库名称。 |
| 集合的名称。 |
要使用MongoDB Go驾驶员 v2.0 或更高版本查看集合的MongoDB Vector Search索引,请执行以下步骤:
创建名为 get-index.go
的文件并使用 SearchIndexes().List()
方法检索索引。
1 package main 2 3 import ( 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 14 func 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 }
替换以下值并保存文件。
| 您的Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。 |
| 包含该集合的数据库。 |
| 要检索其索引的集合。 |
| 如果您想检索特定索引,请提供索引的名称。要返回集合中的所有索引,请省略此值,并在创建搜索索引选项时删除对 |
要使用MongoDB Java驾驶员 v5.2.0 或更高版本查看集合的MongoDB Vector Search索引,请执行以下步骤:
创建 .java
文件并使用 listSearchIndexes()
方法检索索引。
1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import org.bson.Document; 6 7 public 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 }
替换以下值并保存文件。
| 您的Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。 |
| 包含该集合的数据库。 |
| 要检索其索引的集合。 |
| 如果要检索特定索引,请输入索引的名称。 要返回集合上的所有索引,请省略此值。 |
要使用MongoDB节点驾驶员 v6.6.0 或更高版本查看集合的MongoDB Vector Search索引,请执行以下步骤:
创建 .js
文件并使用 listSearchIndexes()
方法检索索引。
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = "<connectionString>"; 5 6 const client = new MongoClient(uri); 7 8 async 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 } 20 run().catch(console.dir);
替换以下值并保存文件。
| 您的Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。 |
| 包含该集合的数据库。 |
| 要检索其索引的集合。 |
| 如果要检索特定索引,请输入索引的名称。 要返回集合上的所有索引,请省略此值。 |
要使用PyMongo 驾驶员v4.7 或更高版本查看集合的MongoDB Vector Search 索引,请执行以下步骤:
创建 .py
文件并使用 list_search_indexes()
方法检索集合的索引。
1 from pymongo.mongo_client import MongoClient 2 3 # Connect to your Atlas deployment 4 uri = "<connectionString>" 5 client = MongoClient(uri) 6 7 # Access your database and collection 8 database = client["<databaseName>"] 9 collection = database["<collectionName>"] 10 11 # Get a list of the collection's search indexes and print them 12 cursor = collection.list_search_indexes() 13 for index in cursor: 14 print(index)
要了解更多信息,请参阅 list_search_indexes() 方法。
替换以下值并保存文件。
| 您的Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。 |
| 包含该集合的数据库名称。 |
| 集合的名称。 |
编辑MongoDB Vector Search 索引
您可以从Atlas用户界面、 Atlas管理API、 Atlas CLI、mongosh
或支持的MongoDB驱动程序更改现有MongoDB Vector Search索引的索引定义。您无法重命名索引或更改索引类型。如果需要更改索引名称或类型,则必须创建新索引并删除旧索引。
重要
编辑索引后, MongoDB Vector Search 会重建索引。重建索引时,您可以使用旧索引定义继续运行向量搜索查询。当索引完成重建后,旧索引将被自动替换。此进程类似于MongoDB Search 索引。要学习;了解更多信息,请参阅创建和更新MongoDB搜索索引。
必需的访问权限
您必须具有 Project Search Index Editor
或更高角色才能编辑MongoDB Vector Search索引。
步骤
➤ 使用选择语言下拉菜单选择要用于编辑索引的客户端。
要使用Atlas API编辑集合的MongoDB Vector Search索引,请向MongoDB Search indexes
端点发送 PATCH
请求,并附带要编辑的索引的唯一ID或名称(第 4 行)。
1 curl --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索引,请执行以下步骤:
创建一个 .json
文件,并在文件中定义索引的更改。
您的索引定义应遵循以下格式:
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 }
运行以下命令以更新索引。
atlas clusters search indexes update <indexId> --clusterName [cluster_name] --file [vector-_index].json
在命令中,替换以下占位符值:
cluster_name
- 包含要更新索引的集合的集群的名称。vector_index
- JSON文件的名称,该文件包含MongoDB Vector Search索引的修改后的索引定义。
要了解有关命令语法和参数的更多信息,请参阅 Atlas CLI 文档中的 atlas clusters search indexes update 命令。
编辑索引。
找到要编辑的
vectorSearch
类型索引。在该索引的 Actions 列中,单击 。
选择Edit With Visual Editor以获得引导体验,或选择Edit With JSON Editor以编辑原始索引定义。
检查当前配置设置,并根据需要进行编辑。
要学习;了解有关MongoDB Vector Search索引中字段的更多信息,请参阅如何为向量搜索的字段创建索引。
单击 Save(保存)以应用更改。
索引状态从 Active 更改为 Building。在此状态下,您可以继续使用旧索引,因为在更新后的索引可供使用之前, MongoDB Vector Search 不会删除旧索引。一旦状态返回到 Active,则修改后的索引就可以使用了。
要使用 mongosh
编辑集合的MongoDB Vector Search索引,请执行以下步骤:
使用mongosh
连接到集群。
要学习;了解更多信息,请参阅通过mongosh连接到集群。
运行 db.collection.updateSearchIndex()
方法。
db.collection.updateSearchIndex()
方法使用的语法如下:
1 db.<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#驾驶员3.1.0 或更高版本更新集合的MongoDB Vector Search索引,请执行以下步骤:
创建 .cs
文件,并在文件中定义索引更改。
1 namespace query_quick_start; 2 3 using MongoDB.Bson; 4 using MongoDB.Driver; 5 6 public 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 }
替换以下值并保存文件。
| Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。 |
| 包含要为其创建索引的集合的数据库。 |
| 要为其创建索引的集合。 |
| 索引的名称。如果索引名称,则默认为 |
| MongoDB Vector Search 在索引时和查询时实施的向量维度数。 |
| 要索引的向量和筛选器字段。 |
要使用MongoDB Go驾驶员 v2.0 或更高版本更新集合的MongoDB Vector Search索引,请执行以下步骤:
创建一个名为 edit-index.go
的文件,并在文件中定义索引更改。
1 package main 2 3 import ( 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 12 func 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 }
替换以下值并保存文件。
| Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。 |
| 包含要为其创建索引的集合的数据库。 |
| 要为其创建索引的集合。 |
| 索引的名称。如果索引名称,则默认为 |
| MongoDB Vector Search 在索引时和查询时实施的向量维度数。 |
| 要索引的向量和筛选器字段。 |
要使用MongoDB Java驾驶员 v5.2.0 或更高版本编辑集合的MongoDB Vector Search索引,请执行以下步骤:
创建 .java
文件,并在文件中定义索引更改。
1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import org.bson.Document; 6 import org.bson.conversions.Bson; 7 8 import java.util.Collections; 9 10 public 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 }
替换以下值并保存文件。
| Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。 |
| 包含要为其创建索引的集合的数据库。 |
| 要为其创建索引的集合。 |
| 索引的名称。如果索引名称,则默认为 |
| MongoDB Vector Search 在索引时和查询时实施的向量维度数。 |
| 要索引的向量和筛选器字段。 |
要使用MongoDB节点驾驶员 v6.6.0 或更高版本更新集合的MongoDB Vector Search索引,请执行以下步骤:
创建 .js
文件,并在文件中定义索引更改。
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = "<connection-string>"; 5 6 const client = new MongoClient(uri); 7 8 async 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 } 41 run().catch(console.dir);
替换以下值并保存文件。
| Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。 |
| 包含要为其创建索引的集合的数据库。 |
| 要为其创建索引的集合。 |
| 索引的名称。如果索引名称,则默认为 |
| MongoDB Vector Search 在索引时和查询时实施的向量维度数。 |
| 要索引的向量和筛选器字段。 |
要使用PyMongo驾驶员v4.7 或更高版本更新集合的MongoDB Vector Search索引,请执行以下步骤:
创建 .py
文件,并在文件中定义索引更改。
1 from pymongo.mongo_client import MongoClient 2 3 # Connect to your Atlas deployment 4 uri = "<connectionString>" 5 client = MongoClient(uri) 6 7 # Access your database and collection 8 database = client["<databaseName>"] 9 collection = database["<collectionName>"] 10 11 definition = { 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 29 collection.update_search_index("<indexName>", definition)
要了解更多信息,请参阅 update_search_index() 方法。
替换以下值并保存文件。
| Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。 |
| 包含要为其创建索引的集合的数据库。 |
| 要为其创建索引的集合。 |
| 索引的名称。如果索引名称,则默认为 |
| MongoDB Vector Search 在索引时和查询时实施的向量维度数。 |
| 要索引的向量和筛选器字段。 |
删除MongoDB Vector Search 索引
您可以随时从Atlas用户界面、 Atlas管理API、 Atlas CLI、mongosh
或支持的MongoDB驱动程序。中删除MongoDB Vector Search索引。
必需的访问权限
您必须具有 Project Search Index Editor
或更高角色才能删除MongoDB Vector Search索引。
步骤
➤ 使用选择语言下拉菜单选择要用于删除索引的客户端。
要使用Atlas API删除集合的MongoDB Vector Search索引,请使用要删除的索引的唯一ID或名称向MongoDB Search indexes
端点发送 DELETE
请求。
1 curl --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索引,请执行以下步骤:
运行命令,以删除索引。
atlas clusters search indexes delete <indexId> [options]
在命令中,将 indexId
占位符值替换为要删除的索引的唯一标识符。
要了解有关命令语法和参数的更多信息,请参阅 Atlas CLI 文档中的 atlas clusters search indexes delete 命令。
要使用mongosh
删除集合的MongoDB Vector Search索引,请执行以下步骤:
使用mongosh
连接到集群。
要学习;了解更多信息,请参阅通过mongosh连接到集群。
运行 db.collection.dropSearchIndex()
方法。
db.collection.dropSearchIndex()
方法使用的语法如下:
1 db.<collectionName>.dropSearchIndex( "<index-name>" );
要使用C#驾驶员3.1.0 或更高版本删除集合的MongoDB Vector Search索引,请执行以下步骤:
创建 .cs
文件并使用 DropOne()
方法删除索引。
1 namespace query_quick_start; 2 3 using MongoDB.Bson; 4 using MongoDB.Driver; 5 6 public 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 }
替换以下值并保存文件。
| 您的Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。 |
| 包含该集合的数据库名称。 |
| 集合的名称。 |
| 要删除的索引名称。 |
要使用MongoDB Go驾驶员 v2.0 或更高版本删除集合的MongoDB Vector Search索引,请执行以下步骤:
创建一个名为 delete-index.go
的文件,并使用 SearchIndexes().DropOne()
方法删除索引。
1 package main 2 3 import ( 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 12 func 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 }
替换以下值并保存文件。
| 您的Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。 |
| 包含要创建索引的集合的数据库。 |
| 要为其创建索引的集合。 |
| 索引的名称。如果索引名称,则默认为 |
要使用MongoDB Java驾驶员 v5.2.0 或更高版本删除集合的MongoDB Vector Search索引,请执行以下步骤:
创建 .java
文件并使用 collection.dropSearchIndex()
方法删除索引。
1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import org.bson.Document; 6 7 public 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 }
替换以下值并保存文件。
| 您的Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。 |
| 包含要创建索引的集合的数据库。 |
| 要为其创建索引的集合。 |
| 索引的名称。如果索引名称,则默认为 |
要使用MongoDB节点驾驶员 v6.6.0 或更高版本删除集合的MongoDB Vector Search索引,请执行以下步骤:
创建 .js
文件并使用 dropSearchIndex()
方法删除索引。
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = "<connectionString>"; 5 6 const client = new MongoClient(uri); 7 8 async 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 } 20 run().catch(console.dir);
替换以下值并保存文件。
| 您的Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。 |
| 包含要创建索引的集合的数据库。 |
| 要为其创建索引的集合。 |
| 索引的名称。如果索引名称,则默认为 |
要使用PyMongo驾驶员v4.7 或更高版本删除集合的MongoDB Vector Search索引,请执行以下步骤:
创建 .py
文件并使用 drop_search_index()
方法删除索引。
1 from pymongo.mongo_client import MongoClient 2 3 # Connect to your Atlas deployment 4 uri = "<connectionString>" 5 client = MongoClient(uri) 6 7 # Access your database and collection 8 database = client["<databaseName>"] 9 collection = database["<collectionName>"] 10 11 # Delete your search index 12 collection.drop_search_index("<indexName>")
要了解更多信息,请参阅 drop_search_index()方法。
替换以下值并保存文件。
| 您的Atlas连接字符串。 要学习;了解更多信息,请参阅通过驱动程序连接到集群。 |
| 包含该集合的数据库名称。 |
| 集合的名称。 |
| 要删除的索引名称。 |
索引状态
创建MongoDB Vector Search索引时,Status 列会显示集群主节点 (primary node in the replica set)节点上索引的当前状态。单击状态下方的 View status details 链接,可查看集群所有节点上索引的状态。
当 Status 列显示为 Active时,索引已准备就绪,可供使用。在其他状态下,对索引的查询可能会返回不完整的结果。
状态 | 说明 |
---|---|
未启动 | Atlas 尚未开始构建索引。 |
初始化同步(Resumable Initial Sync) | Atlas 正在构建索引或在编辑后重新构建索引。当该索引处于以下状态时:
|
活跃的 | 索引已准备就绪。 |
正在恢复 | |
已失败 | Atlas无法构建索引。使用 View status details 模式窗口中的错误来解决问题。要学习;了解更多信息,请参阅修复问题。 |
正在删除 | Atlas 正在从集群节点中删除索引。 |
当 Atlas 构建索引时以及构建完成后,Documents 列会显示已完成索引的文档的百分比和数量。该列还会显示集合中的文档总数。