

# 使用分析工具查询 S3 Storage Lens 存储统计管理工具数据
<a name="storage-lens-s3-tables-querying"></a>

在使用诸如 Amazon Athena 或 Amazon EMR 之类的 Amazon 分析服务查询导出到 S3 表类数据存储服务的 S3 Storage Lens 存储统计管理工具数据之前，必须对 Amazon 托管的“aws-s3”表存储桶启用分析集成并配置 Amazon Lake Formation 权限。

**重要**  
在“aws-s3”表存储桶上启用分析集成是必需的步骤，但经常遭遗漏。如果没有此配置，您将无法使用 Amazon 分析服务查询 S3 Storage Lens 存储统计管理工具表。

## 先决条件
<a name="storage-lens-s3-tables-querying-prerequisites"></a>

在开始之前，请确保您满足以下条件：
+ 具有启用了 S3 表类数据存储服务导出的 S3 Storage Lens 存储统计管理工具配置。有关更多信息，请参阅 [将 S3 Storage Lens 存储统计管理工具指标导出到 S3 表类数据存储服务](storage-lens-s3-tables-export.md)。
+ 具有访问 Amazon Athena 或其它分析服务的权限。
+ 启用导出后等待 24-48 小时，第一批数据才可用。

## 集成概述
<a name="storage-lens-s3-tables-querying-integration-overview"></a>

有关将 S3 表类数据存储服务与 Amazon 分析服务集成的详细信息（包括先决条件、IAM 角色配置和分步过程），请参阅[将 Amazon S3 表类数据存储服务与 Amazon 分析服务集成](https://docs.amazonaws.cn/AmazonS3/latest/userguide/s3-tables-integrating-aws.html)。

启用 S3 表类数据存储服务并设置分析集成后，可以使用诸如 Amazon Athena、Amazon Redshift 和 Amazon EMR 等 Amazon 分析服务查询 S3 Storage Lens 存储统计管理工具数据。这使您能够使用标准 SQL 执行自定义分析、创建控制面板，并从存储数据中获取见解。

## 使用 Amazon Athena 进行查询
<a name="storage-lens-s3-tables-querying-athena"></a>

Amazon Athena 是一种无服务器交互式查询服务，方便使用标准 SQL 分析数据。使用以下步骤在 Athena 中查询 S3 Storage Lens 存储统计管理工具数据。

**注意**  
在所有查询示例中，将 `lens_my-config_exp` 替换为实际的 Storage Lens 存储统计管理工具配置命名空间。有关命名空间命名的更多信息，请参阅 [S3 Storage Lens 存储统计管理工具导出到 S3 表类数据存储服务的表命名](storage-lens-s3-tables-naming.md)。

### 示例：查询排名靠前的存储使用者
<a name="storage-lens-s3-tables-querying-athena-top-consumers"></a>

以下查询按存储消耗量确定排名靠前的 10 个存储桶：

```
SELECT 
    bucket_name,
    storage_class,
    SUM(storage_bytes) / POWER(1024, 3) AS storage_gb,
    SUM(object_count) AS objects
FROM "s3tablescatalog/aws-s3"."lens_my-config_exp"."default_storage_metrics"
WHERE report_time = (
    SELECT MAX(report_time) 
    FROM "s3tablescatalog/aws-s3"."lens_my-config_exp"."default_storage_metrics"
)
    AND record_type = 'BUCKET'
    AND bucket_name != ''
GROUP BY bucket_name, storage_class
ORDER BY storage_gb DESC
LIMIT 10
```

### 示例：分析一段时间内的存储增长
<a name="storage-lens-s3-tables-querying-athena-growth"></a>

以下查询分析过去 30 天的存储增长情况：

```
SELECT 
    CAST(report_time AS date) AS report_date,
    SUM(storage_bytes) / POWER(1024, 3) AS total_storage_gb
FROM "s3tablescatalog/aws-s3"."lens_my-config_exp"."default_storage_metrics"
WHERE report_time >= current_date - interval '30' day
    AND record_type = 'ACCOUNT'
GROUP BY CAST(report_time AS date)
ORDER BY report_date DESC;
```

### 示例：识别未完成的分段上传
<a name="storage-lens-s3-tables-querying-athena-mpu"></a>

以下查询查找具有超过 7 天的未完成分段上传的存储桶：

```
SELECT 
    bucket_name,
    SUM(incomplete_mpu_storage_older_than_7_days_bytes) / POWER(1024, 3) AS wasted_storage_gb,
    SUM(incomplete_mpu_object_older_than_7_days_count) AS wasted_objects
FROM "s3tablescatalog/aws-s3"."lens_my-config_exp"."default_storage_metrics"
WHERE report_time = (
    SELECT MAX(report_time) 
    FROM "s3tablescatalog/aws-s3"."lens_my-config_exp"."default_storage_metrics"
)
    AND record_type = 'BUCKET'
    AND incomplete_mpu_storage_older_than_7_days_bytes > 0
GROUP BY bucket_name
ORDER BY wasted_storage_gb DESC;
```

### 示例：查找冷数据候选对象
<a name="storage-lens-s3-tables-querying-athena-cold-data"></a>

以下查询可识别存储在热存储层中的过去 100 天内没有任何活动的前缀：

```
WITH recent_activity AS (
    SELECT DISTINCT 
        bucket_name,
        record_value AS prefix_path
    FROM "s3tablescatalog/aws-s3"."lens_my-config_exp"."expanded_prefixes_activity_metrics"
    WHERE report_time >= current_date - interval '100' day
        AND record_type = 'PREFIX'
        AND all_request_count > 0
)
SELECT 
    s.bucket_name,
    s.record_value AS prefix_path,
    s.storage_class,
    SUM(s.storage_bytes) / POWER(1024, 3) AS storage_gb
FROM "s3tablescatalog/aws-s3"."lens_my-config_exp"."expanded_prefixes_storage_metrics" s
LEFT JOIN recent_activity r 
    ON s.bucket_name = r.bucket_name 
    AND s.record_value = r.prefix_path
WHERE s.report_time = (
    SELECT MAX(report_time) 
    FROM "s3tablescatalog/aws-s3"."lens_my-config_exp"."expanded_prefixes_storage_metrics"
)
    AND s.record_type = 'PREFIX'
    AND s.storage_class IN ('STANDARD', 'REDUCED_REDUNDANCY')
    AND s.storage_bytes > 1073741824  -- > 1GB
    AND r.prefix_path IS NULL  -- No recent activity
GROUP BY s.bucket_name, s.record_value, s.storage_class
ORDER BY storage_gb DESC
LIMIT 20;
```

### 示例：分析请求模式
<a name="storage-lens-s3-tables-querying-athena-requests"></a>

以下查询分析请求模式以了解访问频率：

```
SELECT 
    bucket_name,
    SUM(all_request_count) AS total_requests,
    SUM(get_request_count) AS get_requests,
    SUM(put_request_count) AS put_requests,
    ROUND(100.0 * SUM(get_request_count) / NULLIF(SUM(all_request_count), 0), 2) AS get_percentage,
    SUM(downloaded_bytes) / POWER(1024, 3) AS downloaded_gb
FROM "s3tablescatalog/aws-s3"."lens_my-config_exp"."default_activity_metrics"
WHERE report_time >= current_date - interval '7' day
    AND record_type = 'BUCKET'
    AND bucket_name != ''
GROUP BY bucket_name
HAVING SUM(all_request_count) > 0
ORDER BY total_requests DESC
LIMIT 10;
```

## 在 Amazon EMR 上使用 Apache Spark 进行查询
<a name="storage-lens-s3-tables-querying-emr"></a>

Amazon EMR 提供托管式 Hadoop 框架，便于轻松地使用 Apache Spark 处理大量数据。可以使用 Iceberg 连接器直接读取 S3 Storage Lens 存储统计管理工具表。

### 使用 Spark 读取 S3 表类数据存储服务
<a name="storage-lens-s3-tables-querying-emr-spark"></a>

使用以下 Python 代码通过 Spark 读取 S3 Storage Lens 存储统计管理工具数据：

```
from pyspark.sql import SparkSession

spark = SparkSession.builder \
    .appName("S3StorageLensAnalysis") \
    .config("spark.sql.catalog.s3tablescatalog", "org.apache.iceberg.spark.SparkCatalog") \
    .config("spark.sql.catalog.s3tablescatalog.catalog-impl", "org.apache.iceberg.aws.glue.GlueCatalog") \
    .getOrCreate()

# Read S3 Storage Lens data
df = spark.read \
    .format("iceberg") \
    .load("s3tablescatalog/aws-s3.lens_my-config_exp.default_storage_metrics")

# Analyze data
df.filter("record_type = 'BUCKET'") \
    .groupBy("bucket_name", "storage_class") \
    .sum("storage_bytes") \
    .orderBy("sum(storage_bytes)", ascending=False) \
    .show(10)
```

## 查询优化最佳实践
<a name="storage-lens-s3-tables-querying-optimization"></a>

请遵循以下最佳实践，以优化查询性能并降低成本：
+  **按 report\_time 筛选**：始终包含日期筛选条件以减少扫描的数据量。这对于保留期较长的表特别重要。

  ```
  WHERE report_time >= current_date - interval '7' day
  ```
+  **使用 record\_type 筛选条件**：指定相应的聚合级别（ACCOUNT、BUCKET、PREFIX），以便仅查询所需的数据。

  ```
  WHERE record_type = 'BUCKET'
  ```
+  **包含 LIMIT 子句**：对探索性查询使用 LIMIT，以控制结果大小并降低查询成本。

  ```
  LIMIT 100
  ```
+  **筛选空记录**：使用条件来排除空记录或零值记录。

  ```
  WHERE storage_bytes > 0
  ```
+  **使用最新数据**：分析当前状态时，筛选最新的 report\_time 以避免扫描历史数据。

  ```
  WHERE report_time = (SELECT MAX(report_time) FROM table_name)
  ```

### 优化的查询模式示例
<a name="storage-lens-s3-tables-querying-optimization-example"></a>

以下查询演示了优化的最佳实践：

```
SELECT 
    bucket_name,
    SUM(storage_bytes) / POWER(1024, 3) AS storage_gb
FROM "s3tablescatalog/aws-s3"."lens_my-config_exp"."default_storage_metrics"
WHERE report_time >= current_date - interval '7' day  -- Date filter
    AND record_type = 'BUCKET'                         -- Record type filter
    AND storage_bytes > 0                              -- Non-empty filter
    AND bucket_name != ''                              -- Non-empty filter
GROUP BY bucket_name
ORDER BY storage_gb DESC
LIMIT 100;                                             -- Result limit
```

## 问题排查
<a name="storage-lens-s3-tables-querying-troubleshooting"></a>

### 查询未返回任何结果
<a name="storage-lens-s3-tables-querying-troubleshooting-no-results"></a>

 **问题：**您的查询成功完成，但未返回任何结果。

 **解决方案：**
+ 通过检查最新的 report\_time 来验证数据是否可用：

  ```
  SELECT MAX(report_time) AS latest_data
  FROM "s3tablescatalog/aws-s3"."lens_my-config_exp"."default_storage_metrics";
  ```
+ 确保您使用的是正确的命名空间名称。使用 `SHOW TABLES IN `lens_my-config_exp`;` 列出可用的表。
+ 启用 S3 表类数据存储服务导出后，等待 24-48 小时，第一批数据才可用。

### 访问被拒绝错误
<a name="storage-lens-s3-tables-querying-troubleshooting-access"></a>

 **问题：**在运行查询时，您会收到访问被拒绝错误。

 **解决方案：**验证是否正确地配置了 Amazon Lake Formation 权限。有关更多信息，请参阅[集成 Amazon S3 表类数据存储服务与 Amazon 分析服务](https://docs.amazonaws.cn/AmazonS3/latest/userguide/s3-tables-integrating-aws.html)。

## 后续步骤
<a name="storage-lens-s3-tables-querying-next-steps"></a>
+ 了解 [将 AI 助手与 S3 Storage Lens 存储统计管理工具表结合使用](storage-lens-s3-tables-ai-tools.md)
+ 查看 [Amazon S3 Storage Lens 存储统计管理工具指标词汇表](storage_lens_metrics_glossary.md)以了解指标定义
+ 探索 [Amazon S3 Storage Lens 存储统计管理工具使用案例](storage-lens-use-cases.md)以了解更多分析思路
+ 了解用于进行无服务器查询的 [Amazon Athena](https://docs.amazonaws.cn/athena/latest/ug/what-is.html)