

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 使用 Apache Spark 執行處理任務
<a name="use-spark-processing-container"></a>

Apache Spark 是用於大規模資料處理的統一分析引擎。Amazon SageMaker AI 提供預先建置的 Docker 映像檔，其中包含 Apache Spark 和執行分散式資料處理任務所需的其他相依項。以下提供如何使用 Apache Spark 執行 Amazon SageMaker Processing 任務的範例。

使用 [Amazon SageMaker Python SDK](https://github.com/aws/sagemaker-python-sdk#installing-the-sagemaker-python-sdk)，您就可以使用 Spark 架構輕鬆套用資料轉換並擷取特徵 (特徵工程)。如需使用 SageMaker Python SDK 執行 Spark 處理任務的資訊，請參閱 [Amazon SageMaker Python SDK](https://sagemaker.readthedocs.io/en/stable/) 中的[使用 Spark 進行資料處理](https://sagemaker.readthedocs.io/en/stable/amazon_sagemaker_processing.html#data-processing-with-spark)。

[GitHub](https://github.com/aws/sagemaker-spark-container) 上有可用的程式碼儲存庫，其中包含 Spark 映像之原始程式碼和 Dockerfile。

 您可以使用 [https://sagemaker.readthedocs.io/en/stable/api/training/processing.html#sagemaker.spark.processing.PySparkProcessor](https://sagemaker.readthedocs.io/en/stable/api/training/processing.html#sagemaker.spark.processing.PySparkProcessor) 或 [https://sagemaker.readthedocs.io/en/stable/api/training/processing.html#sagemaker.spark.processing.SparkJarProcessor](https://sagemaker.readthedocs.io/en/stable/api/training/processing.html#sagemaker.spark.processing.SparkJarProcessor) 類別來執行處理任務內的 Spark 應用程式。請注意，您可以將 MaxRuntimeInSeconds 的執行期上限設定為 5 天。在執行時間和所使用的執行個體數量方面，簡單的 Spark 工作負載可查看執行個體數量與完成時間之間的接近線性關係。

 以下程式碼範例示範如何執行可調用 PySpark 指令碼 `preprocess.py` 的處理任務。

```
from sagemaker.spark.processing import PySparkProcessor

spark_processor = PySparkProcessor(
    base_job_name="spark-preprocessor",
    framework_version="2.4",
    role=role,
    instance_count=2,
    instance_type="ml.m5.xlarge",
    max_runtime_in_seconds=1200,
)

spark_processor.run(
    submit_app="preprocess.py",
    arguments=['s3_input_bucket', bucket,
               's3_input_key_prefix', input_prefix,
               's3_output_bucket', bucket,
               's3_output_key_prefix', output_prefix]
)
```

 如需深入探討，請參閱使用 Apache Spark 和 SageMaker Processing 進行分散式資料處理的[範例筆記本](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker_processing/spark_distributed_data_processing/sagemaker-spark-processing.html)。

 如果您未使用 [Amazon SageMaker AI Python SDK](https://sagemaker.readthedocs.io/) 及任何一個處理器類別來擷取預先建置的映像，您可以自行擷取這些映像。SageMaker 預先建置的 Docker 映像存放在 Amazon Elastic Container Registry (Amazon ECR) 中。如需預先建置之可用 Docker 映像的完整清單，請參閱[可用映像](https://github.com/aws/sagemaker-spark-container/blob/master/available_images.md)文件。

 若要深入了解將 SageMaker Python SDK 與 Processing 容器搭配使用，請參閱 [Amazon SageMaker AI Python SDK](https://sagemaker.readthedocs.io/en/stable/)。