管理 Atlas Search 索引
Atlas Search索引是一种数据结构,它将数据分类为易于搜索的格式。它是术语与包含这些术语的文档之间的映射。 Atlas Search索引启用使用某些标识符更快地检索文档。您必须配置Atlas Search索引,才能使用Atlas Search查询Atlas 集群中的数据。
您可在单个字段或多个字段上创建 Atlas Search 索引。我们建议您对经常用于排序或筛选数据的字段建立索引,以便在查询时快速检索包含相关数据的文档。
Considerations
在创建和管理 Atlas Search 索引时,请考虑以下几点:
索引的一致性与重建
如果您对为其定义Atlas Search索引的集合进行更改,最新数据可能无法立即用于查询。但是,mongot
会监控变更流,使其能够更新存储的数据副本, Atlas Search索引最终会一致。
当您更改索引定义时,mongot
会在背景自动重建新索引,同时继续使用旧索引为查询提供服务,以确保不会停机。当您在同一节点上部署mongot
和 mongod
进程以及将进程部署在不同节点上时,会发生这种情况。当您启用或禁用 静态加密时, Atlas还会重建索引。
如果您更改搜索部署的拓扑结构,Atlas Search 会在删除旧节点之前在任何新节点上配置并构建索引,以确保查询不会停机。
对于 mongod
和 mongot
进程在同一节点上运行的部署,如果Atlas Search引入需要重建索引的更改(例如某些Atlas Search功能需要更新索引),Atlas会自动部署额外的节点免费构建索引,而旧节点继续为您的查询提供服务。
警告
如果您对已具有 Atlas Search 索引的集合进行分片,当该集合开始出现在分片上时,您可能会遇到短暂的查询停机时间。此外,如果您为包含 Atlas Search 索引的已分片集合添加分片,针对该集合的搜索查询将失败,直到添加的分片完成初始同步过程为止。要了解更多信息,请参阅初始同步进程。
专用搜索节点
您可以部署专用搜索节点来提高性能、可扩展性和资源隔离。如果您已经部署搜索节点,请考虑以下情况:
添加和调整 分片将会触发 Atlas Search 索引重建。在该索引重建期间,索引可能没有最新的数据。因此,针对这些分片上的数据的查询可能会失败,或返回不正确的结果。
如果您对包含Atlas Search索引的集合进行重新分片,则在重新分片操作完成后,该集合上的Atlas Search索引将变为不可用。操作完成后,您必须删除Atlas Search 索引并创建新的Atlas Search索引。
如果发出命令更改数据库的主分片,则一旦操作完成,该数据库下任何未分片集合的 Atlas Search索引将不可用。
movePrimary
操作完成后,您必须删除并创建新的 Atlas Search 索引。
要学习;了解有关Atlas Search节点架构的更多信息,请参阅Atlas Search部署选项。
磁盘、内存和资源使用
虽然 Atlas Search 上存储的数据与 Atlas 集群上的集合中的数据副本不同,Atlas Search 索引仍会占用部分磁盘空间和内存。如果您为包含字符串值的字段启用 store
选项,或在索引中配置存储的源字段,Atlas Search 则会在磁盘上存储指定字段的相同副本,而此副本可能会占用磁盘空间。
注意
如果您的集合包含 16 MB 或更大的文档,Atlas Search 将无法为您的数据编制索引。当大型文档的更新操作导致变更流事件超过 16MB BSON 限制时,也可能会出现此问题。为避免这种情况,请考虑以下最佳实践:
将您的文档结构化,以减少子文档或数组的大小。
避免执行更新或替换大字段、子文档或数组的操作。
要了解更多信息,请参阅 Change Streams 生产建议和减少大型文档的大小。
并发请求
如果并发索引创建或其他索引管理操作请求过多, Atlas Search将返回以下错误:
Too many concurrent requests. Please try again later.
我们建议您稍后重试。
支持的客户端
您可以通过 Atlas UI、Atlas Search API、Atlas CLI、 mongosh
、MongoDB Compass 和 MongoDB 驱动程序创建和管理 Atlas Search 索引。
➤ 使用页面中的选择语言下拉菜单为此页面中的过程设立客户端。
Atlas CLI
要使用 Atlas CLI 创建和管理 Atlas Search 索引,您的 Atlas 集群必须运行 MongoDB 6.0+ 或 7.0+。
mongosh
要使用 创建和管理Atlas Search索引,mongosh
Atlas 集群必须运行MongoDB6.0 + 或7.0 +。
MongoDB Compass
要使用Compass创建和管理AtlasAtlas Search Search索引,您的AtlasCompass Atlas集群必须运行MongoDBMongoDB7.0 +。
MongoDB 驱动程序
要在任何集群层上以编程方式创建和管理AtlasAtlas Search MongoDBSearch索引,您可以使用以下任何MongoDB驱动程序:
必需的访问权限
您可以分配项目用户角色或数据库用户角色,以访问权限执行本指南中描述的Atlas Search索引操作所需的用户权限。
下表显示了以下项目角色支持指定Atlas Search操作的访问权限模式:
角色 | Atlas Search 操作 | Atlas UI | Atlas CLI | Atlas API [1] |
---|---|---|---|---|
查看Atlas Search索引和分析器。 | ✓ | ✓ | ||
创建、查看、更新和删除Atlas Search索引和分析器。 | ✓ | ✓ | ✓ | |
创建、查看、更新和删除 Atlas 搜索索引。 | ✓ | ✓ | ✓ |
[1] | 每个角色授予的权限允许在 Atlas Administration API 中调用 Atlas Search API 终结点的子集或完整集合。有关每个角色可访问的 API 终结点的说明,请参阅 Atlas Search Action 列。 |
以下MongoDB数据库角色支持给定的Atlas Search索引特权操作:
操作说明 | 数据库角色 | Atlas Search索引特权操作 |
---|---|---|
查看Atlas Search索引 | ||
创建Atlas Search索引 | ||
编辑Atlas Search索引 | ||
删除Atlas Search索引 |
创建 Atlas Search 索引
以下教程介绍了如何使用所选方法创建Atlas Search索引。
要查看为 sample_mflix.movies
集合创建索引的示例教程,请参阅Atlas Search快速入门。有关如何定义索引以满足您的查询偏好的概念概述,请参阅定义索引。
您还可以将 Atlas Search 与通过 Atlas CLI 创建的本地 Atlas 部署结合使用。要了解详情,请参阅创建本地 Atlas 部署。
要使用Atlas Search API创建Atlas Search索引,请执行以下操作:
发送 POST
请求。
向 search/indexes
端点发送 POST
请求。
curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \ --header "Accept: application/json" \ --header "Content-Type: application/json" \ --include \ --request POST "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes" \ --data ' { "collectionName": "<collection-name>", "database": "<database-name>", "name": "<index-name>", "type": "search", "definition": { "analyzer": "<analyzer-name>", "searchAnalyzer": "<analyzer-name>", "mappings": { "dynamic": <boolean>, "fields": { <field-definition> } }, "numPartitions": <integer>, "analyzers": [ { <custom-analyzer-definition> } ], "storedSource": <boolean> | { <stored-source-definition> }, "synonyms": [ { <synonym-mapping-definition> } ] } }'
要了解有关此端点的语法和参数的更多信息,请参阅创建一个。
要使用Atlas CLI创建Atlas Search索引,请执行以下操作:
云部署
要使用 Atlas CLI 为集群创建搜索索引,请运行以下命令:
atlas clusters search indexes create [indexName] [options]
要了解有关命令语法和参数的更多信息,请参阅 Atlas CLI 文档中的 atlas clusters search indexes create 部分。
本地部署
要使用 Atlas CLI 为指定部署创建搜索索引,请运行以下命令:
atlas deployments search indexes create [indexName] [options]
要了解有关命令语法和参数的更多信息,请参阅 Atlas CLI 文档的 atlas deployments search indexes create 部分。
要学习;了解有关如何使用Atlas CLI创建本地Atlas部署的更多信息,请参阅创建本地Atlas部署。
例子
以下示例说明了如何使用 atlas clusters
或 atlas deployments
命令通过配置文件在非交互模式下创建 Atlas Search 索引。
要使用Atlas用户界面创建Atlas Search索引,请执行以下操作:
查看 Index Configurations(索引配置)部分中的默认 Atlas Search 索引配置设置。
默认索引定义是文档中字段的动态映射,适用于任何集合。
要自定义索引定义,查看以下索引配置:
可视化编辑器字段 | 说明 | 必要性 |
---|---|---|
Index Analyzer | Optional | |
Search Analyzer | Optional | |
Dynamic Mapping | 指定字段的动态或静态映射。 默认下,启用动态映射。要禁用动态映射,请将 要学习;了解有关动态和静态映射的更多信息,请参阅定义字段映射。 对应于 | 必需 |
如果您对默认配置感到满意,请跳过。如果您希望完善您的 Atlas Search 索引,请继续执行下一步。
优化 Atlas Search 索引,配置其他设置。
单击 Refine Your Index 更改以下任何设置。
字段名称说明必要性Field Mappings
如果 Index Configurations 部分中的 Dynamic Mapping 处于禁用状态,则为必填项。
指定要索引的字段:
点击 Add Field Mapping 打开 Add Field Mapping 窗口。
指定关于字段的以下信息:
Field name -要索引的字段名称。
Data Type - 字段数据类型。要详细了解支持的数据类型及其选项,请参阅数据类型。
(可选)指定其他属性。
其他配置选项表出现在 Add Field Mapping窗口中。这些属性取决于您在上一步中选择的数据类型。
要详细了解支持的数据类型及其选项,请参阅数据类型。
(可选)添加多字段。
单击 Add Multi Field 配置备用字段分析器,用于索引字段。要学习;了解更多信息,请参阅多分析器。
单击 Add 添加字段。
您可以单击 Actions 列中字段的省略号 (...) 图标来执行以下操作:
单击 Edit 以修改配置。
单击 Add Data Type,为字段配置其他数据类型。
单击 Delete 从索引中删除该字段。
要学习;了解有关定义字段映射的更多信息,请参阅索引参考。
对应于
mappings.fields
JSON 设置。可选的
Stored Source Fields
指定要在Atlas Search上存储以进行查询时查找的字段。您可以在Atlas Search上存储所有支持的数据类型的字段。
要了解有关存储字段的更多信息,请参阅在 Atlas Search 索引中定义存储的源字段。
对应于
storedSource
JSON 设置。Optional
Synonyms Mappings
指定要在索引中使用的同义词映射。
您可以使用同义词映射来仅查询使用同一分析器分析的字段。
要学习;了解有关同义词映射的更多信息,请参阅在Atlas Search索引中定义同义词映射。
对应于
synonyms
JSON 设置。可选。
Index Partitions
字段对象超过 2.1 十亿时要使用的分区数。
对应于
numPartitions
JSON 设置。可选。
单击 Save Changes(连接)。
将以下任意设置添加到您的索引:
字段名称说明必要性mappings.fields
如果
mappings.dynamic
是false
,则为必填项。指定要编制索引的字段。要了解更多信息,请参阅定义字段映射。
可选的
storedSource
指定要在Atlas Search上存储以进行查询时查找的字段。您可以在Atlas Search上存储所有支持的数据类型的字段。
要了解有关存储字段的更多信息,请参阅在 Atlas Search 索引中定义存储的源字段。
Optional
synonyms
Optional
numPartitions
字段对象超过 2.1 十亿时要使用的分区数。
可选。
要学习;了解有关这些索引定义设置的更多信息,请参阅索引参考。
单击 Next(连接)。
可选。如果使用 Visual Editor(可视化编辑器),则可以保存或删除索引定义草稿。
单击 Cancel(连接)。
点击 Save Draft 或 Delete Draft。
重要
在有待处理的索引草稿时,您无法创建新索引。
要学习;了解更多信息,请参阅恢复或删除Atlas Search索引草稿。
要使用 创建Atlas Search索引:mongosh
使用 mongosh
连接。
要了解更多信息,请参阅通过 mongosh
进行连接。
创建 Atlas Search 索引。
使用 db.collection.createSearchIndex()
方法。
该命令采用以下语法。如果索引名称, Atlas Search会将索引命名为 default
。要学习;了解更多信息,请参阅索引参考。
db.<collection>.createSearchIndex( "<index-name>", { /* search index definition */ } )
例子
要创建名为 example-index
的索引来动态索引 movies
集合中的字段,请运行以下命令:
db.movies.createSearchIndex( "example-index", { mappings: { dynamic: true } } )
example-index
要使用MongoDB Compass创建Atlas Search索引,请执行以下操作:
通过MongoDB Compass连接到您的Atlas 集群。
打开Compass并连接到您的Atlas 集群。有关详细说明,请参阅通过Compass连接。
创建Atlas Search索引。
单击 Indexes 标签页,然后选择 Search Indexes。
单击 Create Index,打开索引创建对话框。
指定索引的名称。
Atlas Search索引默认名为
default
。如果保留此名称,则该索引将成为任何未在运算符中指定其他 选项的Atlasindex
Search查询的默认搜索索引。如果您要创建多个索引,我们建议您在所有索引之间保持一致的描述性命名约定。指定JSON Atlas Search索引定义。
1 { 2 "analyzer": "<analyzer-for-index>", 3 "searchAnalyzer": "<analyzer-for-query>", 4 "mappings": { 5 "dynamic": <boolean>, 6 "fields": { <field-definition> } 7 }, 8 "numPartitions": <integer>, 9 "analyzers": [ <custom-analyzer> ], 10 "storedSource": <boolean> | { 11 <stored-source-definition> 12 }, 13 "synonyms": [ 14 { 15 <synonym-mapping-definition> 16 } 17 ] 18 } 19 单击 Create Search Index(连接)。
要使用 C 驱动程序创建 Atlas Search 索引,请在应用程序中定义搜索索引并调用 mongoc_collection_command_simple()
方法。
注意
Atlas Search 索引管理方法异步运行。驱动程序方法可以在确认成功运行前返回。要确定搜索索引的当前状态,请使用 $listSearchIndexes
管道阶段运行聚合操作。
将以下代码示例复制到该文件中。
以下示例应用程序指定 createSearchIndexes
命令来定义搜索索引。然后,应用程序将命令和搜索索引信息转换为BSON,并将此信息传递给 mongoc_collection_command_simple()
方法以创建搜索索引。要学习;了解更多信息,请参阅索引参考。
int main (void) { mongoc_client_t *client = NULL; mongoc_collection_t *collection = NULL; mongoc_database_t *database = NULL; bson_error_t error; bson_t cmd = BSON_INITIALIZER; bool ok = true; mongoc_init(); // Connect to your Atlas deployment client = mongoc_client_new("<connectionString>"); if (!client) { fprintf(stderr, "Failed to create a MongoDB client.\n"); ok = false; goto cleanup; } // Access your database and collection database = mongoc_client_get_database(client, "<databaseName>"); collection = mongoc_database_get_collection(database, "<collectionName>"); // Specify the command and the new index const char *cmd_str = BSON_STR({ "createSearchIndexes" : "<collectionName>", "indexes" : [ { "name" : "<indexName>", "definition" : { "analyzer": "<indexAnalyzer>", "searchAnalyzer": "<queryAnalyzer>", "mappings": { "dynamic": <boolean>, "fields": { <fieldDefinition> } }, "numPartitions": <integer>, "analyzers": [ <customAnalyzer> ], "storedSource": <boolean> | { <storedSourceDefinition> }, "synonyms": [ { <synonymMappingDefinition> } ] } } ] }); // Convert your command to BSON if (!bson_init_from_json(&cmd, cmd_str, -1, &error)) { fprintf(stderr, "Failed to parse command: %s\n", error.message); ok = false; goto cleanup; } // Create the Atlas search index by running the command if (!mongoc_collection_command_simple (collection, &cmd, NULL, NULL, &error)) { fprintf(stderr, "Failed to run createSearchIndexes: %s\n", error.message); ok = false; goto cleanup; } printf ("Index created!\n"); cleanup: mongoc_collection_destroy (collection); mongoc_client_destroy (client); mongoc_database_destroy (database); bson_destroy (&cmd); mongoc_cleanup (); return ok ? EXIT_SUCCESS : EXIT_FAILURE; }
以下示例应用程序使用createSearchIndexes
命令定义多个搜索索引。然后,应用程序将命令和搜索索引信息转换为BSON ,并将此信息传递给mongoc_collection_command_simple()
方法以创建搜索索引。要学习;了解更多信息,请参阅索引参考。
int main (void) { mongoc_client_t *client = NULL; mongoc_collection_t *collection = NULL; mongoc_database_t *database = NULL; bson_error_t error; bson_t cmd = BSON_INITIALIZER; bool ok = true; mongoc_init(); // Connect to your Atlas deployment client = mongoc_client_new("<connectionString>"); if (!client) { fprintf(stderr, "Failed to create a MongoDB client.\n"); ok = false; goto cleanup; } // Access your database and collection database = mongoc_client_get_database(client, "<databaseName>"); collection = mongoc_database_get_collection(database, "<collectionName>"); // Specify the command and the new indexes const char *cmd_str = BSON_STR({ "createSearchIndexes" : "<collectionName>", "indexes" : [{ // Add your search index definition fields here "name" : "<firstIndexName>" }, { // Add your search index definition fields here "name" : "<secondIndexName>" }] }); // Convert your command to BSON if (!bson_init_from_json(&cmd, cmd_str, -1, &error)) { fprintf(stderr, "Failed to parse command: %s\n", error.message); ok = false; goto cleanup; } // Create the Atlas search indexes by running the command if (!mongoc_collection_command_simple (collection, &cmd, NULL, NULL, &error)) { fprintf(stderr, "Failed to run createSearchIndexes: %s\n", error.message); ok = false; goto cleanup; } printf ("Indexes created!\n"); cleanup: mongoc_collection_destroy (collection); mongoc_client_destroy (client); mongoc_database_destroy (database); bson_destroy (&cmd); mongoc_cleanup (); return ok ? EXIT_SUCCESS : EXIT_FAILURE; }
要使用 C++ 驱动程序创建 Atlas Search 索引,请在应用程序中定义搜索索引并调用 create_one()
方法。
注意
Atlas Search 索引管理方法异步运行。驱动程序方法可以在确认成功运行前返回。要确定搜索索引的当前状态,请在搜索索引视图实例上调用 list()
方法。
将以下代码示例复制到该文件中。
以下示例应用程序将搜索索引名称和定义传递给 search_index_model()
方法,以便对集合中的字段动态索引。然后,应用程序将搜索索引规范传递给 create_one()
方法以创建搜索索引。要学习;了解更多信息,请参阅索引参考。
using bsoncxx::builder::basic::kvp; using bsoncxx::builder::basic::make_document; using namespace mongocxx; int main() { try { // Connect to your Atlas deployment mongocxx::instance instance{}; mongocxx::uri uri("<connectionString>"); mongocxx::client client(uri); // Access your database and collection auto db = client["<databaseName>"]; auto collection = db["<collectionName>"]; // Create an index model with your index name and definition auto siv = collection.search_indexes(); auto name = "<indexName>"; auto definition = make_document(kvp("mappings", make_document(kvp("dynamic", true)))); auto model = search_index_model(name, definition.view()); // Create the search index siv.create_one(model); std::cout << "Index created!" << std::endl; } catch (const std::exception& e) { std::cout<< "Exception: " << e.what() << std::endl; } return 0; }
您还可以同时创建多个 Atlas Searchh 索引。对于要创建的每个搜索索引,将搜索索引规范传递给 search_index_model()
方法。然后,将每个搜索索引添加到一个向量中,并将该向量传递给 create_many()
方法以创建搜索索引:
using bsoncxx::builder::basic::kvp; using bsoncxx::builder::basic::make_document; using namespace mongocxx; int main() { try { // Connect to your Atlas deployment mongocxx::instance instance{}; mongocxx::uri uri("<connectionString>"); mongocxx::client client(uri); // Access your database and collection auto db = client["<databaseName>"]; auto collection = db["<collectionName>"]; // Create index models and add them to a vector auto siv = collection.search_indexes(); std::vector<search_index_model> models; auto name1 = "<firstIndexName>"; auto definition1 = make_document(/* Add search index definition fields here */); auto model1 = search_index_model(name1, definition1.view()); models.push_back(model1); auto name2 = "<secondIndexName>"; auto definition2 = make_document(/* Add search index definition fields here */); auto model2 = search_index_model(name2, definition2.view()); models.push_back(model2); // Create the search indexes siv.create_many(models); std::cout << "Indexes created!" << std::endl; } catch (const std::exception& e) { std::cout<< "Exception: " << e.what() << std::endl; } return 0; }
使用 .NET/C# 驱动程序创建 Atlas Search 索引:
构建一个定义索引的
BsonDocument
。将
BsonDocument
传递给CreateOne()
或CreateOneAsync()
方法。
将 Program.cs
文件的内容替换为定义索引的 BsonDocument
。
替换以下示例应用程序中的占位符值,该应用程序使用 SearchIndexes.CreateOne
命令定义Atlas Search索引:
值 | 说明 |
---|---|
| Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接。 |
| 要创建索引的数据库。 |
| 要为其创建索引的集合。 |
| 索引名称。如果省略索引名称,Atlas Search 会将索引命名为 |
| 索引的定义。要学习;了解索引定义语法,请参阅索引参考。 |
1 using MongoDB.Bson; 2 using MongoDB.Driver; 3 4 // connect to your Atlas deployment 5 var uri = "<connection-string>"; 6 7 var client = new MongoClient(uri); 8 9 var db = client.GetDatabase("<databaseName>"); 10 var collection = db.GetCollection<BsonDocument>("<collectionName>"); 11 12 // define your Atlas Search index 13 var index = new BsonDocument 14 { 15 { "mappings", new BsonDocument 16 { 17 { "dynamic", true } 18 } 19 } 20 }; 21 22 var result = collection.SearchIndexes.CreateOne(index, "<indexName>"); 23 Console.WriteLine(result);
替换以下示例应用程序中的占位符值,该应用程序使用 SearchIndexes.CreateMany
命令定义Atlas Search索引:
值 | 说明 |
---|---|
| Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接。 |
| 要创建索引的数据库。 |
| 要为其创建索引的集合。 |
| 第一个索引的名称。 |
| 最后一个索引的名称。 |
| 索引的定义。要学习;了解索引定义语法,请参阅索引参考。 |
1 using MongoDB.Bson; 2 using MongoDB.Driver; 3 4 // connect to your Atlas deployment 5 var uri = "<connection-string>"; 6 7 var client = new MongoClient(uri); 8 9 var db = client.GetDatabase("<databaseName>"); 10 var collection = db.GetCollection<BsonDocument>("<collectionName>"); 11 12 // define your Atlas Search indexes 13 var indexes = new List<CreateSearchIndexModel> 14 { 15 new CreateSearchIndexModel( 16 "<firstIndexName>", 17 new BsonDocument 18 { 19 <IndexDefinition>// search index definition fields 20 } 21 ), 22 ... 23 new CreateSearchIndexModel( 24 "<lastIndexName>", 25 new BsonDocument 26 { 27 <IndexDefinition> // search index definition fields 28 } 29 ) 30 }; 31 32 var result = collection.SearchIndexes.CreateMany(indexes);
要使用Java驱动程序创建Atlas Search索引,请构造定义搜索索引的文档,然后将该文档传递给 createSearchIndex()
或 createSearchIndexes()
方法。
注意
Atlas Search 索引管理方法异步运行。驱动程序方法可以在确认成功运行前返回。要确定索引的当前状态,请调用 listSearchIndexes()
方法。
将以下代码示例复制到该文件中。
以下示例应用程序定义一个搜索索引以动态索引集合中的字段,然后运行 createSearchIndex()
方法以创建该索引。要学习;了解更多信息,请参阅索引参考。
import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; public class CreateIndex { public static void main(String[] args) { // connect to your Atlas cluster String uri = "<connection-string>"; try (MongoClient mongoClient = MongoClients.create(uri)) { // set namespace MongoDatabase database = mongoClient.getDatabase("<databaseName>"); MongoCollection<Document> collection = database.getCollection("<collectionName>"); Document index = new Document("mappings", new Document("dynamic", true)); collection.createSearchIndex("<index-name>", index); } } }
您可以使用以下示例应用程序一次创建多个 Atlas Search 索引。为此,请为要创建的每个搜索索引构造一个文档,然后将文档作为数组传递给 createSearchIndexes()
方法:
import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.SearchIndexModel; import org.bson.Document; import java.util.Arrays; public class CreateIndex { public static void main(String[] args) { // connect to your Atlas cluster String uri = "<connection-string>"; try (MongoClient mongoClient = MongoClients.create(uri)) { // set namespace MongoDatabase database = mongoClient.getDatabase("<databaseName>"); MongoCollection<Document> collection = database.getCollection("<collectionName>"); SearchIndexModel indexOne = new SearchIndexModel("<first-index-name>", new Document( // search index definition fields )); SearchIndexModel indexTwo = new SearchIndexModel("<second-index-name>", new Document( // search index definition fields )); collection.createSearchIndexes(Arrays.asList(indexOne, indexTwo)); } } }
通过节点驱动程序创建 Atlas Search 索引:
从您的应用程序定义搜索索引。
运行
createSearchIndex
或createSearchIndexes
辅助方法。
定义搜索索引。
替换以下名为 create-index.js
的示例应用程序中的占位符值,该应用程序使用 createSearchIndex
命令定义Atlas Search索引:
值 | 说明 |
---|---|
| Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接。 |
| 要创建索引的数据库。 |
| 要为其创建索引的集合。 |
| 索引的名称。 如果省略索引名称,Atlas Search 会将索引命名为 |
| 索引的定义。要学习;了解索引定义语法,请参阅索引参考。 |
import { MongoClient } from "mongodb"; // connect to your Atlas deployment const uri = "<connectionString>"; const client = new MongoClient(uri); async function run() { try { const database = client.db("<databaseName>"); const collection = database.collection("<collectionName>"); // define your Atlas Search index const index = { name: "<indexName>", definition: { /* search index definition fields */ <indexDefinition> } } // run the helper method const result = await collection.createSearchIndex(index); console.log(result); } finally { await client.close(); } } run().catch(console.dir);
值 | 说明 |
---|---|
| Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接。 |
| 要创建索引的数据库。 |
| 要为其创建索引的集合。 |
| 索引的名称。 如果省略索引名称,Atlas Search 会将索引命名为 |
| 索引的定义。要学习;了解索引定义语法,请参阅索引参考。 |
替换以下名为 create-index.js
的示例应用程序中的占位符值,该应用程序使用 createSearchIndexes
命令定义Atlas Search索引:
import { MongoClient } from "mongodb"; // connect to your Atlas deployment const uri = "<connection-string>"; const client = new MongoClient(uri); async function run() { try { const database = client.db("<databaseName>"); const collection = database.collection("<collectionName>"); // define an array of Atlas Search indexes const indexes = [ { name: "<first-index-name>", definition: { /* search index definition fields */ } }, ... { name: "<last-index-name>", definition: { /* search index definition fields */ } } ] // run the helper method const result = await collection.createSearchIndexes(indexes); console.log(result); } finally { await client.close(); } } run().catch(console.dir);
要使用 Python 驱动程序来创建 Atlas Search 索引,请在应用程序中定义搜索索引并调用 create_search_index()
方法。
注意
Atlas Search 索引管理方法异步运行。驱动程序方法可以在确认成功运行前返回。要确定搜索索引的当前状态,请对集合调用 list_search_indexes()
方法。
例子
将以下代码示例复制到该文件中。
以下示例应用程序定义了一个搜索索引,以便对集合中的字段进行动态索引。然后,应用程序对集合调用 create_search_index()
方法以创建搜索索引。要学习;了解更多信息,请参阅索引参考。
from pymongo.mongo_client import MongoClient from pymongo.operations import SearchIndexModel def create_index(): # Connect to your Atlas deployment uri = "<connectionString>" client = MongoClient(uri) # Access your database and collection database = client["<databaseName>"] collection = database["<collectionName>"] # Create your index model, then create the search index search_index_model = SearchIndexModel( definition={ "mappings": { "dynamic": True }, }, name="<indexName>", ) result = collection.create_search_index(model=search_index_model) print(result)
您还可以同时创建多个 Atlas Searchh 索引。在您的应用程序中,定义搜索索引数组。然后,将该数组作为参数传递给 create_search_indexes()
方法:
from pymongo.mongo_client import MongoClient from pymongo.operations import SearchIndexModel def create_indexes(): # Connect to your Atlas deployment uri = "<connectionString>" client = MongoClient(uri) # Access your database and collection database = client["<databaseName>"] collection = database["<collectionName>"] # Create your index models and add them to an array first_model = SearchIndexModel( definition={ # Add search index definition fields here }, name="<firstIndexName>", ) second_model = SearchIndexModel( definition={ # Add search index definition fields here }, name="<secondIndexName>", ) idx_models = [first_model, second_model] # Create the search indexes result = collection.create_search_indexes(models=idx_models) print(result)
创建Atlas Search索引时, Atlas Search页面会显示有关Atlas Search索引的信息。 Status 列显示集群主节点 (primary node in the replica set)节点上索引的当前状态。要学习;了解更多信息,请参阅查看索引状态。
警告
如果您对已具有 Atlas Search 索引的集合进行分片,当该集合开始出现在分片上时,您可能会遇到短暂的查询停机时间。此外,如果您为包含 Atlas Search 索引的已分片集合添加分片,针对该集合的搜索查询将失败,直到添加的分片完成初始同步过程为止。要了解更多信息,请参阅初始同步进程。
查看Atlas Search索引
➤ 使用选择语言下拉菜单设立本节中过程的语言。
要使用Atlas Search API检索Atlas Search索引,检索以下操作:
发送 GET
请求。
使用您想要检索的 Atlas Search 索引的唯一 ID 或名称向 search/indexes/
端点发送一个 GET
请求。
curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \ --header "Accept: application/json" \ --include \ --request GET "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{indexId}"
要进一步了解任一端点的语法和参数,请参阅按名称获取一个和按 ID 获取一个。
要检索集合的所有 Atlas Search 索引,请执行以下操作:
发送 GET
请求。
向 search/indexes/
端点发送 GET
请求,其中包含要检索其索引的集合的名称。
curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \ --header "Accept: application/json" \ --include \ --request GET "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{databaseName}/{collectionName}"
要检索集群的所有 Atlas Search 索引:
发送 GET
请求。
要检索集群的索引,请将 GET
请求发送到 search/indexes/
端点,该请求包含要检索其索引的集群的名称。
curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \ --header "Accept: application/json" \ --include \ --request GET "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes"
检索云部署的 Atlas Search 索引
要使用 Atlas CLI 列出集群的所有搜索索引,请运行以下命令:
atlas clusters search indexes list [options]
要使用 Atlas CLI 返回您指定的搜索索引的详细信息,请运行以下命令:
atlas clusters search indexes describe <indexId> [options]
要了解有关上述命令的语法和参数的更多信息,请参阅Atlas CLI Atlas集群Atlas Search 索引列表 和Atlas 集群Atlas Search 索引描述 的 文档。
检索本地部署的 Atlas Search 索引
要使用 Atlas CLI 描述指定部署的指定搜索索引,请运行以下命令:
atlas deployments search indexes describe [indexId] [options]
要使用 Atlas CLI 列出指定部署的所有搜索索引,请运行以下命令:
atlas deployments search indexes list [options]
要进一步了解上一个命令的语法和参数,请参阅 Atlas CLI 文档 Atlas 部署搜索索引说明和 Atlas 部署搜索索引列表。
要查看Atlas 用户界面 Atlas Search 页面,请执行以下操作:
Atlas Search页面包含一个表,该表在以下列中描述了项目中每个现有的Atlas Search索引。
列 | 说明 |
---|---|
Database | 包含该集合的数据库名称。 |
Collection | 索引集合的名称。 |
Index Name | 索引名称。 |
Status | 集群主节点 (primary node in the replica set)节点上的索引状态。要学习;了解更多信息,请参阅Atlas Search索引状态。 |
Queryable | 用于标识集合是否可使用索引进行查询的图标。值可以是以下图标之一:
|
Type | 索引的类型。值可以是以下类型的索引之一:
|
Index Fields | |
Documents | 在集群的主节点或搜索节点上构建索引期间和之后,索引文档占集合中文档总数的近似数量和百分比。 |
Size | 索引的大小。 |
Required Memory | 运行查询所需的大致内存量。仅适用于Atlas Vector Search索引。 |
Actions |
默认下, Atlas首先按数据库名称,然后按集合名称对索引进行排序。要按多列排序,请按 Shift
并按照要对索引列表进行多重排序的顺序单击列名称。
从该表中,您可以转到以下部分,了解有关每个索引的更多详细信息:
Index Overview
要从 Atlas Search 页面转到 Index Overview 页面,请在 Index Name 列中单击要查看的索引名称。对于每个索引,Index Overview 页面显示索引的命名空间以及索引定义中指定的以下配置:
要通过 mongosh
检索 Atlas Search 索引,请使用 db.collection.getSearchIndexes()
方法。
该命令采用以下语法。如果省略索引名称,Atlas Search 将返回集合上的所有索引。
db.<collection>.getSearchIndexes("<index-name>")
例子
以下命令从 movies
集合中检索名为 default
的搜索索引。结果应类似于示例输出:
db.movies.getSearchIndexes("default")
[ { id: '648b4ad4d697b73bf9d2e5e0', name: 'default', status: 'READY', queryable: true, latestDefinition: { mappings: { dynamic: true } } } ]
通过MongoDB Compass连接到您的Atlas 集群。
打开Compass并连接到您的Atlas 集群。有关详细说明,请参阅通过Compass连接。
Indexes单击 标签页,然后单击Search Indexes 。
页面显示以下内容:
列名称 | 说明 |
---|---|
Name and Fields | 索引的名称和索引字段的名称。 |
Type | 索引类型。值可以是 |
Status | 索引的状态。要学习;了解更多信息,请参阅查看索引状态。 |
操作 | 将鼠标悬停在索引上时可以对索引执行的操作。您可以执行以下操作:
|
要使用 C 驱动程序检索 Atlas Search 索引,请使用 mongoc_collection_aggregate()
方法创建一个包含 $listSearchIndexes
阶段的聚合管道。
例子
将以下代码示例复制到该文件中。
以下示例应用程序指定聚合管道中的 $listSearchIndexes
阶段。然后,应用程序将管道和目标集合传递给 mongoc_collection_aggregate()
方法。此方法返回一个游标,代码可以从中访问并打印每个 Atlas Search 索引:
int main (void) { mongoc_client_t *client = NULL; mongoc_collection_t *collection = NULL; mongoc_database_t *database = NULL; bson_error_t error; bson_t cmd = BSON_INITIALIZER; bool ok = true; bson_t pipeline = BSON_INITIALIZER; mongoc_cursor_t *cursor = NULL; mongoc_init(); // Connect to your Atlas deployment client = mongoc_client_new("<connectionString>"); if (!client) { fprintf(stderr, "Failed to create a MongoDB client.\n"); ok = false; goto cleanup; } // Access your database and collection database = mongoc_client_get_database(client, "<databaseName>"); collection = mongoc_database_get_collection(database, "<collectionName>"); // Create an aggregation pipeline with the $listSearchIndexes stage const char *pipeline_str = BSON_STR ({"pipeline" : [ {"$listSearchIndexes" : {}} ]}); // Convert your aggregation pipeline to BSON if (!bson_init_from_json(&pipeline, pipeline_str, -1, &error)) { fprintf(stderr, "Failed to parse command: %s\n", error.message); ok = false; goto cleanup; } // Run the aggregation operation and iterate through the indexes returned cursor = mongoc_collection_aggregate (collection, MONGOC_QUERY_NONE, &pipeline, NULL, NULL); const bson_t *got; char *str; while (mongoc_cursor_next (cursor, &got)) { str = bson_as_canonical_extended_json (got, NULL); printf ("%s\n", str); bson_free (str); } if (mongoc_cursor_error (cursor, &error)) { fprintf (stderr, "Failed to iterate all documents: %s\n", error.message); ok = false; goto cleanup; } cleanup: mongoc_cursor_destroy(cursor); mongoc_collection_destroy(collection); mongoc_database_destroy(database); mongoc_client_destroy(client); bson_destroy(&pipeline); bson_destroy(&cmd); mongoc_cleanup (); return ok ? EXIT_SUCCESS : EXIT_FAILURE; }
指定以下值并保存文件。
Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接。
您要检索索引的数据库和集合。
要使用 C++ 驱动程序检索您的 Atlas 搜索索引,请在搜索索引视图上调用 list()
方法。
例子
将以下代码示例复制到该文件中。
以下示例应用程序在目标集合上使用 search_indexes()
方法来实例化搜索索引视图。然后,应用程序会调用视图上的 list()
方法。此方法返回一个游标,代码从该游标访问并打印每个 Atlas Search 索引。
using namespace mongocxx; int main() { mongocxx::instance instance{}; try { // Connect to your Atlas deployment mongocxx::uri uri("<connectionString>"); mongocxx::client client(uri); // Access your database and collection auto db = client["<databaseName>"]; auto collection = db["<collectionName>"]; // Access and print the indexes in your collection auto siv = collection.search_indexes(); auto cursor = siv.list(); for (auto&& doc : cursor) { std::cout << bsoncxx::to_json(doc) << std::endl; }; } catch (const std::exception& e) { std::cout<< "Exception: " << e.what() << std::endl; } return 0; }
指定以下值并保存文件。
Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接。
您要检索索引的数据库和集合。
要使用 .NET/C# 驱动程序检索 Atlas Search 索引,请使用 List()
或 ListAsync()
方法。
例子
以下示例应用程序返回集合上的索引。指定以下值:
Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接。
包含要检索的搜索索引的数据库和集合。
注意
List()
方法返回的是游标,而不是索引本身。要访问索引,请使用游标范例,例如 MoveNext()
方法。
using MongoDB.Bson; using MongoDB.Driver; // connect to your Atlas deployment var uri = "<connection-string>"; var client = new MongoClient(uri); var db = client.GetDatabase("<databaseName>"); var collection = db.GetCollection<BsonDocument>("<collectionName>"); // list your Atlas Search indexes var result = collection.SearchIndexes.List().ToList(); foreach (var index in result) { Console.WriteLine(index); }
若要运行示例应用程序,请创建一个名为 csharp-list-indexes
的新 .NET 控制台项目,并将上一个代码示例复制到 Program.cs
文件中。然后,使用以下命令运行项目:
dotnet run csharp-list-indexes.csproj
<indexes for this collection>
要使用 Java 驱动程序检索集合上的 Atlas 搜索索引,请使用 listSearchIndexes()
方法。您必须有 Java 驱动程序 v 4.11.0 或更高版本。
将以下代码示例复制到该文件中。
以下示例应用程序检索给定集合上的所有 Atlas Search 索引。
1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoCursor; 5 import com.mongodb.client.MongoDatabase; 6 import org.bson.Document; 7 public class ViewIndex { 8 public static void main(String[] args) { 9 // connect to your Atlas cluster 10 String uri = "<connection-string>"; 11 try (MongoClient mongoClient = MongoClients.create(uri)) { 12 // set namespace 13 MongoDatabase database = mongoClient.getDatabase("<database-name>"); 14 MongoCollection<Document> collection = database.getCollection("<collection-name>"); 15 // retrieve indexes 16 try (MongoCursor<Document> resultsCursor = collection.listSearchIndexes().iterator()) { 17 while (resultsCursor.hasNext()) { 18 System.out.println(resultsCursor.next()); 19 } 20 } 21 } 22 } 23 }
替换以下值,然后保存文件。
<connection-string>
- Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接。<database-name>
— 包含该集合的数据库的名称。<collection-name>
— 要检索其索引的集合的名称。
另请参阅:
要通过节点驱动程序检索 Atlas Search 索引,请使用listSearchIndexes
辅助方法。
例子
您可以使用以下名为 list-indexes.js
的示例应用程序返回集合上的索引。指定以下值:
Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接。
包含要检索的搜索索引的数据库和集合。
如果要检索特定索引,则为索引名称。 要返回集合上的所有索引,请省略此值。
注意
listSearchIndexes
命令会返回一个游标。 因此,它不会立即返回与该命令匹配的索引。 要访问结果,请使用游标范例,例如toArray()
方法。 要了解详情,请参阅从游标访问数据。
import { MongoClient } from "mongodb"; // connect to your Atlas deployment const uri = "<connection-string>"; const client = new MongoClient(uri); async function run() { try { const database = client.db("<databaseName>"); const collection = database.collection("<collectionName>"); // run the helper method const result = await collection.listSearchIndexes("<index-name>").toArray(); console.log(result); } finally { await client.close(); } } run().catch(console.dir);
要运行样本应用程序,请使用以下命令。 结果应类似于示例输出:
node list-indexes.js
[ { id: '648b4ad4d697b73bf9d2e5e0', name: 'default', status: 'READY', queryable: true, latestDefinition: { mappings: { dynamic: true } } }, { id: '648b4ad4d697b73bf9d2e5e1', name: 'example-index', status: 'PENDING', queryable: false, latestDefinition: { mappings: { dynamic: false, fields: { text: { type: 'string' } } } } } ]
要使用 Python 驱动程序 检索 Atlas Search 索引,请在集合上调用 list_search_indexes()
方法。
例子
将以下代码示例复制到该文件中。
下面的示例应用程序在一个集合上调用了 list_search_indexes()
方法。此方法返回一个游标,代码可以从中访问并打印每个 Atlas Search 索引:
from pymongo.mongo_client import MongoClient def view_index(): # Connect to your Atlas deployment uri = "<connectionString>" client = MongoClient(uri) # Access your database and collection database = client["<databaseName>"] collection = database["<collectionName>"] # Get a list of the collection's search indexes and print them cursor = collection.list_search_indexes() for index in cursor: print(index)
指定以下值并保存文件。
Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接。
您要检索索引的数据库和集合。
恢复或删除 Atlas Search 索引草稿
要恢复或删除在Atlas用户界面中保存为草稿的索引定义:
重要
在有待处理的索引草稿时,您无法创建新索引。
编辑 Atlas Search 索引
您可以更改现有 Atlas Search 索引的索引定义。您无法对索引进行重命名;如果需要更改索引名称,则必须创建新索引并删除旧索引。
您可以在Atlas用户界面中编辑Atlas Search索引,或者使用您的首选语言使用 mongosh
、 Atlas CLI、 API或支持的MongoDB驱动程序以编程方式编辑 Atlas Search 索引。
➤ 使用选择语言下拉菜单设立本节中过程的语言。
要通过 API 编辑 Atlas Search 索引,请执行以下操作:
发送 PATCH
请求。
向 search/indexes/
端点发送 PATCH
请求,其中包含要修改的 Atlas 搜索索引的唯一 ID 或名称。
curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \ --header "Accept: application/json" \ --header "Content-Type: application/json" \ --include \ --request PATCH "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{indexId}" \ --data ' { "definition": { "analyzer": "lucene.<analyzer>", "analyzers": [ { "charFilters": [ ... ], "name": "string", "tokenFilters": [ ... ], "tokenizer": { ... } } ], "mappings": { "dynamic": true | false, "fields": { "property1": {}, ... } }, "searchAnalyzer": "<analyzer-name>", "storedSource": { "include | exclude": [...] }, "synonyms": [ { <synonym-mapping-definition> } } ] } }'
要了解有关任一端点的语法和参数的更多信息,请参阅按名称更新一个和按 ID 更新一个。
要使用 Atlas CLI 更新集群的搜索索引,请运行以下命令:
atlas clusters search indexes update <indexId> [options]
要了解有关命令语法和参数的更多信息,请参阅 Atlas CLI 文档中的 Atlas 集群搜索索引更新。
检查当前配置设置,并根据需要进行编辑。
检查以下索引配置设置:
可视化编辑器字段 | 说明 | 必要性 |
---|---|---|
Index Analyzer | Optional | |
Search Analyzer | Optional | |
Dynamic Mapping | 指定字段的动态或静态映射。 默认下,启用动态映射。要禁用动态映射,请将 要学习;了解有关动态和静态映射的更多信息,请参阅定义字段映射。 对应于 | 必需 |
检查以下高级配置设置:
字段名称 | 说明 | 必要性 |
---|---|---|
Field Mappings | 如果 Index Configurations 部分中的 Dynamic Mapping 处于禁用状态,则为必填项。 指定要索引的字段:
要学习;了解有关定义字段映射的更多信息,请参阅索引参考。 对应于 | 可选的 |
Stored Source Fields | 指定要在Atlas Search上存储以进行查询时查找的字段。您可以在Atlas Search上存储所有支持的数据类型的字段。 要了解有关存储字段的更多信息,请参阅在 Atlas Search 索引中定义存储的源字段。 对应于 | Optional |
Synonyms Mappings | 指定要在索引中使用的同义词映射。 您可以使用同义词映射来仅查询使用同一分析器分析的字段。 要学习;了解有关同义词映射的更多信息,请参阅在Atlas Search索引中定义同义词映射。 对应于 | 可选。 |
Index Partitions | 字段对象超过 2.1 十亿时要使用的分区数。 对应于 | 可选。 |
检查以下索引配置设置:
字段名称 | 说明 | 必要性 |
---|---|---|
| Optional | |
| Optional | |
| 指定字段的动态或静态映射。要禁用动态映射,请将 | 必需 |
检查以下高级配置设置:
字段名称 | 说明 | 必要性 |
---|---|---|
| 如果 指定要编制索引的字段。要了解更多信息,请参阅定义字段映射。 | 可选的 |
| 指定要在Atlas Search上存储以进行查询时查找的字段。您可以在Atlas Search上存储所有支持的数据类型的字段。 要了解有关存储字段的更多信息,请参阅在 Atlas Search 索引中定义存储的源字段。 | Optional |
| Optional | |
| 字段对象超过 2.1 十亿时要使用的分区数。 | 可选。 |
要学习;了解有关这些索引定义设置的更多信息,请参阅索引参考。
要通过mongosh
编辑 Atlas Search 索引,请使用db.collection.updateSearchIndex()
方法。
该命令采用以下语法。指定要编辑的索引名称,并定义新的索引定义。此定义将替换索引的现有定义。要学习;了解更多信息,请参阅索引参考。
db.<collection>.updateSearchIndex( "<index-name>", /* updated search index definition */ )
例子
以下命令会更新collection中名为default
movies
的搜索索引以使用 静态映射:
db.movies.updateSearchIndex( "default", { "mappings": { "dynamic": false, "fields": { "<field-name>": { "type": "<field-type>" } } } )
注意
db.collection.updateSearchIndex()
命令不返回输出。您可以使用Atlas用户界面查看索引状态。
要使用C 驱动程序编辑 Atlas Search 索引,请在应用程序中指定更新的索引信息并调用 mongoc_collection_command_simple()
方法。
例子
将以下代码示例复制到该文件中。
以下示例应用程序指定 updateSearchIndex
命令、更新的索引定义和现有索引名称。然后,应用程序将命令和更新的索引信息转换为 BSON ,并将此信息传递给 mongoc_collection_command_simple()
方法来编辑搜索索引。
int main (void) { mongoc_client_t *client = NULL; mongoc_collection_t *collection = NULL; mongoc_database_t *database = NULL; bson_error_t error; bson_t cmd = BSON_INITIALIZER; bool ok = true; mongoc_init(); // Connect to your Atlas deployment client = mongoc_client_new("<connectionString>"); if (!client) { fprintf(stderr, "Failed to create a MongoDB client.\n"); ok = false; goto cleanup; } // Access your database and collection database = mongoc_client_get_database(client, "<databaseName>"); collection = mongoc_database_get_collection(database, "<collectionName>"); // Specify the command and the updated index definition const char *cmd_str = BSON_STR({ "updateSearchIndex" : "<collectionName>", "definition" : {"mappings" : {"dynamic" : true}}, "name" : "<indexName>" }); // Convert your command to BSON if (!bson_init_from_json(&cmd, cmd_str, -1, &error)) { fprintf(stderr, "Failed to parse command: %s\n", error.message); ok = false; goto cleanup; } // Update the Atlas search index by running the command if (!mongoc_collection_command_simple (collection, &cmd, NULL, NULL, &error)) { fprintf(stderr, "Failed to run updateSearchIndex: %s\n", error.message); ok = false; goto cleanup; } printf ("Index updated!\n"); cleanup: mongoc_collection_destroy (collection); mongoc_database_destroy (database); mongoc_client_destroy (client); bson_destroy (&cmd); mongoc_cleanup (); return ok ? EXIT_SUCCESS : EXIT_FAILURE; }
要使用 C++ 驱动程序编辑 Atlas Search 索引,请在搜索索引视图上调用 update_one()
方法。
例子
将以下代码示例复制到该文件中。
以下示例应用程序实例化搜索索引视图并指定新的 Atlas Search 索引定义。然后,应用程序将此定义和现有索引名称传递给 update_one()
方法,该方法将更新现有索引以反映新的定义文档。
using namespace mongocxx; using bsoncxx::builder::basic::make_document; int main() { mongocxx::instance instance{}; try { // Connect to your Atlas deployment mongocxx::uri uri("<connectionString>"); mongocxx::client client(uri); // Access your database and collection auto db = client["<databaseName>"]; auto collection = db["<collectionName>"]; // Access the indexes in your collection auto siv = collection.search_indexes(); // Specify a new definiton and update your search index auto newDefinition = make_document(kvp("mappings", make_document(kvp("dynamic", true)))); siv.update_one("<indexName>", newDefinition.view()); } catch (const std::exception& e) { std::cout<< "Exception: " << e.what() << std::endl; } return 0; }
要使用 .NET/C# 驱动程序编辑 Atlas Search 索引,请使用 Update()
或 UpdateAsync()
方法。
例子
以下示例应用程序更新了现有索引定义。指定以下值:
Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接。
在其中创建搜索索引的数据库和集合。
新的索引定义将替换现有定义。在示例中,您更新索引以使用静态映射。您可以更改此定义以满足您的特定索引需求。要学习;了解更多信息,请参阅索引参考。
要更新的索引的名称。
using MongoDB.Bson; using MongoDB.Driver; // connect to your Atlas deployment var uri = "<connection-string>"; var client = new MongoClient(uri); var db = client.GetDatabase("<databaseName>"); var collection = db.GetCollection<BsonDocument>("<collectionName>"); // define your Atlas Search index var index = new BsonDocument { // updated search index definition { "mappings", new BsonDocument { { "dynamic", false }, { "fields", new BsonDocument { { "<field-name>", new BsonDocument { { "type", "<field-type>" } } } } } } } }; collection.SearchIndexes.Update("<index-name>", index);
若要运行示例应用程序,请创建一个名为 csharp-update-index
的新 .NET 控制台项目,并将上一个代码示例复制到 Program.cs
文件中。然后,使用以下命令运行项目:
dotnet run csharp-update-index.csproj
注意
Update()
方法不返回输出。您可以使用Atlas用户界面查看索引状态。
要使用 Java 驱动程序编辑集合上的 Atlas Search 索引,请构建一个修改搜索索引设置的文档,然后将该文档传递给 updateSearchIndex()
方法。您必须有 Java 驱动程序 v 4.11.0 或更高版本。
将以下代码示例复制到该文件中。
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 EditIndex { 8 public static void main(String[] args) { 9 // connect to your Atlas cluster 10 String uri = "<connection-string>"; 11 12 try (MongoClient mongoClient = MongoClients.create(uri)) { 13 // set namespace 14 MongoDatabase database = mongoClient.getDatabase("<document-name>"); 15 MongoCollection<Document> collection = database.getCollection("<collection-name>"); 16 // define field mappings 17 Document index = new Document("analyzer", "<analyzer-name>").append( 18 "mappings", new Document("dynamic", <true|false>) 19 .append("fields", new Document("<field-name>", 20 new Document("type", "<field-type>")))); 21 // run the updateSearchIndex() method 22 collection.updateSearchIndex("<index-name>", index); 23 } 24 } 25 }
替换代码中的以下值,然后保存该文件。
<connection-string>
- Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接。注意
在连接字符串中,不要包含 writeConcern 设置。
<database-name>
— 包含该集合的数据库的名称。<collection-name>
— 要检索其索引的集合的名称。<analyzer-name>
- 分析器的名称。dynamic
- 指示是否自动索引字段的标志。<field-name>
— 要索引的字段的名称。<field-type>
- 字段数据类型。<index-name>
- 索引名称。
编译并运行文件。
javac EditIndex.java java EditIndex
updateSearchIndex()
方法异步运行。使用 listSearchIndexes()
方法确定更改是否已应用于索引。要学习;了解有关检索Atlas Search索引的更多信息,请参阅查看Atlas Search索引。
另请参阅:
要通过节点驱动程序编辑 Atlas Search 索引,请使用 updateSearchIndex
辅助方法。
例子
您可以使用以下名为 update-index.js
的示例应用程序更新现有索引定义。指定以下值:
Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接。
在其中创建搜索索引的数据库和集合。
新的索引定义将替换现有定义。在示例中,您更新索引以使用静态映射。您可以更改此定义以满足您的特定索引需求。要学习;了解更多信息,请参阅索引参考。
要更新的索引的名称。
import { MongoClient } from "mongodb"; // connect to your Atlas deployment const uri = "<connection-string>"; const client = new MongoClient(uri); async function run() { try { const database = client.db("<databaseName>"); const collection = database.collection("<collectionName>"); // define your Atlas Search index const index = { /* updated search index definition */ "mappings": { "dynamic": false, "fields": { "<field-name>": { "type": "<field-type>" } } } } // run the helper method await collection.updateSearchIndex("<index-name>", index); } finally { await client.close(); } } run().catch(console.dir);
要运行样本应用程序,请使用以下命令:
node update-index.js
注意
updateSearchIndex
方法不返回输出。您可以使用Atlas用户界面查看索引状态。
要使用 Python 驱动程序更新您的 Atlas 搜索索引,请在您的集合中调用 update_search_index()
方法。
例子
将以下代码示例复制到该文件中。
以下示例应用程序指定了新的 Atlas Search 索引定义。然后,应用程序将此定义和现有索引名称传递给 update_search_index()
方法,该方法更新现有索引,以反映新的定义文档。
from pymongo.mongo_client import MongoClient def edit_index(): # Connect to your Atlas deployment uri = "<connectionString>" client = MongoClient(uri) # Access your database and collection database = client["<databaseName>"] collection = database["<collectionName>"] # Specify a new index definition definition = { "mappings": { "dynamic": True }, } # Update your search index collection.update_search_index("<indexName>", definition)
注意
在构建更新后的索引时,不同节点的更新速度可能不同。在此期间,您可能会遇到混合查询结果,反映了新的索引定义和以前的索引定义。您可以在索引状态详细信息页面查看正在为查询提供服务的索引。
更新现有索引
某些 Atlas Search 功能要求您更新索引。 要更新索引,可以执行以下操作之一:
使用编辑Atlas Search索引中的步骤编辑索引定义。
请执行以下步骤,选择从Atlas用户界面进行索引更新:
重要
更新 Atlas Search 索引的过程需要时间和资源。要成功完成索引更新,请分配等于当前索引磁盘空间 125% 的可用磁盘空间。
删除 Atlas Search 索引
您可以在Atlas用户界面中删除Atlas Search索引,也可以使用 mongosh
、 Atlas CLI、 API或您首选语言支持的MongoDB驱动程序以编程方式删除 Atlas Search 索引。
➤ 使用选择语言下拉菜单设立本节中过程的语言。
要通过 API 删除 Atlas Search 索引,请执行以下操作:
发送 DELETE
请求。
使用您要删除的 Atlas Search 索引的唯一 ID 或名称发送 DELETE
请求到 search/indexes/
端点。
curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \ --header "Accept: application/json" \ --include \ --request DELETE "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{indexId}"
删除云部署的 Atlas Search 索引
要使用 Atlas CLI 从集群中删除搜索索引,请运行以下命令:
atlas clusters search indexes delete <indexId> [options]
要了解有关命令语法和参数的更多信息,请参阅 Atlas CLI 文档中的 Atlas 集群搜索索引删除部分。
删除本地部署的 Atlas Search 索引
要使用 Atlas CLI 删除指定部署的指定搜索索引,请运行以下命令:
atlas deployments search indexes delete <indexId> [options]
要了解有关命令语法和参数的更多信息,请参阅Atlas CLI AtlasAtlas Search部署 索引删除 的 文档。
要通过 mongosh
删除 Atlas Search 索引,请使用 db.collection.dropSearchIndex()
方法。
该命令具有以下语法:
db.<collection>.dropSearchIndex("<index-name>")
例子
以下命令从 movies
集合中删除名为 default
的搜索索引:
db.movies.dropSearchIndex("default")
注意
db.collection.dropSearchIndex()
命令不返回输出。您可以使用Atlas用户界面查看索引状态。
要使用 C 驱动程序删除您的 Atlas Search 索引,请将您的集合和 drop 命令传递给 mongoc_collection_command_simple()
方法。
例子
将以下代码示例复制到该文件中。
以下示例应用程序指定 dropSearchIndex
命令和现有索引名称。然后,应用程序将命令和索引信息转换为 BSON,并将此信息传递给 mongoc_collection_command_simple()
方法以删除搜索索引。
int main (void) { mongoc_client_t *client = NULL; mongoc_collection_t *collection = NULL; mongoc_database_t *database = NULL; bson_error_t error; bson_t cmd = BSON_INITIALIZER; bool ok = true; mongoc_init(); // Connect to your Atlas deployment client = mongoc_client_new("<connectionString>"); if (!client) { fprintf(stderr, "Failed to create a MongoDB client.\n"); ok = false; goto cleanup; } // Access your database and collection database = mongoc_client_get_database(client, "<databaseName>"); collection = mongoc_database_get_collection(database, "<collectionName>"); // Specify the command and the index name const char *cmd_str = BSON_STR ({"dropSearchIndex" : "<collectionName>", "name" : "<indexName>"}); // Convert your command to BSON if (!bson_init_from_json(&cmd, cmd_str, -1, &error)) { fprintf(stderr, "Failed to parse command: %s\n", error.message); ok = false; goto cleanup; } // Run the command to drop the search index if (!mongoc_collection_command_simple (collection, &cmd, NULL, NULL, &error)) { fprintf(stderr, "Failed to run dropSearchIndex: %s\n", error.message); ok = false; goto cleanup; } printf ("Index dropped!\n"); cleanup: mongoc_collection_destroy(collection); mongoc_database_destroy(database); mongoc_client_destroy(client); bson_destroy(&cmd); mongoc_cleanup (); return ok ? EXIT_SUCCESS : EXIT_FAILURE; }
指定以下值并保存文件。
Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接。
您要删除索引的数据库和集合。
要删除的索引的名称。
要使用 C++ 驱动程序删除 Atlas Search 索引,请在搜索索引视图上调用 drop_one()
方法。
例子
将以下代码示例复制到该文件中。
以下示例应用程序在目标集合上使用 search_indexes()
方法来实例化搜索索引视图。然后,应用程序在视图上调用 drop_one()
方法,并将 Atlas Search 索引名称作为参数传递给该索引,以删除该索引。
using namespace mongocxx; int main() { mongocxx::instance instance{}; try { // Connect to your Atlas deployment mongocxx::uri uri("<connectionString>"); mongocxx::client client(uri); // Access your database and collection auto db = client["<databaseName>"]; auto collection = db["<collectionName>"]; // Access the indexes in your collection auto siv = collection.search_indexes(); // Delete your search index auto name = "<indexName>"; siv.drop_one(name); } catch (const std::exception& e) { std::cout<< "Exception: " << e.what() << std::endl; } return 0; }
指定以下值并保存文件。
Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接。
您要检索索引的数据库和集合。
要删除的索引的名称。
要使用 .NET/C# 驱动程序删除 Atlas Search 索引,请使用 DropOne()
或 DropOneAsync()
方法。
例子
以下示例应用程序从集合中删除索引。指定以下值:
Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接。
包含您要删除的搜索索引的数据库和集合。
要删除的搜索索引的名称。
using MongoDB.Bson; using MongoDB.Driver; // connect to your Atlas deployment var uri = "<connection-string>"; var client = new MongoClient(uri); var db = client.GetDatabase("<databaseName>"); var collection = db.GetCollection<BsonDocument>("<collectionName>"); // drop your Atlas Search index collection.SearchIndexes.DropOne("<index name>");
若要运行示例应用程序,请创建一个名为 csharp-delete-index
的新 .NET 控制台项目,并将上一个代码示例复制到 Program.cs
文件中。然后,使用以下命令运行项目:
dotnet run csharp-delete-index.csproj
注意
DropOne()
方法不返回输出。您可以使用Atlas用户界面查看索引状态。
要使用Java 驱动程序删除集合上的 Atlas Search 索引,请使用 dropSearchIndex()
方法。您必须有 Java 驱动程序 v 4.11.0 或更高版本。
将以下代码示例复制到该文件中。
以下示例应用程序删除指定集合上的指定 Atlas Search 索引。
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 public static void main(String[] args) { 9 // connect to your Atlas cluster 10 String uri = "<connection-string>"; 11 12 try (MongoClient mongoClient = MongoClients.create(uri)) { 13 // set namespace 14 MongoDatabase database = mongoClient.getDatabase("<database-name>"); 15 MongoCollection<Document> collection = database.getCollection("<collection>"); 16 // delete the index 17 collection.dropSearchIndex("<index-name>"); 18 } 19 } 20 }
替换以下值,然后保存文件。
<connection-string>
- Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接。注意
在连接字符串中,不要包含 writeConcern 设置。
<database-name>
— 包含该集合的数据库的名称。<collection-name>
— 要检索其索引的集合的名称。<index-name>
- 要删除的索引的名称。
另请参阅:
要通过节点驱动程序删除 Atlas Search 索引,请使用dropSearchIndex
辅助方法。
例子
您可以使用以下名为drop-index.js
的示例应用程序来删除集合上的索引。 指定以下值:
Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接。
在其中创建搜索索引的数据库和集合。
要删除的索引的名称。
// connect to your Atlas deployment const uri = "<connection-string>"; const client = new MongoClient(uri); async function run() { try { const database = client.db("<databaseName>"); const collection = database.collection("<collectionName>"); // run the helper method await collection.dropSearchIndex("<index-name>"); } finally { await client.close(); } } run().catch(console.dir);
要运行样本应用程序,请使用以下命令。
node drop-index.js
注意
dropSearchIndex
方法不返回输出。您可以使用Atlas用户界面查看索引状态。
要使用 Python 驱动程序删除 Atlas Search 索引,请在集合上调用 drop_search_index()
方法。
例子
将以下代码示例复制到该文件中。
以下示例应用程序将 Atlas Search 索引名称传递给 drop_search_index()
方法以删除该索引。
from pymongo.mongo_client import MongoClient def delete_index(): # Connect to your Atlas deployment uri = "<connectionString>" client = MongoClient(uri) # Access your database and collection database = client["<databaseName>"] collection = database["<collectionName>"] # Delete your search index collection.drop_search_index("<indexName>")
指定以下值并保存文件。
Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接。
您要删除索引的数据库和集合。
要删除的索引的名称。
估算您的索引大小
mongot
进程将索引字段和 _id
字段存储在磁盘上,因此您可能需要在构建索引之前调整索引的大小。您可以估计完整Atlas Search索引的大小,方法是在集合的子集上创建索引,并使用以下公式根据数据的总大小扩展示例数据索引的大小:
estimated-index-size = ( subset-data-index-size / subset-data-size ) x total-collection-data-size
示例,如果要估计movies
sample_mflix
数据库中 集合的索引大小,请执行mongosh
中的以下步骤:
运行
$sample
,使用随机数据示例创建名为sample_data
的新集合:use sample_mflix db.movies.aggregate([ { $sample: { size: 10 } }, { $out: "sample_data" } ]) [ { _id: ObjectId('573a13bbf29313caabd53f9c'), plot: "Three years ago, in real-life, Hama Ali, a charismatic actor from Iraq famous locally for his performance as Iraq's version of Superman, met Ayca on a film-set. He and Ayca, a fiery actress...", genres: [ 'Drama', 'Romance', 'War' ], runtime: 93, cast: [ 'Ayèa Damgaci', 'Hama Ali Kahn', 'Cengiz Bozkurt', 'Nesrin Cavadzade' ], num_mflix_comments: 1, poster: 'https://m.media-amazon.com/images/M/MV5BMjA1OTI1MjI4OV5BMl5BanBnXkFtZTgwODk1MTA2MDE@._V1_SY1000_SX677_AL_.jpg', title: 'Gitmek: My Marlon and Brando', fullplot: "Three years ago, in real-life, Hama Ali, a charismatic actor from Iraq famous locally for his performance as Iraq's version of Superman, met Ayca on a film-set. He and Ayca, a fiery actress from Turkey, had a passionate love affair before returning to their respective homes. From his Kurdish village, Hama Ali sends Ayca video love letters which he has filmed on his handycam. She watches them from her sofa in Istanbul, with her cat for company. The video love letters capture the hellish violence engulfing Iraq, the goats and uncles populating his rural area, and also his tender affection towards her. Feeling suffocated by her own city and angered by the indifference towards the war that surrounds her, Ayca decides to make the journey eastwards to Iraq to be reunited with her lover. GITMEK, a dramatic feature film, is based on the true story of Ayca's departure from Istanbul and her extraordinary journey to the Iraqi border. At a time when many people were fleeing from East to West in search of safety, Ayca makes the opposite journey, in search of love. She is helped by immigrant artists who live in the slums of Istanbul and the mothers of long distance truck drivers who she meets at various border towns. The journey takes her through breathtaking landscapes, strange encounters and terrifying times.", languages: [ 'English', 'Kurdish', 'Turkish' ], released: ISODate('2008-11-14T00:00:00.000Z'), directors: [ 'Huseyin Karabey' ], writers: [ 'Ayèa Damgaci', 'Huseyin Karabey' ], awards: { wins: 12, nominations: 4, text: '12 wins & 4 nominations.' }, lastupdated: '2015-07-04 00:20:59.083000000', year: 2008, imdb: { rating: 6.6, votes: 628, id: 920460 }, countries: [ 'Turkey' ], type: 'movie', tomatoes: { viewer: { rating: 3.7, numReviews: 181, meter: 79 }, lastUpdated: ISODate('2015-07-16T18:10:38.000Z') } }, { _id: ObjectId('573a139af29313caabcefb6a'), plot: '48 hours of intersecting lives and crimes in Los Angeles.', genres: [ 'Comedy', 'Crime', 'Drama' ], runtime: 104, rated: 'R', cast: [ 'Danny Aiello', 'Greg Cruttwell', 'Jeff Daniels', 'Teri Hatcher' ], num_mflix_comments: 1, poster: 'https://m.media-amazon.com/images/M/MV5BZDI0ZmFmYTgtMTQ5OS00MTVmLTgwNWYtNzIyY2Y5NjYxNzgyXkEyXkFqcGdeQXVyNzc5MjA3OA@@._V1_SY1000_SX677_AL_.jpg', title: '2 Days in the Valley', fullplot: 'John Herzfeld deftly welds together a multitude of subplots-- a loser hitman and a cool assassin involved in an insurance scam; a washed-up director, turned suicidal, if only he had someone to care for his beloved dog; a snooty art dealer, wracked by kidney stones, cared for by his devoted assistant; a grungy deranged vice cop, now partnered with a fresh-faced rookie; and two beautiful and jealous women entangled in their deadly scheme--into a spoof of the crime thriller genre.', languages: [ 'English', 'Vietnamese' ], released: ISODate('1996-09-27T00:00:00.000Z'), directors: [ 'John Herzfeld' ], writers: [ 'John Herzfeld' ], awards: { wins: 0, nominations: 1, text: '1 nomination.' }, lastupdated: '2015-09-11 00:42:22.520000000', year: 1996, imdb: { rating: 6.5, votes: 15019, id: 115438 }, countries: [ 'USA' ], type: 'movie', tomatoes: { viewer: { rating: 3, numReviews: 14630, meter: 55 }, dvd: ISODate('2001-08-07T00:00:00.000Z'), critic: { rating: 6, numReviews: 53, meter: 60 }, lastUpdated: ISODate('2015-08-19T18:25:36.000Z'), consensus: 'A labyrinthine thriller with a host of memorable characters, 2 Days in the Valley is an uneven but intriguing thriller/black comedy.', rotten: 21, production: 'HBO Video', fresh: 32 } }, { _id: ObjectId('573a13bdf29313caabd5943e'), fullplot: "When Emily Parris exposes a secret society of teenage girls who have slipped out of the world of social media and into another world they've discovered in the woods at night. When she accuses the girls of committing sexually deviant activities, Emily sends the small American town into a atmosphere of hysteria and the national media spotlight. The mystery deepens when each of the accused girls upholds a vow of silence.", imdb: { rating: 6.2, votes: 861, id: 1015471 }, year: 2014, plot: "When a teenage girl says she's the victim of a secret network called The Sisterhood of Night, a quiet suburban town becomes the backdrop for a modern-day Salem witch trial.", genres: [ 'Drama', 'Mystery', 'Thriller' ], rated: 'PG-13', metacritic: 60, title: 'The Sisterhood of Night', lastupdated: '2015-09-10 17:22:16.113000000', languages: [ 'English' ], writers: [ 'Marilyn Fu (screenplay)', 'Steven Millhauser (short story)' ], type: 'movie', tomatoes: { website: 'http://www.thesisterhoodofnight-movie.com/', viewer: { rating: 3.6, numReviews: 382, meter: 65 }, dvd: ISODate('2015-06-09T00:00:00.000Z'), critic: { rating: 6.6, numReviews: 19, meter: 79 }, boxOffice: '$5.3k', rotten: 4, production: 'Cine Mosaic', lastUpdated: ISODate('2015-09-13T17:24:37.000Z'), fresh: 15 }, poster: 'https://m.media-amazon.com/images/M/MV5BODg3MjE0MDM4N15BMl5BanBnXkFtZTgwOTY0MjE5NDE@._V1_SY1000_SX677_AL_.jpg', num_mflix_comments: 1, released: ISODate('2014-10-18T00:00:00.000Z'), awards: { wins: 2, nominations: 3, text: '2 wins & 3 nominations.' }, countries: [ 'USA' ], cast: [ 'Georgie Henley', 'Kara Hayward', 'Willa Cuthrell', 'Olivia DeJonge' ], directors: [ 'Caryn Waechter' ], runtime: 104 }, { _id: ObjectId('573a13c4f29313caabd6d7bf'), plot: 'A film producer struggles with suicidal despair.', genres: [ 'Drama' ], runtime: 110, metacritic: 76, cast: [ 'Louis-Do de Lencquesaing', 'Chiara Caselli', 'Alice de Lencquesaing', 'Alice Gautier' ], num_mflix_comments: 0, poster: 'https://m.media-amazon.com/images/M/MV5BMTUxODczODA2NV5BMl5BanBnXkFtZTcwNzExMjQ1Mw@@._V1_SY1000_SX677_AL_.jpg', title: 'Father of My Children', fullplot: "In the first half, Gregoire, a movie producer of great charm, owner of Moon Films, plays with his younger daughters, talks with his wife and his eldest daughter, and keeps his studio going while one project hemorrhages money and creditors circle. In the second half, Sylvia, his Italian wife, tries to hold the family together as she looks fully into Moon Films' troubles. She meets with a banker, a temperamental Swede, Russian TV magnates, a film lab exec, and Moon's lawyer. Clèmence, the oldest daughter, goes on her own search. Debt can crush; how does a family pick up the pieces?", languages: [ 'French' ], released: ISODate('2009-12-16T00:00:00.000Z'), directors: [ 'Mia Hansen-Lève' ], writers: [ 'Mia Hansen-Lève (screenplay)' ], awards: { wins: 2, nominations: 3, text: '2 wins & 3 nominations.' }, lastupdated: '2015-09-02 00:01:22.897000000', year: 2009, imdb: { rating: 6.7, votes: 1820, id: 1356928 }, countries: [ 'France', 'Germany', 'Belgium' ], type: 'movie', tomatoes: { website: 'http://www.filmsdulosange.fr/fr/fr_peredemesenfants.html', viewer: { rating: 3.3, numReviews: 1232, meter: 60 }, dvd: ISODate('2010-06-21T00:00:00.000Z'), critic: { rating: 7.4, numReviews: 55, meter: 91 }, lastUpdated: ISODate('2015-09-11T18:38:12.000Z'), consensus: 'A tragedy gracefully lifted by tender empathy and moments of joy, Father of My Children is a quiet triumph for writer-director Mia Hansen-Love.', rotten: 5, production: 'IFC Films', fresh: 50 } }, { _id: ObjectId('573a13a5f29313caabd15cc1'), plot: 'After a 13-year imprisonment in Hong Kong, a kickboxer challenges the current champion in order to restore his honor.', genres: [ 'Drama', 'Romance', 'Sport' ], runtime: 105, cast: [ 'Andy Lau', 'Takako Tokiwa', 'Inthira Charoenpura', 'Apichaya Thanatthanapong' ], title: 'Ah Fu', lastupdated: '2015-09-14 12:56:13.823000000', languages: [ 'Cantonese' ], released: ISODate('2000-11-21T00:00:00.000Z'), directors: [ 'Daniel Lee' ], writers: [ 'Chi-Sing Cheung', 'Daniel Lee' ], awards: { wins: 1, nominations: 3, text: '1 win & 3 nominations.' }, year: 2000, imdb: { rating: 6.6, votes: 350, id: 277558 }, countries: [ 'Hong Kong' ], type: 'movie', tomatoes: { viewer: { rating: 3.3, numReviews: 644, meter: 57 }, lastUpdated: ISODate('2015-04-25T18:41:33.000Z') }, num_mflix_comments: 0 }, { _id: ObjectId('573a13bef29313caabd5ce2b'), plot: 'Johann Sebastian Bach llega con su familia a Leipzig para ocupar el puesto de cantor en la Escuela de Santo Tomès...', genres: [ 'Musical' ], runtime: 102, metacritic: 70, cast: [ 'Christian Atanasiu', 'Fèodor Atkine', 'George-Christoph Biller', 'Christian Brembeck' ], title: 'The Silence Before Bach', lastupdated: '2015-05-25 00:50:52.210000000', languages: [ 'Spanish', 'German', 'Catalan' ], released: ISODate('2007-12-21T00:00:00.000Z'), directors: [ 'Pere Portabella' ], writers: [ 'Xavier Albertè', 'Pere Portabella', 'Carles Santos' ], awards: { wins: 3, nominations: 3, text: '3 wins & 3 nominations.' }, year: 2007, imdb: { rating: 6.8, votes: 329, id: 1079450 }, countries: [ 'Spain' ], type: 'movie', tomatoes: { website: 'http://www.pereportabella.com/eng/fla/die/home_eng.html', viewer: { rating: 3.5, numReviews: 391, meter: 64 }, critic: { rating: 6.6, numReviews: 16, meter: 81 }, lastUpdated: ISODate('2015-08-11T19:15:49.000Z'), rotten: 3, production: 'Film Forum', fresh: 13 }, num_mflix_comments: 0 }, { _id: ObjectId('573a13ccf29313caabd83260'), plot: 'A woman subject to mental, physical, and sexual abuse on a remote island seeks a way out.', genres: [ 'Crime', 'Drama', 'Horror' ], runtime: 115, cast: [ 'Yeong-hie Seo', 'Seong-won Ji', 'Min-ho Hwang', 'Min Je' ], num_mflix_comments: 0, poster: 'https://m.media-amazon.com/images/M/MV5BMjAyNDEwMDgzMl5BMl5BanBnXkFtZTcwNzMyMTYwNQ@@._V1_SY1000_SX677_AL_.jpg', title: 'Bedevilled', fullplot: "Hae-won is a beautiful single woman in her thirties who works at a bank in the Seoul city. She leads a busy life until she becomes a witness to an attempted murder case, and at the same time, things get complicated at work. When things get out of hand she is forced to take a vacation so she heads for 'Moodo', a small undeveloped island, where she had once visited to see her grandparents. And where she had befriended a girl named Bok-nam who stills writes to Hae-won asking her to visit despite the fact that Hae-won never bothered to reply. Upon arriving at the island, Hae-won is shocked to see everyone treating Bok-nam like a slave. As practically the only young woman on the island, she is a plaything for all the men and a free laborer for the women. Sick of all the inhumane treatment, Bok-nam had tried to escape the island several times in the past but had failed each time. She begs Hae-won to help her escape the place, but Hae-won remains indifferent not wanting to be involved in complicated situations. When Bok-nam realizes that her own daughter will follow her footsteps, she tries to escape the island with her daughter.", languages: [ 'Korean' ], released: ISODate('2010-09-02T00:00:00.000Z'), directors: [ 'Cheol-soo Jang' ], writers: [ 'Kwang-young Choi' ], awards: { wins: 10, nominations: 5, text: '10 wins & 5 nominations.' }, lastupdated: '2015-09-01 01:18:02.960000000', year: 2010, imdb: { rating: 7.3, votes: 7983, id: 1646959 }, countries: [ 'South Korea' ], type: 'movie' }, { _id: ObjectId('573a13c7f29313caabd746fe'), plot: 'A Californian family inherits a castle in Romania. This is especially exciting to the son, who is obsessed with monsters. And he is not disappointed.', genres: [ 'Comedy', 'Family' ], runtime: 83, rated: 'TV-G', cast: [ 'Victoria Justice', 'Chase Ellison', 'Anna Galvin', 'Matt Winston' ], num_mflix_comments: 0, poster: 'https://m.media-amazon.com/images/M/MV5BMjU1MmJlMTctY2FiMC00MmU1LWI5NmYtMDc5OWM0NjEzMmI2XkEyXkFqcGdeQXVyNDgyODgxNjE@._V1_SY1000_SX677_AL_.jpg', title: 'The Boy Who Cried Werewolf', fullplot: 'A Californian family inherits a castle in Romania. This is especially exciting to the son, who is obsessed with monsters. And he is not disappointed.', languages: [ 'English' ], released: ISODate('2010-10-22T00:00:00.000Z'), directors: [ 'Eric Bross' ], writers: [ 'Art Edler Brown', 'Douglas Sloan' ], awards: { wins: 1, nominations: 2, text: '1 win & 2 nominations.' }, lastupdated: '2015-08-20 00:01:59.673000000', year: 2010, imdb: { rating: 6.3, votes: 1582, id: 1451423 }, countries: [ 'USA', 'Canada' ], type: 'movie', tomatoes: { viewer: { rating: 3.7, numReviews: 762, meter: 66 }, lastUpdated: ISODate('2015-09-12T17:30:20.000Z') } }, { _id: ObjectId('573a13b4f29313caabd3f473'), genres: [ 'Documentary' ], runtime: 85, title: 'Zero Degrees of Separation', countries: [ 'Canada' ], lastupdated: '2015-08-09 00:30:38.977000000', languages: [ 'Arabic', 'English', 'Hebrew' ], released: ISODate('2005-06-22T00:00:00.000Z'), directors: [ 'Elle Flanders' ], writers: [ 'Elle Flanders' ], awards: { wins: 1, nominations: 0, text: '1 win.' }, year: 2005, imdb: { rating: 6.6, votes: 90, id: 454990 }, type: 'movie', tomatoes: { viewer: { rating: 3.5, numReviews: 5, meter: 100 }, fresh: 1, critic: { numReviews: 2 }, rotten: 1, lastUpdated: ISODate('2015-01-04T23:25:58.000Z') }, num_mflix_comments: 0 }, { _id: ObjectId('573a13bff29313caabd5f070'), plot: 'This hilarious genre-bending comedy follows Gary Brewer, along with girlfriend Holly Brewer (no relation), and best friend Trevor Morehouse as Gary quests to reign supreme at the 2006 Rock, Paper, Scissors World Championships.', genres: [ 'Comedy' ], runtime: 85, cast: [ 'Tim Doiron', 'April Mullen', 'Ryan Tilley', 'Peter Pasyk' ], num_mflix_comments: 0, poster: 'https://m.media-amazon.com/images/M/MV5BMTI5MzIwMjA2Ml5BMl5BanBnXkFtZTcwOTcyOTA4MQ@@._V1_SY1000_SX677_AL_.jpg', title: 'Rock, Paper, Scissors: The Way of the Tosser', fullplot: 'This hilarious genre-bending comedy follows Gary Brewer, along with girlfriend Holly Brewer (no relation), and best friend Trevor Morehouse as Gary quests to reign supreme at the 2006 Rock, Paper, Scissors World Championships.', languages: [ 'English' ], released: ISODate('2007-07-06T00:00:00.000Z'), directors: [ 'Tim Doiron', 'April Mullen' ], writers: [ 'Tim Doiron (creator)', 'April Mullen (creator)', 'Tim Doiron' ], awards: { wins: 2, nominations: 0, text: '2 wins.' }, lastupdated: '2015-08-12 00:01:33.813000000', year: 2007, imdb: { rating: 6.2, votes: 316, id: 1121964 }, countries: [ 'Canada' ], type: 'movie' } ] 使用要用于完整集合的索引定义,在包含示例数据的集合上创建搜索索引:
db.sample_data.createSearchIndex( "sample-index", { mappings: { dynamic: true } } ) sample-index 将示例数据的大小按集合的总大小进行缩放。示例,如果
sample-index
索引的大小为 44.88,根据Atlas用户界面索引概述页面,您可以使用以下命令来计算索引的总大小:let sampleSize = db.sample_data.totalSize() let totalSize = db.movies.totalSize() let totalIndexSize = ( 44.88 / sampleSize ) * totalSize; totalIndexSize 45864.28
审查索引状态
在Atlas 用户界面中,Atlas Search 页面上的 Status 列显示集群主节点 (primary node in the replica set)节点上索引的当前状态。下表描述了可能的索引状态:
状态 | 说明 |
---|---|
待处理 | Atlas 尚未开始构建索引。 |
构建 | Atlas 正在构建索引或在编辑后重新构建索引。当该索引处于以下状态时:
|
Ready(就绪) | 索引已准备就绪。 |
Stale | 由于以下任一原因,索引已过时:
您仍然可以查询现有索引。但是,针对过时索引的查询结果可能包含过时数据。您可以扩容搜索节点以获得更多磁盘空间,并删除现有索引以释放磁盘空间。或者,使用 View status details(查看状态详情)模态窗口中的错误来排查问题。要了解更多信息,请参阅修复 Atlas Search 问题。 |
已失败 | Atlas 无法构建索引。使用 View status details(查看状态详细信息)模式窗口中的错误来解决问题。要了解更多信息,请参阅修复 Atlas Search 问题。 |
删除 | Atlas 正在从集群节点中删除索引。 |
Does not Exist(不存在) | 索引无效,因为索引的集合不再存在。您无法对此索引运行查询,因为该索引没有相应的集合。Atlas 最终会删除该索引。 |
您可以通过以下方式之一在 Status Details 页面中查看更多状态信息:
单击 Status 列中的 View status details 链接。
单击 Index Name 列中的名称,然后从 Index Overview 左侧的菜单中选择 Status Details。
Status Details 页面包含以下部分:
索引服务查询
此部分显示用于提供服务的索引。
如果该集合只有一个版本的索引使用该名称,则该部分包含一个指向 Index Overview 的链接,在该链接中可以查看正在使用的索引的索引定义。
如果集合中有其他同名索引,则该部分将显示最新的索引定义,还会显示您可以在不同标签页中复制的索引的先前有效版本。
更新索引时,不同节点以不同速度应用更新。因此,某些节点可能会使用最新版本,而某些节点可能会使用先前版本。Atlas 会显示索引的两个版本,直到更改应用于所有节点。
如果尝试使用无效的索引定义更新索引,则索引构建将失败,Atlas 只能显示之前有效的索引定义。
按节点查看状态详情
此部分显示集群每个节点上的索引状态。您可以查看每个节点上索引的以下详细信息:
Shard | 分片名称。 |
Node | 节点信息。 |
Status | 分片节点点上的索引状态。 |
Queryable | 指示索引能否提供服务查询提供服务的图标。 |
Message | 索引状态的原因。对于处于 |
Node Type | 节点类型。值可以是以下类型之一:
|
Region | Node 区域。 |
Size | 节点上索引的大小。 |
Documents | 已建立索引的文档数量和百分比。 |
Actions | 您可以对节点中的索引采取的操作。您可以点击并选择下列选项之一:
|
迁移到搜索节点
本部分显示正在进行的Atlas Search和Atlas Vector Search索引到搜索节点的迁移状态(如果适用)。仅当您当前正在迁移到搜索节点时,才会显示此部分。
单击 Index Status by Search Node 部分下信息横幅中的 View Migration Progress 链接,了解有关将索引迁移到 Search Nodes 的进度的详细信息(基于每个节点)。
Atlas 用户界面显示集群上每个索引的以下列。
列 | 说明 |
---|---|
Database | 包含该集合的数据库名称。 |
Collection | 索引集合的名称。 |
Index Name | 索引名称。 |
Index Fields | |
Type | 索引的类型。值可以是以下类型的索引之一:
|
Status | 迁移状态。 要学习;了解更多信息,请参阅迁移到搜索节点。 |
Size | 索引的大小。 |
Documents | 迁移期间和之后,集群搜索节点上已建立索引的文档在集合中文档总数中所占的比例。 |
状态列显示搜索节点上索引的以下状态之一:
状态 | 说明 |
---|---|
构建 | 当前正在搜索节点上构建索引。在构建新索引时,您的查询可以继续使用现有索引。 |
On Deck | 索引已在搜索节点上成功构建,但迁移尚未完成。请注意,只有当 Atlas 在 Search 节点上成功构建所有索引时,迁移才算完成。 |
Ready(就绪) | 搜索节点上的索引已准备好用于查询。仅当 Atlas 成功完成到搜索节点的迁移时才会显示。 |
已失败 |
您的查询可以继续使用现有索引,同时在搜索节点上构建新索引。仅当Atlas成功在搜索节点上构建所有索引时,才能完成向搜索节点的迁移。然后,您的查询将自动路由到使用搜索节点上的索引。
了解详情
要学习;了解如何定义Atlas Search索引以满足Atlas Search查询需求,请参阅定义查询。
要学习;了解如何创建Atlas Search索引,请参阅创建Atlas Search索引。
要学习;了解有关本教程中描述的Atlas Search索引配置的更多信息,请参阅以下参考页面:
如需亲身体验为示例数据集创建Atlas Search索引以及对索引数据运行Atlas Search查询,请尝试Atlas Search快速入门。
继续学习
通过观看学习
本视频教程演示如何创建不同复杂程度的 Atlas Search 索引。
时长:15 分钟