

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 分析 Amazon DocumentDB 操作
<a name="profiling"></a>

可以使用 Amazon DocumentDB（与 MongoDB 兼容）中的分析器来记录在您集群上执行的操作的执行时间和详细信息。对于监控集群上速度最慢的操作以帮助您提高单个查询的性能和整体集群性能，分析器非常有用。

默认情况下，分析器功能处于禁用状态。启用后，Profiler 会将花费超过客户定义的阈值（例如 100 毫秒）的操作记录到 Ama CloudWatch zon Logs 中。记录的详细信息包括分析的命令、时间、计划摘要和客户端元数据。将操作记录到 CloudWatch 日志后，您可以使用 CloudWatch Logs Insights 来分析、监控和存档您的 Amazon DocumentDB 分析数据。[常见查询](#profiling.common-queries) 部分中提供了常见的查询。

在启用时，分析器会使用集群中的其他资源。我们建议您从较高的阈值（例如，500 毫秒）开始，然后逐步降低该值以确定缓慢的操作。对于高吞吐量应用程序，从 50 毫秒阈值开始会导致集群性能问题。分析器在集群级别启用，并对集群中的所有实例和数据库执行分析。Amazon DocumentDB 会尽力将操作记录到亚马逊 CloudWatch 日志。

尽管 Amazon DocumentDB 不会为启用分析器收取任何额外费用，但您需要按标准费率支付日志使用费。 CloudWatch 有关 CloudWatch 日志定价的信息，请参阅 [Amazon CloudWatch 定价](https://aws.amazon.com/cloudwatch/pricing/)。

**Topics**
+ [支持的操作](#profiling.supported-commands)
+ [限制](#profiling.limitations)
+ [启用分析器](#profiling.enable-profiling)
+ [禁用分析器](#profiling.disable-profiling)
+ [禁用分析器日志导出](#profiling.disabling-logs-export)
+ [访问分析器日志](#profiling.accessing)
+ [常见查询](#profiling.common-queries)

## 支持的操作
<a name="profiling.supported-commands"></a>

Amazon DocumentDB 分析器支持以下操作：
+ `aggregate`
+ `count`
+ `delete`
+ `distinct`
+ `find`（OP\$1QUERY 和命令）
+ `findAndModify`
+ `insert`
+ `update`

## 限制
<a name="profiling.limitations"></a>

仅当查询的整个结果集能够容纳在一个批处理中，并且结果集小于 16MB（最大 BSON 大小）时，慢速查询分析器才能够生成分析器日志。大于 16MB 的结果集会自动拆分为多个批处理。

大多数驱动程序或 Shell 可能会设置一个较小的默认批处理大小。您可以在查询中指定批处理大小。为了捕获慢速查询日志，我们建议设置一个超过您预期结果集大小的批处理大小。如果不确定结果集大小，或者结果集大小不同，也可以将批处理大小设置为较大的数字（例如，100k）。

但是，使用较大的批大小意味着在将响应发送到客户端之前，必须从数据库中检索更多结果。对于某些查询，这可能会在获得结果之前造成更长的延迟。如果您不打算使用整个结果集，则可能会花更多的钱 I/Os 来处理查询并丢弃结果。

## 启用 Amazon DocumentDB 分析器
<a name="profiling.enable-profiling"></a>

在集群上启用分析器的过程包含三个步骤。确保所有步骤都已完成，否则分析日志将不会发送到 CloudWatch 日志。分析器在集群级别设置，对集群的所有数据库和实例执行分析。

**在集群上启用分析器**

1. 由于您无法修改默认集群参数组，请确保您有可用的自定义集群参数组。有关更多信息，请参阅 [创建 Amazon DocumentDB 集群参数组](cluster_parameter_groups-create.md)。

1. 使用可用的自定义集群参数组，修改以下参数：`profiler`、`profiler_threshold_ms` 和 `profiler_sampling_rate`。有关更多信息，请参阅 [修改 Amazon DocumentDB 集群参数组](cluster_parameter_groups-modify.md)。

1. 创建或修改您的集群以使用自定义集群参数组并启用将`profiler`日志导出到 CloudWatch 日志的功能。

以下各节介绍如何使用 AWS 管理控制台 和 AWS Command Line Interface (AWS CLI) 实现这些步骤。

------
#### [ Using the AWS 管理控制台 ]

1. 开始之前，请先创建一个 Amazon DocumentDB 集群和一个自定义集群参数组（如果您还没有）。有关更多信息，请参阅[创建 Amazon DocumentDB 集群参数组](cluster_parameter_groups-create.md)和[创建 Amazon DocumentDB 集群](db-cluster-create.md)。

1. 使用可用的自定义集群参数组，修改以下参数。有关更多信息，请参阅 [修改 Amazon DocumentDB 集群参数组](cluster_parameter_groups-modify.md)。
   + `profiler`：启用或禁用查询分析。允许的值为 `enabled ` 和 `disabled`。默认值为 `disabled`。要启用分析，请将值设置为 `enabled`。
   + `profiler_threshold_ms`— 如果设置`profiler`为`enabled`，则所有花费时间超过其时间的命令` profiler_threshold_ms`都将被记录到 CloudWatch。允许的值为 `[50-INT_MAX]`。默认值为 `100`。
   + `profiler_sampling_rate`：应该分析或记录的缓慢操作的部分。允许的值为 `[0.0-1.0]`。默认值为 `1.0`。

1. 修改您的集群以使用自定义集群参数组，并将分析器日志导出设置为发布到 Amazon CloudWatch。

   1. 在导航窗格中，选择 **Clusters (集群)** 以将自定义参数组添加到集群。

   1. 选择要与您的参数组关联的集群名称左边的按钮。选择 **Actions (操作)**，然后选择 **Modify (修改)** 以修改您的集群。

   1. 在 **Cluster options (集群选项)** 下，选择上一步中的自定义参数组以将其添加到集群中。

   1. 在 “**日志导出**” 下，选择要发布到 Amazon CloudWatch 的 **Profiler 日志**。

   1. 选择 **Continue (继续)** 以查看修改摘要。

   1. 在确认您的更改后，您可以立即应用这些更改，也可以在 **Scheduling of modifications (修改计划)** 下的下一个维护时段内应用这些更改。

   1. 选择 **Modify cluster (修改集群)** 以使用新参数组更新您的集群。

------
#### [ Using the AWS CLI ]

以下过程对集群 `sample-cluster` 上的所有支持操作启用分析器。

1. 在开始之前，请运行以下命令，并查看对于名称中不包含 `default` 且具有 `docdb3.6` 作为参数组系列的集群参数组的输出，以确保您拥有可用的自定义集群参数组。如果您没有非默认集群参数组，请参阅[创建 Amazon DocumentDB 集群参数组](cluster_parameter_groups-create.md)。

   ```
   aws docdb describe-db-cluster-parameter-groups \
       --query 'DBClusterParameterGroups[*].[DBClusterParameterGroupName,DBParameterGroupFamily]'
   ```

   在以下输出中，仅 `sample-parameter-group ` 满足这两个条件。

   ```
   [
          [
              "default.docdb3.6",
              "docdb3.6"
          ],
          [
              "sample-parameter-group",
              "docdb3.6"
          ]
   ]
   ```

1. 使用您的自定义集群参数组，修改以下参数。
   + `profiler`：启用或禁用查询分析。允许的值为 `enabled ` 和 `disabled`。默认值为 `disabled`。要启用分析，请将值设置为 `enabled`。
   + `profiler_threshold_ms`— 如果设置`profiler`为`enabled`，则所有命令花费的时间`profiler_threshold_ms`都超过了记录到的时间 CloudWatch。允许的值为 `[50-INT_MAX]`。默认值为 `100`。
   + `profiler_sampling_rate`：应该分析或记录的缓慢操作的部分。允许的值为 `[0.0-1.0]`。默认值为 `1.0`。

   ```
   aws docdb modify-db-cluster-parameter-group \
       --db-cluster-parameter-group-name sample-parameter-group \
       --parameters ParameterName=profiler,ParameterValue=enabled,ApplyMethod=immediate \
                    ParameterName=profiler_threshold_ms,ParameterValue=100,ApplyMethod=immediate \
                    ParameterName=profiler_sampling_rate,ParameterValue=0.5,ApplyMethod=immediate
   ```

1. 修改您的 Amazon DocumentDB 集群，使其使用上一步中提到的 `sample-parameter-group` 自定义集群参数组，并将参数 `--enable-cloudwatch-logs-exports` 设置为 `profiler`。

   以下代码修改群集`sample-cluster`以使用上一步`sample-parameter-group`中的，并`profiler`添加到已启用的 CloudWatch 日志导出中。

   ```
   aws docdb modify-db-cluster \
          --db-cluster-identifier sample-cluster \
          --db-cluster-parameter-group-name sample-parameter-group \
          --cloudwatch-logs-export-configuration '{"EnableLogTypes":["profiler"]}'
   ```

   此操作的输出将类似于下文。

   ```
   {
       "DBCluster": {
           "AvailabilityZones": [
               "us-east-1c",
               "us-east-1b",
               "us-east-1a"
           ],
           "BackupRetentionPeriod": 1,
           "DBClusterIdentifier": "sample-cluster",
           "DBClusterParameterGroup": "sample-parameter-group",
           "DBSubnetGroup": "default",
           "Status": "available",
           "EarliestRestorableTime": "2020-04-07T02:05:12.479Z",
           "Endpoint": "sample-cluster.node.us-east-1.docdb.amazonaws.com",
           "ReaderEndpoint": "sample-cluster.node.us-east-1.docdb.amazonaws.com",
           "MultiAZ": false,
           "Engine": "docdb",
           "EngineVersion": "3.6.0",
           "LatestRestorableTime": "2020-04-08T22:08:59.317Z",
           "Port": 27017,
           "MasterUsername": "test",
           "PreferredBackupWindow": "02:00-02:30",
           "PreferredMaintenanceWindow": "tue:09:50-tue:10:20",
           "DBClusterMembers": [
               {
                   "DBInstanceIdentifier": "sample-instance-1",
                   "IsClusterWriter": true,
                   "DBClusterParameterGroupStatus": "in-sync",
                   "PromotionTier": 1
               },
               {
                   "DBInstanceIdentifier": "sample-instance-2",
                   "IsClusterWriter": true,
                   "DBClusterParameterGroupStatus": "in-sync",
                   "PromotionTier": 1
               }
           ],
           "VpcSecurityGroups": [
               {
                   "VpcSecurityGroupId": "sg-abcd0123",
                   "Status": "active"
               }
           ],
           "HostedZoneId": "ABCDEFGHIJKLM",
           "StorageEncrypted": true,
           "KmsKeyId": "arn:aws:kms:us-east-1:<accountID>:key/sample-key",
           "DbClusterResourceId": "cluster-ABCDEFGHIJKLMNOPQRSTUVWXYZ",
           "DBClusterArn": "arn:aws:rds:us-east-1:<accountID>:cluster:sample-cluster",
           "AssociatedRoles": [],
           "ClusterCreateTime": "2020-01-10T22:13:38.261Z",
           "EnabledCloudwatchLogsExports": [
               "profiler"
           ],
           "DeletionProtection": true
       }
   }
   ```

------

## 禁用 Amazon DocumentDB 分析器
<a name="profiling.disable-profiling"></a>

要禁用探查器，您可以禁用`profiler`参数和将日志导出到`profiler`日 CloudWatch 志。

### 禁用分析器
<a name="profiling.disable-profiler"></a>

您可以使用 AWS 管理控制台 或禁用该`profiler`参数 AWS CLI，如下所示。

------
#### [ Using the AWS 管理控制台 ]

以下过程使用来禁用 Amazon Documen `profiler` tDB。 AWS 管理控制台 

1. [登录 AWS 管理控制台，然后在 /docdb 上打开亚马逊文档数据库控制台。https://console.aws.amazon.com](https://console.aws.amazon.com/docdb)

1. 在导航窗格中，选择**参数组**。然后选择您要在其上禁用分析器的集群参数组的名称。

1. 在生成的 **Cluster parameters (集群参数)** 页面中，选择 `profiler` 参数左侧的按钮，然后选择 **Edit (编辑)**。

1. 在 **Modify Profiler (修改分析器)** 对话框中，在列表中选择 `disabled`。

1. 选择 **Modify cluster parameter (修改集群参数)**。

------
#### [ Using the AWS CLI ]

要使用 AWS CLI在集群上禁用 `profiler`，请如下所示修改集群。

```
aws docdb modify-db-cluster-parameter-group \
    --db-cluster-parameter-group-name sample-parameter-group \
    --parameters ParameterName=profiler,ParameterValue=disabled,ApplyMethod=immediate
```

------

## 禁用分析器日志导出
<a name="profiling.disabling-logs-export"></a>

您可以使用 AWS 管理控制台 或禁用将`profiler` CloudWatch 日志导出到日志 AWS CLI，如下所示。

------
#### [ Using the AWS 管理控制台 ]

以下过程使用禁用 Amazon DocumentDB AWS 管理控制台 将日志导出到。 CloudWatch

1. [在 /docdb 上打开亚马逊 DocumentDB 控制台。https://console.aws.amazon.com](https://console.aws.amazon.com/docdb)

1. 在导航窗格中，选择**集群**。选择要禁用导出日志的集群名称左侧的按钮。

1. 在 **Actions (操作)** 菜单上，选择 **Modify (修改)**。

1. 向下滚动到 **Log exports (日志导出)** 部分并取消选择 **Profiler logs (分析器日志)**。

1. 选择**继续**。

1. 检查更改，然后选择何时将该更改应用到集群：
   + **Apply during the next scheduled maintenance window (在下一个计划的维护时段内应用)**
   + **Apply immediately (立即应用)**

1. 选择**修改集群**。

------
#### [ Using the AWS CLI ]

以下代码修改集群`sample-cluster `并禁用 CloudWatch 探查器日志。

**Example**  
对于 Linux、macOS 或 Unix：  

```
aws docdb modify-db-cluster \
   --db-cluster-identifier sample-cluster \
   --cloudwatch-logs-export-configuration '{"DisableLogTypes":["profiler"]}'
```
对于 Windows：  

```
aws docdb modify-db-cluster ^
   --db-cluster-identifier sample-cluster ^
   --cloudwatch-logs-export-configuration '{"DisableLogTypes":["profiler"]}'
```
此操作的输出将类似于下文。  

```
{
    "DBCluster": {
        "AvailabilityZones": [
            "us-east-1c",
            "us-east-1b",
            "us-east-1a"
        ],
        "BackupRetentionPeriod": 1,
        "DBClusterIdentifier": "sample-cluster",
        "DBClusterParameterGroup": "sample-parameter-group",
        "DBSubnetGroup": "default",
        "Status": "available",
        "EarliestRestorableTime": "2020-04-08T02:05:17.266Z",
        "Endpoint": "sample-cluster.node.us-east-1.docdb.amazonaws.com",
        "ReaderEndpoint": "sample-cluster.node.us-east-1.docdb.amazonaws.com",
        "MultiAZ": false,
        "Engine": "docdb",
        "EngineVersion": "3.6.0",
        "LatestRestorableTime": "2020-04-09T05:14:44.356Z",
        "Port": 27017,
        "MasterUsername": "test",
        "PreferredBackupWindow": "02:00-02:30",
        "PreferredMaintenanceWindow": "tue:09:50-tue:10:20",
        "DBClusterMembers": [
            {
                "DBInstanceIdentifier": "sample-instance-1",
                "IsClusterWriter": true,
                "DBClusterParameterGroupStatus": "in-sync",
                "PromotionTier": 1
            },
            {
                "DBInstanceIdentifier": "sample-instance-2",
                "IsClusterWriter": true,
                "DBClusterParameterGroupStatus": "in-sync",
                "PromotionTier": 1
            }
        ],
        "VpcSecurityGroups": [
            {
                "VpcSecurityGroupId": "sg-abcd0123",
                "Status": "active"
            }
        ],
        "HostedZoneId": "ABCDEFGHIJKLM",
        "StorageEncrypted": true,
        "KmsKeyId": "arn:aws:kms:us-east-1:<accountID>:key/sample-key",
        "DbClusterResourceId": "cluster-ABCDEFGHIJKLMNOPQRSTUVWXYZ",
        "DBClusterArn": "arn:aws:rds:us-east-1:<accountID>:cluster:sample-cluster",
        "AssociatedRoles": [],
        "ClusterCreateTime": "2020-01-10T22:13:38.261Z",
        "DeletionProtection": true
    }
}
```

------

## 访问您的 Amazon DocumentDB 分析器日志
<a name="profiling.accessing"></a>

按照以下步骤访问您在Amazon上的个人资料日志 CloudWatch。

1. 打开 CloudWatch 控制台，网址为[https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/)。

1. 确保您与 Amazon DocumentDB 集群位于同一区域。

1. 在导航窗格中，选择**日志**。

1. 要查找集群的分析器日志，请在列表中选择 `/aws/docdb/yourClusterName/profiler`。

   此时，每个实例名称的下方将显示该实例的分析日志。

## 常见查询
<a name="profiling.common-queries"></a>

以下是您可以用来分析您的已分析命令的常见查询。有关 [Lo CloudWatch gs Insights 的更多信息，请参阅使用 CloudWatch 日志见解和[示例查询](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_QuerySyntax-examples.html)分析日志数据](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AnalyzingLogData.html)。

### 获取指定集合上最慢的 10 个操作
<a name="profiling.common-queries.slow-queries-on-collection"></a>

```
filter ns="test.foo" | sort millis desc | limit 10
```

### 获取集合上用时超过 60 毫秒的所有更新操作
<a name="profiling.common-queries.updates-gt-60-ms"></a>

```
filter millis > 60 and op = "update"
```

### 获取上个月最慢的 10 个操作
<a name="profiling.common-queries.slow-queries-last-month"></a>

```
sort millis desc | limit 10
```

### 获取具有 COLLSCAN 计划摘要的所有查询
<a name="profiling.common-queries.collscan-plan-summary"></a>

```
filter planSummary="COLLSCAN"
```