Docs 菜单
Docs 主页
/
Atlas
/ /

管理 Atlas Search 索引

Atlas Search索引是一种数据结构,它将数据分类为易于搜索的格式。它是术语与包含这些术语的文档之间的映射。 Atlas Search索引启用使用某些标识符更快地检索文档。您必须配置Atlas Search索引,才能使用Atlas Search查询Atlas 集群中的数据。

您可在单个字段或多个字段上创建 Atlas Search 索引。我们建议您对经常用于排序或筛选数据的字段建立索引,以便在查询时快速检索包含相关数据的文档。

如果您对为其定义Atlas Search索引的集合进行更改,最新数据可能无法立即用于查询。但是,mongot 会监控变更流,使其能够更新存储的数据副本, Atlas Search索引最终会一致。

当您更改索引定义时,mongot 会在背景自动重建新索引,同时继续使用旧索引为查询提供服务,以确保不会停机。当您在同一节点上部署mongotmongod 进程以及将进程部署在不同节点上时,会发生这种情况。当您启用或禁用 静态加密时, Atlas还会重建索引。

如果您更改搜索部署的拓扑结构,Atlas Search 会在删除旧节点之前在任何新节点上配置并构建索引,以确保查询不会停机。

对于 mongodmongot 进程在同一节点上运行的部署,如果Atlas Search引入需要重建索引的更改(例如某些Atlas Search功能需要更新索引),Atlas会自动部署额外的节点免费构建索引,而旧节点继续为您的查询提供服务。

警告

如果您对已具有 Atlas Search 索引的集合进行分片,当该集合开始出现在分片上时,您可能会遇到短暂的查询停机时间。此外,如果您为包含 Atlas Search 索引的已分片集合添加分片,针对该集合的搜索查询将失败,直到添加的分片完成初始同步过程为止。要了解更多信息,请参阅初始同步进程。

重要

如果使用$out聚合阶段修改具有现有Atlas Search索引的集合,则必须删除并重新创建搜索索引。如果可能,请考虑使用$merge而不是 $out

您可以部署专用搜索节点来提高性能、可扩展性和资源隔离。如果您已经部署搜索节点,请考虑以下情况:

  • 添加和调整 分片将会触发 Atlas Search 索引重建。在该索引重建期间,索引可能没有最新的数据。因此,针对这些分片上的数据的查询可能会失败,或返回不正确的结果。

  • 如果您对包含Atlas Search索引的集合进行重新分片,则在重新分片操作完成后,该集合上的Atlas Search索引将变为不可用。操作完成后,您必须删除Atlas Search 索引并创建新的Atlas Search索引。

  • 如果发出命令更改数据库的主分片,则一旦操作完成,该数据库下任何未分片集合的 Atlas Search索引将不可用。movePrimary 操作完成后,您必须删除并创建新的 Atlas Search 索引。

要学习;了解有关Atlas Search节点架构的更多信息,请参阅Atlas Search部署选项。

您可以分配项目用户角色或数据库用户角色,以访问权限执行本指南中描述的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索引。

要查看为 sample_mflix.movies集合创建索引的示例教程,请参阅Atlas Search快速入门。有关如何定义索引以满足您的查询偏好的概念概述,请参阅定义索引

您还可以将 Atlas Search 与通过 Atlas CLI 创建的本地 Atlas 部署结合使用。要了解详情,请参阅创建本地 Atlas 部署


➤ 使用选择语言下拉菜单设立本节中过程的语言。


要使用Atlas Search API创建Atlas Search索引:

1

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>
}
]
}
}'

要了解有关此端点的语法和参数的更多信息,请参阅创建一个。

2

注意

如果该集合不存在,Atlas 则不会创建索引,但仍会返回 200 状态。

要使用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 clustersatlas deployments 命令通过配置文件在非交互模式下创建 Atlas Search 索引。

1
{
"collectionName": "movies",
"database": "sample_mflix",
"definition": {
"mappings": {
"dynamic": true
},
},
"name": "searchIndex"
}
2
  1. 运行以下命令之一。

    云部署:

    atlas clusters search indexes create --file indexDef.json

    本地部署:

    atlas deployments search indexes create --file indexDef.json
  2. 指定部署并按 Enter

要使用Atlas用户界面创建Atlas Search索引,请执行以下操作:

1

警告

导航改进正在进行中

我们目前正在推出改进的全新导航体验。如果以下步骤与Atlas用户界面中的视图不匹配,请参阅预览文档。

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

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

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

    会显示集群页面。

2

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

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

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

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

    将显示 Atlas Search 页面。

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

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

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

    将显示 Atlas Search 页面。

  1. 单击集群的名称。

  2. 单击 Atlas Search 标签页。

    将显示 Atlas Search 页面。

3
4

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

Search Type

选择Atlas Search索引类型。

Index Name and Data Source

指定以下信息:

  • Index Name: default

  • Database and Collection:

    • 数据库名称

    • 集合名称

Configuration Method

For a guided experience, select Visual Editor.

To edit the raw index definition, select JSON Editor.

注意

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

5

默认索引定义是文档中字段的动态映射,适用于任何集合。

要自定义索引定义,查看以下索引配置:

可视化编辑器字段
说明
必要性

Index Analyzer

指定用于索引集合数据的分析器。默认情况下,Atlas Search 使用标准分析器 (lucene.standard)。

对应于 analyzer JSON 设置。

Optional

Search Analyzer

指定在搜索查询文本之前要应用到文本的分析器。如果省略此字段,则索引默认按以下顺序继承分析器:

  1. 该字段的 analyzer 选项(如果已指定)。

  2. 索引searchAnalyzer 选项(如果指定)。

  3. 索引analyzer 选项(如果指定)。

  4. lucene.standard 分析器。

对应于 searchAnalyzer JSON 设置。

Optional

Dynamic Mapping

指定字段的动态或静态映射。

默认下,启用动态映射。要禁用动态映射,请将 dynamic设立为 Off。如果禁用动态映射,则必须指定要索引的字段。

要学习;了解有关动态和静态映射的更多信息,请参阅定义字段映射。

对应于 mappings.dynamic JSON 设置。

必需

字段名称
说明
必要性

analyzer

指定用于索引集合数据的分析器。默认情况下,Atlas Search 使用标准分析器 (lucene.standard)。

Optional

searchAnalyzer

指定在搜索查询文本之前要应用到文本的分析器。如果省略此字段,则索引默认按以下顺序继承分析器:

  1. 该字段的 analyzer 选项(如果已指定)。

  2. 索引searchAnalyzer 选项(如果指定)。

  3. 索引analyzer 选项(如果指定)。

  4. lucene.standard 分析器。

Optional

mappings.dynamic

指定字段的动态或静态映射。要禁用动态映射,请将 "dynamic": 设立为 false。默认下,启用动态映射。如果禁用动态映射,则必须指定要索引的字段。要学习;了解有关动态和静态映射的更多信息,请参阅索引参考。

必需

要学习;了解有关这些索引定义设置的更多信息,请参阅索引参考。

如果您对默认配置感到满意,请跳过。如果您希望完善您的 Atlas Search 索引,请继续执行下一步。

6
  1. 单击 Refine Your Index 更改以下任何设置。

    字段名称
    说明
    必要性

    Field Mappings

    如果 Index Configurations 部分中的 Dynamic Mapping 处于禁用状态,则为必填项。

    指定要索引的字段:

    1. 点击 Add Field Mapping 打开 Add Field Mapping 窗口。

    2. 指定关于字段的以下信息:

      • Field name -要索引的字段名称。

      • Data Type - 字段数据类型。要详细了解支持的数据类型及其选项,请参阅数据类型。

    3. (可选)指定其他属性。

      其他配置选项表出现在 Add Field Mapping窗口中。这些属性取决于您在上一步中选择的数据类型。

      要详细了解支持的数据类型及其选项,请参阅数据类型。

    4. (可选)添加多字段。

      单击 Add Multi Field 配置备用字段分析器,用于索引字段。要学习;了解更多信息,请参阅多分析器。

    5. 单击 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 设置。

    可选。

  2. 单击 Save Changes(连接)。

  1. 将以下任意设置添加到您的索引:

    字段名称
    说明
    必要性

    mappings.fields

    如果 mappings.dynamicfalse,则为必填项。

    指定要编制索引的字段。要了解更多信息,请参阅定义字段映射。

    可选的

    storedSource

    指定要在Atlas Search上存储以进行查询时查找的字段。您可以在Atlas Search上存储所有支持的数据类型的字段。

    要了解有关存储字段的更多信息,请参阅在 Atlas Search 索引中定义存储的源字段

    Optional

    synonyms

    指定要在索引中使用的同义词映射。

    您可以使用同义词映射来仅查询使用同一分析器分析的字段。

    要学习;了解有关同义词映射的更多信息,请参阅在Atlas Search索引中定义同义词映射。

    Optional

    numPartitions

    字段对象超过 2.1 十亿时要使用的分区数。

    可选。

    要学习;了解有关这些索引定义设置的更多信息,请参阅索引参考。

  2. 单击 Next(连接)。

7

注意

您无法将默认索引定义保存为草稿。如果您使用 Visual Editor 并且索引定义包含静态映射,则可以将索引定义保存为草稿。

  1. 单击 Cancel(连接)。

  2. 点击 Save DraftDelete Draft

    重要

    在有待处理的索引草稿时,您无法创建新索引。

    要学习;了解更多信息,请参阅恢复或删除Atlas Search索引草稿。

8

Atlas 会显示一个 Toast(简短的非交互式通知),以通知索引正在构建中。

9

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

注意

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

要使用 创建Atlas Search索引:mongosh

1

要了解更多信息,请参阅通过 mongosh 进行连接

2

使用 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索引,请执行以下操作:

1

打开Compass并连接到您的Atlas 集群。有关详细说明,请参阅通过Compass连接。

2

Database 屏幕上,单击数据库名称,然后单击集合名称。

3
  1. 单击 Indexes 标签页,然后选择 Search Indexes

  2. 单击 Create Index,打开索引创建对话框。

  3. 指定索引的名称。

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

  4. 指定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
  5. 单击 Create Search Index(连接)。

要使用 C 驱动程序创建 Atlas Search 索引,请在应用程序中定义搜索索引并调用 mongoc_collection_command_simple() 方法。

注意

Atlas Search 索引管理方法异步运行。驱动程序方法可以在确认成功运行前返回。要确定搜索索引的当前状态,请使用 $listSearchIndexes 管道阶段运行聚合操作。

1
2

以下示例应用程序指定 createSearchIndexes 命令来定义搜索索引。然后,应用程序将命令和搜索索引信息转换为BSON,并将此信息传递给 mongoc_collection_command_simple() 方法以创建搜索索引。要学习;了解更多信息,请参阅索引参考

#include <mongoc/mongoc.h>
#include <stdlib.h>
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() 方法以创建搜索索引。要学习;了解更多信息,请参阅索引参考。

#include <mongoc/mongoc.h>
#include <stdlib.h>
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;
}
3
  • Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接

  • 要创建索引的数据库和集合。

  • 索引名称。如果省略索引名称,Atlas Search 会将索引命名为 default

  • 搜索索引定义。要学习;了解更多信息,请参阅索引参考。

4
gcc -o create-index create-index.c $(pkg-config --libs --cflags libmongoc-1.0)
./create-index

要使用 C++ 驱动程序创建 Atlas Search 索引,请在应用程序中定义搜索索引并调用 create_one() 方法。

注意

Atlas Search 索引管理方法异步运行。驱动程序方法可以在确认成功运行前返回。要确定搜索索引的当前状态,请在搜索索引视图实例上调用 list() 方法。

1
2

以下示例应用程序将搜索索引名称和定义传递给 search_index_model() 方法,以便对集合中的字段动态索引。然后,应用程序将搜索索引规范传递给 create_one() 方法以创建搜索索引。要学习;了解更多信息,请参阅索引参考。

#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/builder/basic/kvp.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/search_index_view.hpp>
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() 方法以创建搜索索引:

#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/builder/basic/kvp.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/search_index_view.hpp>
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;
}
3
  • Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接

  • 要创建索引的数据库和集合。

  • 索引名称。如果省略索引名称,Atlas Search 会将索引命名为 default

  • 搜索索引定义。要学习;了解更多信息,请参阅索引参考。

4
g++ -o create-index create-index.cpp $(pkg-config --cflags --libs libmongocxx)
./create-index

使用 .NET/C# 驱动程序创建 Atlas Search 索引:

  1. 构建一个定义索引的 BsonDocument

  2. BsonDocument 传递给 CreateOne()CreateOneAsync() 方法。

1
  1. 运行以下命令以创建一个名为 csharp-create-index 的新目录。

    mkdir csharp-create-index
  2. 运行以下命令以切换到新目录。

    cd csharp-create-index
  3. 运行以下命令,以初始化项目。

    dotnet new console
2

运行以下命令:

dotnet add package MongoDB.Driver
3

替换以下示例应用程序中的占位符值,该应用程序使用 SearchIndexes.CreateOne 命令定义Atlas Search索引:

说明

<connection-string>

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

<databaseName>

要创建索引的数据库。

<collectionName>

要为其创建索引的集合。

<IndexName>

索引名称。如果省略索引名称,Atlas Search 会将索引命名为 default

<IndexDefinition>

索引的定义。要学习;了解索引定义语法,请参阅索引参考。

1using MongoDB.Bson;
2using MongoDB.Driver;
3
4// connect to your Atlas deployment
5var uri = "<connection-string>";
6
7var client = new MongoClient(uri);
8
9var db = client.GetDatabase("<databaseName>");
10var collection = db.GetCollection<BsonDocument>("<collectionName>");
11
12// define your Atlas Search index
13var index = new BsonDocument
14{
15 { "mappings", new BsonDocument
16 {
17 { "dynamic", true }
18 }
19 }
20};
21
22var result = collection.SearchIndexes.CreateOne(index, "<indexName>");
23Console.WriteLine(result);

替换以下示例应用程序中的占位符值,该应用程序使用 SearchIndexes.CreateMany 命令定义Atlas Search索引:

说明

<connection-string>

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

<databaseName>

要创建索引的数据库。

<collectionName>

要为其创建索引的集合。

<firstIndexName>

第一个索引的名称。

<lastIndexName>

最后一个索引的名称。

<IndexDefinition>

索引的定义。要学习;了解索引定义语法,请参阅索引参考。

1using MongoDB.Bson;
2using MongoDB.Driver;
3
4// connect to your Atlas deployment
5var uri = "<connection-string>";
6
7var client = new MongoClient(uri);
8
9var db = client.GetDatabase("<databaseName>");
10var collection = db.GetCollection<BsonDocument>("<collectionName>");
11
12// define your Atlas Search indexes
13var 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
32var result = collection.SearchIndexes.CreateMany(indexes);
4

使用以下命令运行项目:

dotnet run csharp-create-index.csproj
default

提示

API 文档

要了解有关本页方法的更多信息,请参阅 .NET/C# 驱动程序的 API 文档

要使用Java驱动程序创建Atlas Search索引,请构造定义搜索索引的文档,然后将该文档传递给 createSearchIndex()createSearchIndexes() 方法。

注意

Atlas Search 索引管理方法异步运行。驱动程序方法可以在确认成功运行前返回。要确定索引的当前状态,请调用 listSearchIndexes() 方法。

1
2

以下示例应用程序定义一个搜索索引以动态索引集合中的字段,然后运行 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));
}
}
}
3
  • Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接

  • 要创建索引的数据库和集合。

  • 您的索引的名称。如果省略索引的名称,Atlas Search 会将索引命名为 default

  • 用于定义搜索索引的字段。要学习;了解更多信息,请参阅索引参考。

4
javac CreateIndex.java
java CreateIndex

通过节点驱动程序创建 Atlas Search 索引:

  1. 从您的应用程序定义搜索索引。

  2. 运行 createSearchIndexcreateSearchIndexes 辅助方法。

1
2

替换以下名为 create-index.js 的示例应用程序中的占位符值,该应用程序使用 createSearchIndex 命令定义Atlas Search索引:

说明

<connectionString>

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

<databaseName>

要创建索引的数据库。

<collectionName>

要为其创建索引的集合。

<indexName>

索引的名称。 如果省略索引名称,Atlas Search 会将索引命名为default

<IndexDefinition>

索引的定义。要学习;了解索引定义语法,请参阅索引参考。

create-index.js
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);
说明

<connectionString>

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

<databaseName>

要创建索引的数据库。

<collectionName>

要为其创建索引的集合。

<indexName>

索引的名称。 如果省略索引名称,Atlas Search 会将索引命名为default

<IndexDefinition>

索引的定义。要学习;了解索引定义语法,请参阅索引参考。

替换以下名为 create-index.js 的示例应用程序中的占位符值,该应用程序使用 createSearchIndexes 命令定义Atlas Search索引:

create-index.js
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);
3

请使用以下命令:

node create-index.js
<index-name>

要使用 Python 驱动程序来创建 Atlas Search 索引,请在应用程序中定义搜索索引并调用 create_search_index() 方法。

注意

Atlas Search 索引管理方法异步运行。驱动程序方法可以在确认成功运行前返回。要确定搜索索引的当前状态,请对集合调用 list_search_indexes() 方法。

1
2

以下示例应用程序定义了一个搜索索引,以便对集合中的字段进行动态索引。然后,应用程序对集合调用 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)
3
  • Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接

  • 要创建索引的数据库和集合。

  • 索引名称。如果省略索引名称,Atlas Search 会将索引命名为 default

  • 搜索索引定义。要学习;了解更多信息,请参阅索引参考。

4
python create_index.py

创建Atlas Search索引时, Atlas Search页面会显示有关Atlas Search索引的信息。 Status 列显示集群主节点 (primary node in the replica set)节点上索引的当前状态。要学习;了解更多信息,请参阅查看索引状态。

警告

如果您对已具有 Atlas Search 索引的集合进行分片,当该集合开始出现在分片上时,您可能会遇到短暂的查询停机时间。此外,如果您为包含 Atlas Search 索引的已分片集合添加分片,针对该集合的搜索查询将失败,直到添加的分片完成初始同步过程为止。要了解更多信息,请参阅初始同步进程。


➤ 使用选择语言下拉菜单设立本节中过程的语言。


要使用Atlas Search API检索Atlas Search索引,检索以下操作:

1

使用您想要检索的 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 获取一个。

2

要检索集合的所有 Atlas Search 索引,请执行以下操作:

1

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}"
2

要检索集群的所有 Atlas Search 索引:

1

要检索集群的索引,请将 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"
2

要使用 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 CLI 描述指定部署的指定搜索索引,请运行以下命令:

atlas deployments search indexes describe [indexId] [options]

要使用 Atlas CLI 列出指定部署的所有搜索索引,请运行以下命令:

atlas deployments search indexes list [options]

要进一步了解上一个命令的语法和参数,请参阅 Atlas CLI 文档 Atlas 部署搜索索引说明 Atlas 部署搜索索引列表。

提示

请参阅:相关链接

要查看Atlas 用户界面 Atlas Search 页面,请执行以下操作:

1

警告

导航改进正在进行中

我们目前正在推出改进的全新导航体验。如果以下步骤与Atlas用户界面中的视图不匹配,请参阅预览文档。

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

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

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

    会显示集群页面。

2

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

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

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

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

    将显示 Atlas Search 页面。

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

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

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

    将显示 Atlas Search 页面。

  1. 单击集群的名称。

  2. 单击 Atlas Search 标签页。

    将显示 Atlas Search 页面。

Atlas Search页面包含一个表,该表在以下列中描述了项目中每个现有的Atlas Search索引。

说明

Database

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

Collection

索引集合的名称。

Index Name

索引名称。

Status

集群主节点 (primary node in the replica set)节点上的索引状态。要学习;了解更多信息,请参阅Atlas Search索引状态。

Queryable

用于标识集合是否可使用索引进行查询的图标。值可以是以下图标之一:

  • - 用于可用于查询集合的索引。

  • X - 用于不能用于查询集合的索引。

Type

索引的类型。值可以是以下类型的索引之一:

Index Fields

索引字段。如果启用了动态映射,则值为dynamic 。对于静态映射,该列显示所有索引字段。

Documents

在集群的主节点或搜索节点上构建索引期间和之后,索引文档占集合中文档总数的近似数量和百分比。

Size

索引的大小。

Actions

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

  • 单击 Query ,进入 Search Tester ,用于查询集合。

  • 单击 并选择以下操作之一来处理索引:

默认下, Atlas首先按数据库名称,然后按集合名称对索引进行排序。要按多列排序,请按 Shift 并按照要对索引列表进行多重排序的顺序单击列名称。

从该表中,您可以转到以下部分,了解有关每个索引的更多详细信息:

要从 Atlas Search 页面转到 Index Overview 页面,请在 Index Name 列中单击要查看的索引名称。对于每个索引,Index Overview 页面显示索引的命名空间以及索引定义中指定的以下配置:

说明

索引分析器

选择文本分析器,用于指定在构建搜索索引时如何处理和标记化文本。

Search Analyzer

所选文本分析器,用于指定如何处理和标记搜索查询中的文本。

动态映射

布尔值,表示您为字段映射启用了动态还是静态映射

字段映射

任何指定的字段映射,包括字段名称、数据类型以及是否为单个字段启用动态映射

存储源字段

任何已定义的存储源字段

同义词映射

任何已定义的同义词映射

要通过 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 } }
}
]
1

打开Compass并连接到您的Atlas 集群。有关详细说明,请参阅通过Compass连接。

2

Database 屏幕上,单击数据库名称,然后单击集合名称。

3

页面显示以下内容:

列名称
说明

Name and Fields

索引的名称和索引字段的名称。

Type

索引类型。值可以是 SearchVector Search

Status

索引的状态。要学习;了解更多信息,请参阅查看索引状态。

操作

将鼠标悬停在索引上时可以对索引执行的操作。您可以执行以下操作:

  • 聚合 — 切换到 Aggregations标签页以使用索引运行查询。

  • — 编辑原始JSON格式的索引。

  • -删除索引。

要使用 C 驱动程序检索 Atlas Search 索引,请使用 mongoc_collection_aggregate() 方法创建一个包含 $listSearchIndexes 阶段的聚合管道。

1
2

以下示例应用程序指定聚合管道中的 $listSearchIndexes 阶段。然后,应用程序将管道和目标集合传递给 mongoc_collection_aggregate() 方法。此方法返回一个游标,代码可以从中访问并打印每个 Atlas Search 索引:

#include <mongoc/mongoc.h>
#include <stdlib.h>
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;
}
3
  • Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接

  • 您要检索索引的数据库和集合。

4
gcc -o view-index view-index.c $(pkg-config --libs --cflags libmongoc-1.0)
./view-index

要使用 C++ 驱动程序检索您的 Atlas 搜索索引,请在搜索索引视图上调用 list() 方法。

1
2

以下示例应用程序在目标集合上使用 search_indexes() 方法来实例化搜索索引视图。然后,应用程序会调用视图上的 list() 方法。此方法返回一个游标,代码从该游标访问并打印每个 Atlas Search 索引。

#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/search_index_view.hpp>
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;
}
3
  • Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接

  • 您要检索索引的数据库和集合。

4
g++ -o view-index view-index.cpp $(pkg-config --cflags --libs libmongocxx)
./view-index

要使用 .NET/C# 驱动程序检索 Atlas Search 索引,请使用 List()ListAsync() 方法。

以下示例应用程序返回集合上的索引。指定以下值:

  • Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接

  • 包含要检索的搜索索引的数据库和集合。

注意

List() 方法返回的是游标,而不是索引本身。要访问索引,请使用游标范例,例如 MoveNext() 方法。

Program.cs
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>

提示

API 文档

要了解有关本页方法的更多信息,请参阅 .NET/C# 驱动程序的 API 文档

要使用 Java 驱动程序检索集合上的 Atlas 搜索索引,请使用 listSearchIndexes() 方法。您必须有 Java 驱动程序 v 4.11.0 或更高版本。

1
2

以下示例应用程序检索给定集合上的所有 Atlas Search 索引。

1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoCursor;
5import com.mongodb.client.MongoDatabase;
6import org.bson.Document;
7public 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}
3
  • <connection-string> - Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接

  • <database-name> — 包含该集合的数据库的名称。

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

4
javac ViewIndex.java
java ViewIndex

另请参阅:

要通过节点驱动程序检索 Atlas Search 索引,请使用listSearchIndexes辅助方法。

您可以使用以下名为 list-indexes.js 的示例应用程序返回集合上的索引。指定以下值:

  • Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接

  • 包含要检索的搜索索引的数据库和集合。

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

注意

listSearchIndexes命令会返回一个游标。 因此,它不会立即返回与该命令匹配的索引。 要访问结果,请使用游标范例,例如toArray()方法。 要了解详情,请参阅从游标访问数据。

list-indexes.js
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() 方法。

1
2

下面的示例应用程序在一个集合上调用了 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)
3
  • Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接

  • 您要检索索引的数据库和集合。

4
python view_index.py

要恢复或删除在Atlas用户界面中保存为草稿的索引定义:

重要

在有待处理的索引草稿时,您无法创建新索引。

1

警告

导航改进正在进行中

我们目前正在推出改进的全新导航体验。如果以下步骤与Atlas用户界面中的视图不匹配,请参阅预览文档。

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

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

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

    会显示集群页面。

2

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

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

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

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

    将显示 Atlas Search 页面。

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

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

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

    将显示 Atlas Search 页面。

  1. 单击集群的名称。

  2. 单击 Atlas Search 标签页。

    将显示 Atlas Search 页面。

3
4
  1. 单击 Cancel(连接)。

  2. 点击 Save DraftDelete Draft

5
  1. 单击 Refine Your Index 以更改索引配置。

  2. 单击 Save Changes(连接)。

6

Atlas 会显示一个 Toast(简短的非交互式通知),以通知索引正在构建中。

7

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

注意

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

您可以更改现有 Atlas Search 索引的索引定义。您无法对索引进行重命名;如果需要更改索引名称,则必须创建新索引并删除旧索引。

您可以在Atlas用户界面中编辑Atlas Search索引,或者使用您的首选语言使用 mongosh、 Atlas CLI、 API或支持的MongoDB驱动程序以编程方式编辑 Atlas Search 索引。


➤ 使用选择语言下拉菜单设立本节中过程的语言。


要通过 API 编辑 Atlas Search 索引,请执行以下操作:

1

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 更新一个。

2

要使用 Atlas CLI 更新集群的搜索索引,请运行以下命令:

atlas clusters search indexes update <indexId> [options]

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

1

警告

导航改进正在进行中

我们目前正在推出改进的全新导航体验。如果以下步骤与Atlas用户界面中的视图不匹配,请参阅预览文档。

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

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

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

    会显示集群页面。

2

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

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

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

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

    将显示 Atlas Search 页面。

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

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

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

    将显示 Atlas Search 页面。

  1. 单击集群的名称。

  2. 单击 Atlas Search 标签页。

    将显示 Atlas Search 页面。

3
  • Edit With Visual Editor 以获取引导式体验。

  • Edit With JSON Editor 编辑原始索引定义。

4

检查以下索引配置设置:

可视化编辑器字段
说明
必要性

Index Analyzer

指定用于索引集合数据的分析器。默认情况下,Atlas Search 使用标准分析器 (lucene.standard)。

对应于 analyzer JSON 设置。

Optional

Search Analyzer

指定在搜索查询文本之前要应用到文本的分析器。如果省略此字段,则索引默认按以下顺序继承分析器:

  1. 该字段的 analyzer 选项(如果已指定)。

  2. 索引searchAnalyzer 选项(如果指定)。

  3. 索引analyzer 选项(如果指定)。

  4. lucene.standard 分析器。

对应于 searchAnalyzer JSON 设置。

Optional

Dynamic Mapping

指定字段的动态或静态映射。

默认下,启用动态映射。要禁用动态映射,请将 dynamic设立为 Off。如果禁用动态映射,则必须指定要索引的字段。

要学习;了解有关动态和静态映射的更多信息,请参阅定义字段映射。

对应于 mappings.dynamic JSON 设置。

必需

检查以下高级配置设置:

字段名称
说明
必要性

Field Mappings

如果 Index Configurations 部分中的 Dynamic Mapping 处于禁用状态,则为必填项。

指定要索引的字段:

  1. 点击 Add Field Mapping 打开 Add Field Mapping 窗口。

  2. 指定关于字段的以下信息:

    • Field name -要索引的字段名称。

    • Data Type - 字段数据类型。要详细了解支持的数据类型及其选项,请参阅数据类型。

  3. (可选)指定其他属性。

    其他配置选项表出现在 Add Field Mapping窗口中。这些属性取决于您在上一步中选择的数据类型。

    要详细了解支持的数据类型及其选项,请参阅数据类型。

  4. (可选)添加多字段。

    单击 Add Multi Field 配置备用字段分析器,用于索引字段。要学习;了解更多信息,请参阅多分析器。

  5. 单击 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 设置。

可选。

检查以下索引配置设置:

字段名称
说明
必要性

analyzer

指定用于索引集合数据的分析器。默认情况下,Atlas Search 使用标准分析器 (lucene.standard)。

Optional

searchAnalyzer

指定在搜索查询文本之前要应用到文本的分析器。如果省略此字段,则索引默认按以下顺序继承分析器:

  1. 该字段的 analyzer 选项(如果已指定)。

  2. 索引searchAnalyzer 选项(如果指定)。

  3. 索引analyzer 选项(如果指定)。

  4. lucene.standard 分析器。

Optional

mappings.dynamic

指定字段的动态或静态映射。要禁用动态映射,请将 "dynamic": 设立为 false。默认下,启用动态映射。如果禁用动态映射,则必须指定要索引的字段。要学习;了解有关动态和静态映射的更多信息,请参阅索引参考。

必需

检查以下高级配置设置:

字段名称
说明
必要性

mappings.fields

如果 mappings.dynamicfalse,则为必填项。

指定要编制索引的字段。要了解更多信息,请参阅定义字段映射。

可选的

storedSource

指定要在Atlas Search上存储以进行查询时查找的字段。您可以在Atlas Search上存储所有支持的数据类型的字段。

要了解有关存储字段的更多信息,请参阅在 Atlas Search 索引中定义存储的源字段

Optional

synonyms

指定要在索引中使用的同义词映射。

您可以使用同义词映射来仅查询使用同一分析器分析的字段。

要学习;了解有关同义词映射的更多信息,请参阅在Atlas Search索引中定义同义词映射。

Optional

numPartitions

字段对象超过 2.1 十亿时要使用的分区数。

可选。

要学习;了解有关这些索引定义设置的更多信息,请参阅索引参考。

5

索引的状态从 Active 变为 Building。在该状态下,您可以继续使用旧索引,因为在更新的索引可供使用之前,Atlas Search 不会删除旧索引。在状态恢复为 Active 后,就可以使用修改的索引了。

要通过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用户界面查看索引状态。

要使用MongoDB Compass编辑Atlas Search索引,请执行以下操作:

1
2
3
4

要使用C 驱动程序编辑 Atlas Search 索引,请在应用程序中指定更新的索引信息并调用 mongoc_collection_command_simple() 方法。

1
2

以下示例应用程序指定 updateSearchIndex 命令、更新的索引定义和现有索引名称。然后,应用程序将命令和更新的索引信息转换为 BSON ,并将此信息传递给 mongoc_collection_command_simple() 方法来编辑搜索索引。

#include <mongoc/mongoc.h>
#include <stdlib.h>
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;
}
3
  • Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接

  • 要更新索引的数据库和集合。

  • 要更新的索引的名称。

  • 用于重新定义搜索索引的字段。要学习;了解更多信息,请参阅索引参考。

4
gcc -o edit-index edit-index.c $(pkg-config --libs --cflags libmongoc-1.0)
./edit-index

要使用 C++ 驱动程序编辑 Atlas Search 索引,请在搜索索引视图上调用 update_one() 方法。

1
2

以下示例应用程序实例化搜索索引视图并指定新的 Atlas Search 索引定义。然后,应用程序将此定义和现有索引名称传递给 update_one() 方法,该方法将更新现有索引以反映新的定义文档。

#include <bsoncxx/builder/basic/document.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/search_index_view.hpp>
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;
}
3
  • Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接

  • 要更新索引的数据库和集合。

  • 要更新的索引的名称。

  • 用于重新定义搜索索引的字段。要学习;了解更多信息,请参阅索引参考。

4
g++ -o edit-index edit-index.cpp $(pkg-config --cflags --libs libmongocxx)
./edit-index

要使用 .NET/C# 驱动程序编辑 Atlas Search 索引,请使用 Update()UpdateAsync() 方法。

以下示例应用程序更新了现有索引定义。指定以下值:

  • Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接

  • 在其中创建搜索索引的数据库和集合。

  • 新的索引定义将替换现有定义。在示例中,您更新索引以使用静态映射。您可以更改此定义以满足您的特定索引需求。要学习;了解更多信息,请参阅索引参考。

  • 要更新的索引的名称。

Program.cs
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用户界面查看索引状态。

提示

API 文档

要了解有关本页方法的更多信息,请参阅 .NET/C# 驱动程序的 API 文档

要使用 Java 驱动程序编辑集合上的 Atlas Search 索引,请构建一个修改搜索索引设置的文档,然后将该文档传递给 updateSearchIndex() 方法。您必须有 Java 驱动程序 v 4.11.0 或更高版本。

1
2
1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoDatabase;
5import org.bson.Document;
6
7public class 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}
3
  • <connection-string> - Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接

    注意

    在连接字符串中,不要包含 writeConcern 设置。

  • <database-name> — 包含该集合的数据库的名称。

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

  • <analyzer-name> - 分析器的名称。

  • dynamic - 指示是否自动索引字段的标志。

  • <field-name> — 要索引的字段的名称。

  • <field-type> - 字段数据类型。

  • <index-name> - 索引名称。

4
javac EditIndex.java
java EditIndex

updateSearchIndex() 方法异步运行。使用 listSearchIndexes() 方法确定更改是否已应用于索引。要学习;了解有关检索Atlas Search索引的更多信息,请参阅查看Atlas Search索引。

另请参阅:

要通过节点驱动程序编辑 Atlas Search 索引,请使用 updateSearchIndex 辅助方法。

您可以使用以下名为 update-index.js 的示例应用程序更新现有索引定义。指定以下值:

  • Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接

  • 在其中创建搜索索引的数据库和集合。

  • 新的索引定义将替换现有定义。在示例中,您更新索引以使用静态映射。您可以更改此定义以满足您的特定索引需求。要学习;了解更多信息,请参阅索引参考。

  • 要更新的索引的名称。

update-index.js
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() 方法。

1
2

以下示例应用程序指定了新的 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)
3
  • Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接

  • 要更新索引的数据库和集合。

  • 要更新的索引的名称。

  • 用于重新定义搜索索引的字段。要学习;了解更多信息,请参阅索引参考。

4
python edit_index.py

注意

在构建更新后的索引时,不同节点的更新速度可能不同。在此期间,您可能会遇到混合查询结果,反映了新的索引定义和以前的索引定义。您可以在索引状态详细信息页面查看正在为查询提供服务的索引。

某些 Atlas Search 功能要求您更新索引。 要更新索引,可以执行以下操作之一:

  • 使用编辑Atlas Search索引中的步骤编辑索引定义。

  • 请执行以下步骤,选择从Atlas用户界面进行索引更新:

重要

更新 Atlas Search 索引的过程需要时间和资源。要成功完成索引更新,请分配等于当前索引磁盘空间 125% 的可用磁盘空间。

1

警告

导航改进正在进行中

我们目前正在推出改进的全新导航体验。如果以下步骤与Atlas用户界面中的视图不匹配,请参阅预览文档。

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

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

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

    会显示集群页面。

2

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

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

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

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

    将显示 Atlas Search 页面。

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

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

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

    将显示 Atlas Search 页面。

  1. 单击集群的名称。

  2. 单击 Atlas Search 标签页。

    将显示 Atlas Search 页面。

3

提示

如果索引需要更新才能启用新功能,Atlas 用户界面会在索引名称旁边显示一个警告图标。

4
  1. Index Overview 页面中,点击横幅中的 Update

  2. 单击确认窗口中的 Update Index

    更新索引时,您可以继续使用以前的索引查询集合。

您可以在Atlas用户界面中删除Atlas Search索引,也可以使用 mongosh、 Atlas CLI、 API或您首选语言支持的MongoDB驱动程序以编程方式删除 Atlas Search 索引。


➤ 使用选择语言下拉菜单设立本节中过程的语言。


要通过 API 删除 Atlas Search 索引,请执行以下操作:

1

使用您要删除的 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}"

要进一步了解任一端点的语法和参数,请参阅按名称删除一个按 ID 删除一个

2

要使用 Atlas CLI 从集群中删除搜索索引,请运行以下命令:

atlas clusters search indexes delete <indexId> [options]

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

要使用 Atlas CLI 删除指定部署的指定搜索索引,请运行以下命令:

atlas deployments search indexes delete <indexId> [options]

要了解有关命令语法和参数的更多信息,请参阅Atlas CLI AtlasAtlas Search部署 索引删除 的 文档。

1

警告

导航改进正在进行中

我们目前正在推出改进的全新导航体验。如果以下步骤与Atlas用户界面中的视图不匹配,请参阅预览文档。

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

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

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

    会显示集群页面。

2

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

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

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

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

    将显示 Atlas Search 页面。

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

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

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

    将显示 Atlas Search 页面。

  1. 单击集群的名称。

  2. 单击 Atlas Search 标签页。

    将显示 Atlas Search 页面。

3

ellipsis按钮位于面板右侧。 单击所需索引旁边的按钮并选择Delete Index

4

要通过 mongosh 删除 Atlas Search 索引,请使用 db.collection.dropSearchIndex() 方法。

该命令具有以下语法:

db.<collection>.dropSearchIndex("<index-name>")

以下命令从 movies 集合中删除名为 default 的搜索索引:

db.movies.dropSearchIndex("default")

注意

db.collection.dropSearchIndex() 命令不返回输出。您可以使用Atlas用户界面查看索引状态。

要使用MongoDB Compass删除Atlas Search索引,请执行以下操作:

1
2
3
4

要使用 C 驱动程序删除您的 Atlas Search 索引,请将您的集合和 drop 命令传递给 mongoc_collection_command_simple() 方法。

1
2

以下示例应用程序指定 dropSearchIndex 命令和现有索引名称。然后,应用程序将命令和索引信息转换为 BSON,并将此信息传递给 mongoc_collection_command_simple() 方法以删除搜索索引。

#include <mongoc/mongoc.h>
#include <stdlib.h>
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;
}
3
  • Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接

  • 您要删除索引的数据库和集合。

  • 要删除的索引的名称。

4
gcc -o delete-index delete-index.c $(pkg-config --libs --cflags libmongoc-1.0)
./delete-index

要使用 C++ 驱动程序删除 Atlas Search 索引,请在搜索索引视图上调用 drop_one() 方法。

1
2

以下示例应用程序在目标集合上使用 search_indexes() 方法来实例化搜索索引视图。然后,应用程序在视图上调用 drop_one() 方法,并将 Atlas Search 索引名称作为参数传递给该索引,以删除该索引。

#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/search_index_view.hpp>
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;
}
3
  • Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接

  • 您要检索索引的数据库和集合。

  • 要删除的索引的名称。

4
g++ -o delete-index delete-index.cpp $(pkg-config --cflags --libs libmongocxx)
./delete-index

要使用 .NET/C# 驱动程序删除 Atlas Search 索引,请使用 DropOne()DropOneAsync() 方法。

以下示例应用程序从集合中删除索引。指定以下值:

  • Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接

  • 包含您要删除的搜索索引的数据库和集合。

  • 要删除的搜索索引的名称。

Program.cs
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用户界面查看索引状态。

提示

API 文档

要了解有关本页方法的更多信息,请参阅 .NET/C# 驱动程序的 API 文档

要使用Java 驱动程序删除集合上的 Atlas Search 索引,请使用 dropSearchIndex() 方法。您必须有 Java 驱动程序 v 4.11.0 或更高版本。

1
2

以下示例应用程序删除指定集合上的指定 Atlas Search 索引。

1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoDatabase;
5import org.bson.Document;
6
7public class DeleteIndex {
8 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}
3
  • <connection-string> - Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接

    注意

    在连接字符串中,不要包含 writeConcern 设置。

  • <database-name> — 包含该集合的数据库的名称。

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

  • <index-name> - 要删除的索引的名称。

4
javac DeleteIndex.java
java DeleteIndex

另请参阅:

要通过节点驱动程序删除 Atlas Search 索引,请使用dropSearchIndex辅助方法。

您可以使用以下名为drop-index.js的示例应用程序来删除集合上的索引。 指定以下值:

  • Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接

  • 在其中创建搜索索引的数据库和集合。

  • 要删除的索引的名称。

drop-index.js
// 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() 方法。

1
2

以下示例应用程序将 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>")
3
  • Atlas 连接字符串。要了解更多信息,请参阅通过驱动程序连接

  • 您要删除索引的数据库和集合。

  • 要删除的索引的名称。

4
python delete_index.py

mongot进程将索引字段和 _id字段存储在磁盘上,因此您可能需要在构建索引之前调整索引的大小。您可以估计完整Atlas Search索引的大小,方法是在集合的子集上创建索引,并使用以下公式根据数据的总大小扩展示例数据索引的大小:

estimated-index-size = ( subset-data-index-size / subset-data-size ) x total-collection-data-size

示例,如果要估计movies sample_mflix数据库中 集合的索引大小,请执行mongosh 中的以下步骤:

  1. 运行 $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'
    }
    ]
  2. 使用要用于完整集合的索引定义,在包含示例数据的集合上创建搜索索引:

    db.sample_data.createSearchIndex(
    "sample-index",
    { mappings: { dynamic: true } }
    )
    sample-index
  3. 将示例数据的大小按集合的总大小进行缩放。示例,如果 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 正在构建索引或在编辑后重新构建索引。当该索引处于以下状态时:

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

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

Ready(就绪)

索引已准备就绪。

Stale

由于以下任一原因,索引已过时:

  • 由于磁盘利用率较高,复制已停止。

    暂停复制阈值为 90% 磁盘利用率,恢复复制的阈值为 85%。

  • 如果复制长时间停止,Atlas Search mongot 进程将从 oplog 中消失。

    若当前复制点在 mongod oplog 上不再可用,通常会出现此状态。如果 oplog 的 mongot 进程消失,Atlas 会重建索引。

  • 索引已达到 20 亿文档限制。

  • 复制因错误而失败。

您仍然可以查询现有索引。但是,针对过时索引的查询结果可能包含过时数据。您可以扩容搜索节点以获得更多磁盘空间,并删除现有索引以释放磁盘空间。或者,使用 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

索引状态的原因。对于处于 StaleFailed 状态的索引,显示索引过时或索引构建失败的原因。

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

索引字段。如果启用了动态映射,则值为dynamic 。对于静态映射,该列显示所有索引字段。

Type

索引的类型。值可以是以下类型的索引之一:

Status

Size

索引的大小。

Documents

迁移期间和之后,集群搜索节点上已建立索引的文档在集合中文档总数中所占的比例。

状态列显示搜索节点上索引的以下状态之一:

状态
说明

构建

当前正在搜索节点上构建索引。在构建新索引时,您的查询可以继续使用现有索引。

On Deck

索引已在搜索节点上成功构建,但迁移尚未完成。请注意,只有当 Atlas 在 Search 节点上成功构建所有索引时,迁移才算完成。

Ready(就绪)

搜索节点上的索引已准备好用于查询。仅当 Atlas 成功完成到搜索节点的迁移时才会显示。

已失败

索引构建失败,迁移到单独的搜索节点时停止。您的查询可以继续使用现有索引。Atlas 将尝试重建索引,但会在 7 天后超时。

要成功迁移,请在“按节点列出的状态详细信息” Message列或索引的Status Details 页面中查看索引的错误消息,并解决导致在搜索节点上构建索引失败的问题。

您的查询可以继续使用现有索引,同时在搜索节点上构建新索引。仅当Atlas成功在搜索节点上构建所有索引时,才能完成向搜索节点的迁移。然后,您的查询将自动路由到使用搜索节点上的索引。

要学习;了解如何定义Atlas Search索引以满足Atlas Search查询需求,请参阅定义查询。

要学习;了解如何创建Atlas Search索引,请参阅创建Atlas Search索引。

要学习;了解有关本教程中描述的Atlas Search索引配置的更多信息,请参阅以下参考页面:

如需亲身体验为示例数据集创建Atlas Search索引以及对索引数据运行Atlas Search查询,请尝试Atlas Search快速入门。

本视频教程演示如何创建不同复杂程度的 Atlas Search 索引。

时长:15 分钟

后退

查询和索引

在此页面上