

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

# AWS Glue for Spark 中的輸入與輸出的資料格式選項
<a name="aws-glue-programming-etl-format"></a>

這些頁面提供有關 AWS Glue for Spark 支援的資料格式之功能支援和組態參數的資訊。有關此信息的用法和適用性的說明，請參閱以下內容。

## Glue AWS 中跨資料格式的功能支援
<a name="aws-glue-programming-etl-format-features"></a>

 每個資料格式可能支援不同的 AWS Glue 功能。根據您的格式類型，可能會或可能不支持以下常見功能。請參閱資料格式的文件，瞭解如何運用我們的功能來滿足您的需求。


|  |  | 
| --- |--- |
| 讀取 | AWS Glue 無需連接器等其他資源即可識別和解譯此資料格式。 | 
| 寫入 | AWS Glue 可以以此格式寫入資料，無需其他資源。您可以在工作中包含協力廠商程式庫，並使用標準 Apache Spark 函數來寫入資料，就像在其他 Spark 環境中一樣。如需這些程式庫的詳細資訊，請參閱 [搭配 Glue 使用 Python AWS 程式庫](aws-glue-programming-python-libraries.md)。 | 
| 串流讀取 | AWS Glue 可以從 Apache Kafka、Amazon Managed Streaming for Apache Kafka 或 Amazon Kinesis 訊息串流辨識和解譯此資料格式。我們希望流以一致的格式呈現數據，因此它們被讀為DataFrames。 | 
| 對小型檔案進行分組 | AWS Glue 可以將檔案分組，以在執行 Glue AWS 轉換時傳送至每個節點的批次工作。如此可大幅改善涉及大量小型檔案的工作負載的效能。如需詳細資訊，請參閱[讀取在大型群組中的輸入檔案](grouping-input-files.md)。 | 
| 任務書籤 | AWS Glue 可以使用任務書籤追蹤在任務執行期間對相同資料集執行相同工作的轉換進度。這可以提高工作負載的效能，涉及自上次作業執行以來只需在新資料上完成工作的資料集。如需詳細資訊，請參閱[使用任務書籤追蹤處理的資料](monitor-continuations.md)。 | 

## 用來與 Glue AWS 中的資料格式互動的參數
<a name="aws-glue-programming-etl-format-parameters"></a>

某些 AWS Glue 連線類型支援多種`format`類型，要求您在使用 等方法時，使用 `format_options` 物件指定資料格式的相關資訊`GlueContext.write_dynamic_frame.from_options`。
+ `s3` – 如需詳細資訊，請參閱 Glue 中 ETL AWS 的連線類型和選項：[S3 連線參數](aws-glue-programming-etl-connect-s3-home.md#aws-glue-programming-etl-connect-s3)。您也可以檢視促進此連線類型之方法的文件：[create\$1dynamic\$1frame\$1from\$1options](aws-glue-api-crawler-pyspark-extensions-glue-context.md#aws-glue-api-crawler-pyspark-extensions-glue-context-create_dynamic_frame_from_options)和[write\$1dynamic\$1frame\$1from\$1options](aws-glue-api-crawler-pyspark-extensions-glue-context.md#aws-glue-api-crawler-pyspark-extensions-glue-context-write_dynamic_frame_from_options)在 Python 和相應的斯卡拉方法[def getSourceWithFormat](glue-etl-scala-apis-glue-gluecontext.md#glue-etl-scala-apis-glue-gluecontext-defs-getSourceWithFormat)和[def getSinkWithFormat](glue-etl-scala-apis-glue-gluecontext.md#glue-etl-scala-apis-glue-gluecontext-defs-getSinkWithFormat)。

  
+ `kinesis` – 如需詳細資訊，請參閱 Glue 中 ETL AWS 的連線類型和選項：[Kinesis 連線參數](aws-glue-programming-etl-connect-kinesis-home.md#aws-glue-programming-etl-connect-kinesis)。您也可以檢視促進此連線類型的方法文件：[create\$1data\$1frame\$1from\$1options](aws-glue-api-crawler-pyspark-extensions-glue-context.md#aws-glue-api-crawler-pyspark-extensions-glue-context-create-dataframe-from-options)和相應的斯卡拉方法[def createDataFrameFromOptions](glue-etl-scala-apis-glue-gluecontext.md#glue-etl-scala-apis-glue-gluecontext-defs-createDataFrameFromOptions)。
+ `kafka` – 如需詳細資訊，請參閱 Glue 中 ETL AWS 的連線類型和選項：[Kafka 連線參數](aws-glue-programming-etl-connect-kafka-home.md#aws-glue-programming-etl-connect-kafka)。您也可以檢視促進此連線類型的方法文件：[create\$1data\$1frame\$1from\$1options](aws-glue-api-crawler-pyspark-extensions-glue-context.md#aws-glue-api-crawler-pyspark-extensions-glue-context-create-dataframe-from-options)和相應的斯卡拉方法[def createDataFrameFromOptions](glue-etl-scala-apis-glue-gluecontext.md#glue-etl-scala-apis-glue-gluecontext-defs-createDataFrameFromOptions)。

某些連線類型不需要`format_options`。例如，在正常使用中，與關聯式資料庫的 JDBC 連線將以一致的表格式擷取資料。因此，從 JDBC 連接讀取不需要`format_options`。

在膠水中讀取和寫入數據的某些方法不需要`format_options`。例如，使用 `GlueContext.create_dynamic_frame.from_catalog`搭配 AWS Glue 爬蟲程式。爬蟲確定數據的形狀。使用爬蟲程式時，Glue AWS 分類器會檢查您的資料，以做出如何代表資料格式的明智決策。然後，它會將資料的表示法存放在 AWS Glue Data Catalog 中，可用於 Glue ETL AWS 指令碼，以 `GlueContext.create_dynamic_frame.from_catalog`方法擷取您的資料。檢索器無需手動指定有關數據格式的信息。

對於存取 AWS Lake Formation 受管資料表的任務， AWS Glue支援讀取和寫入 Lake Formation 受管資料表支援的所有格式。如需受 AWS Lake Formation 管資料表支援的最新格式清單，請參閱《 *AWS Lake Formation 開發人員指南*》中的[受管資料表的注意事項和限制](https://docs.aws.amazon.com/lake-formation/latest/dg/governed-table-restrictions.html)。

**注意**  
對於寫入 Apache Parquet，AWS Glue ETL 只支援透過指定為動態框架優化的自訂 Parquet 寫入器類型的選項寫入受管控資料表。使用 `parquet` 格式寫入受管控資料表時，您應該在表參數中新增值為 `true` 的金鑰 `useGlueParquetWriter`。

**Topics**
+ [Glue AWS 中跨資料格式的功能支援](#aws-glue-programming-etl-format-features)
+ [用來與 Glue AWS 中的資料格式互動的參數](#aws-glue-programming-etl-format-parameters)
+ [在 Glue AWS 中使用 CSV 格式](aws-glue-programming-etl-format-csv-home.md)
+ [在 Glue AWS 中使用 Parquet 格式](aws-glue-programming-etl-format-parquet-home.md)
+ [在 Glue AWS 中使用 XML 格式](aws-glue-programming-etl-format-xml-home.md)
+ [在 Glue AWS 中使用 Avro 格式](aws-glue-programming-etl-format-avro-home.md)
+ [在 Glue AWS 中使用 grokLog 格式](aws-glue-programming-etl-format-grokLog-home.md)
+ [在 Glue AWS 中使用 Ion 格式](aws-glue-programming-etl-format-ion-home.md)
+ [在 Glue AWS 中使用 JSON 格式](aws-glue-programming-etl-format-json-home.md)
+ [在 Glue AWS 中使用 ORC 格式](aws-glue-programming-etl-format-orc-home.md)
+ [搭配 AWS Glue ETL 任務使用資料湖架構](aws-glue-programming-etl-datalake-native-frameworks.md)
+ [共用的組態參考](#aws-glue-programming-etl-format-shared-reference)

# 在 Glue AWS 中使用 CSV 格式
<a name="aws-glue-programming-etl-format-csv-home"></a>

AWS Glue 會從來源擷取資料，並將資料寫入以各種資料格式存放和傳輸的目標。如果您的資料是以 CSV 資料格式存放或傳輸，本文件會介紹在 Glue AWS 中使用資料的可用功能。

 AWS Glue 支援使用逗號分隔值 (CSV) 格式。此格式是一種極小的、以列為基礎的資料格式。CSV 通常不會嚴格符合標準，但您可以參閱 [RFC 4180](https://tools.ietf.org/html/rfc4180) 和 [RFC 7111](https://tools.ietf.org/html/rfc7111) 來了解詳細資訊。

您可以使用 AWS Glue 從 Amazon S3 和串流來源讀取 CSVs，以及將 CSVs 寫入 Amazon S3。您可以讀取和寫入來自 S3 的包含 CSV 檔案的 `bzip` 和 `gzip` 封存。您可以在 [S3 連線參數](aws-glue-programming-etl-connect-s3-home.md#aws-glue-programming-etl-connect-s3) 上設定壓縮行為，而不是在本頁討論的組態中設定。

下表顯示哪些常見的 AWS Glue 功能支援 CSV 格式選項。


| 讀取 | 寫入 | 串流讀取 | 對小型檔案進行分組 | 任務書籤 | 
| --- | --- | --- | --- | --- | 
| 支援 | 支援 | 支援 | 支援 | 支援 | 

## 範例：從 S3 讀取 CSV 檔案或資料夾
<a name="aws-glue-programming-etl-format-csv-read"></a>

 **先決條件：**您需要指向希望讀取的 CSV 檔案或資料夾的 S3 路徑 (`s3path`)。

 **組態：**在您的函數選項中，指定 `format="csv"`。在您的 `connection_options` 中，使用 `paths` 鍵來指定 `s3path`。您可以在 `connection_options` 中設定讀取器與 S3 互動的方式。如需詳細資訊，請參閱 Glue 中 ETL AWS 的連線類型和選項：[S3 連線參數](aws-glue-programming-etl-connect-s3-home.md#aws-glue-programming-etl-connect-s3)。您可以在 `format_options` 中設定讀取器解譯 CSV 的方式。如需詳細資訊，請參閱 [CSV 組態參考](#aws-glue-programming-etl-format-csv-reference)。

下列 AWS Glue ETL 指令碼顯示從 S3 讀取 CSV 檔案或資料夾的程序。

 我們透過 `optimizePerformance` 組態鍵為常見工作流提供經過效能最佳化的自訂 CSV 讀取器。若要判斷此讀取器是否適合您的工作負載，請參閱 [使用向量化 SIMD CSV 讀取器最佳化讀取效能](#aws-glue-programming-etl-format-simd-csv-reader)。

------
#### [ Python ]

在此範例中，使用 [create\$1dynamic\$1frame.from\$1options](aws-glue-api-crawler-pyspark-extensions-glue-context.md#aws-glue-api-crawler-pyspark-extensions-glue-context-create_dynamic_frame_from_options) 方法。

```
# Example: Read CSV from S3
# For show, we handle a CSV with a header row.  Set the withHeader option.
# Consider whether optimizePerformance is right for your workflow.

from pyspark.context import SparkContext
from awsglue.context import GlueContext

sc = SparkContext.getOrCreate()
glueContext = GlueContext(sc)
spark = glueContext.spark_session

dynamicFrame = glueContext.create_dynamic_frame.from_options(
    connection_type="s3",
    connection_options={"paths": ["s3://s3path"]},
    format="csv",
    format_options={
        "withHeader": True,
        # "optimizePerformance": True,
    },
)
```

您也可以在指令碼中使用 DataFrames (`pyspark.sql.DataFrame`)。

```
dataFrame = spark.read\
    .format("csv")\
    .option("header", "true")\
    .load("s3://s3path")
```

------
#### [ Scala ]

在此範例中，使用 [getSourceWithFormat](glue-etl-scala-apis-glue-gluecontext.md#glue-etl-scala-apis-glue-gluecontext-defs-getSourceWithFormat) 操作。

```
// Example: Read CSV from S3
// For show, we handle a CSV with a header row.  Set the withHeader option.
// Consider whether optimizePerformance is right for your workflow.

import com.amazonaws.services.glue.util.JsonOptions
import com.amazonaws.services.glue.{DynamicFrame, GlueContext}
import org.apache.spark.SparkContext

object GlueApp {
  def main(sysArgs: Array[String]): Unit = {
    val spark: SparkContext = new SparkContext()
    val glueContext: GlueContext = new GlueContext(spark)
    
    val dynamicFrame = glueContext.getSourceWithFormat(
      formatOptions=JsonOptions("""{"withHeader": true}"""),
      connectionType="s3",
      format="csv",
      options=JsonOptions("""{"paths": ["s3://s3path"], "recurse": true}""")
    ).getDynamicFrame()
  }
}
```

您也可以在指令碼中使用 DataFrames (`org.apache.spark.sql.DataFrame`)。

```
val dataFrame = spark.read
  .option("header","true")
  .format("csv")
  .load("s3://s3path“)
```

------

## 範例：將 CSV 檔案和資料夾寫入 S3
<a name="aws-glue-programming-etl-format-csv-write"></a>

 **先決條件：**您需要已初始化的 DataFrame (`dataFrame`) 或 DynamicFrame (`dynamicFrame`)。您還需要預期的 S3 輸出路徑 `s3path`。

 **組態：**在您的函數選項中，指定 `format="csv"`。在您的 `connection_options` 中，使用 `paths` 鍵來指定 `s3path`。您可以在 `connection_options` 中設定寫入器與 S3 的互動方式。如需詳細資訊，請參閱 Glue 中 ETL AWS 的連線類型和選項：[S3 連線參數](aws-glue-programming-etl-connect-s3-home.md#aws-glue-programming-etl-connect-s3)。您可以在 `format_options` 中設定操作如何寫入檔案內容。如需詳細資訊，請參閱 [CSV 組態參考](#aws-glue-programming-etl-format-csv-reference)。以下 AWS Glue ETL 指令碼顯示將 CSV 檔案和資料夾寫入 S3 的流程。

------
#### [ Python ]

在此範例中，使用 [write\$1dynamic\$1frame.from\$1options](aws-glue-api-crawler-pyspark-extensions-glue-context.md#aws-glue-api-crawler-pyspark-extensions-glue-context-write_dynamic_frame_from_options) 方法。

```
# Example: Write CSV to S3
# For show, customize how we write string type values.  Set quoteChar to -1 so our values are not quoted.

from pyspark.context import SparkContext
from awsglue.context import GlueContext

sc = SparkContext.getOrCreate()
glueContext = GlueContext(sc)

glueContext.write_dynamic_frame.from_options(
    frame=dynamicFrame,
    connection_type="s3",
    connection_options={"path": "s3://s3path"},
    format="csv",
    format_options={
        "quoteChar": -1,
    },
)
```

您也可以在指令碼中使用 DataFrames (`pyspark.sql.DataFrame`)。

```
dataFrame.write\
    .format("csv")\
    .option("quote", None)\
    .mode("append")\
    .save("s3://s3path")
```

------
#### [ Scala ]

在此範例中，使用 [getSinkWithFormat](glue-etl-scala-apis-glue-gluecontext.md#glue-etl-scala-apis-glue-gluecontext-defs-getSinkWithFormat) 方法。

```
// Example: Write CSV to S3
// For show, customize how we write string type values. Set quoteChar to -1 so our values are not quoted.

import com.amazonaws.services.glue.util.JsonOptions
import com.amazonaws.services.glue.{DynamicFrame, GlueContext}
import org.apache.spark.SparkContext

object GlueApp {
  def main(sysArgs: Array[String]): Unit = {
    val spark: SparkContext = new SparkContext()
    val glueContext: GlueContext = new GlueContext(spark)
    
    glueContext.getSinkWithFormat(
        connectionType="s3",
        options=JsonOptions("""{"path": "s3://s3path"}"""),
        format="csv"
    ).writeDynamicFrame(dynamicFrame)
  }
}
```

您也可以在指令碼中使用 DataFrames (`org.apache.spark.sql.DataFrame`)。

```
dataFrame.write
    .format("csv")
    .option("quote", null)
    .mode("Append")
    .save("s3://s3path")
```

------

## CSV 組態參考
<a name="aws-glue-programming-etl-format-csv-reference"></a>

只要 Glue AWS 程式庫指定 `format_options`，您就可以使用下列項目`format="csv"`：
+ `separator` – 指定分隔符號字元。預設值為逗號，但您仍可指定任何其他字元。
  + **類型：**文字，**預設：**`","`
+ `escaper` – 指定用於逸出的字元。只有在讀取 (而非寫入) CSV 檔案時，才會使用此選項。若啟用，後面緊接的字元會維持現狀，一小組已知的逸出字元 (`\n`、`\r`、`\t` 與 `\0`) 除外。
  + **類型：**文字，**預設：**無
+ `quoteChar` – 指定用於引用的字元。預設為雙引號。將之設為 `-1` 可完全關閉引用功能。
  + **類型：**文字，**預設：**`'"'`
+ `multiLine` – 指定單項記錄是否可以跨越多行。當欄位內含引用的新行字元時，可能就會發生這種情況。若有任何記錄跨越多行，請務必將此選項設為 `True`。啟用 `multiLine` 可能會降低性能，因為在剖析時需要更加謹慎的檔案分割。
  + **類型：**布林值，**預設：**`false`
+ `withHeader` – 指定是否要將第一行做為標頭。`DynamicFrameReader` 類別可使用該選項。
  + **類型：**布林值，**預設：**`false`
+ `writeHeader` – 指定是否要將標頭寫入輸出之中。`DynamicFrameWriter` 類別可使用該選項。
  + **類型：**布林值，**預設：**`true`
+ `skipFirst` – 指定是否要略過第一個資料行。
  + **類型：**布林值，**預設：**`false`
+ `optimizePerformance` – 指定是否要使用進階 SIMD CSV 讀取器，以及以 Apache Arrow 為基礎的直欄式記憶體格式。僅適用於 AWS Glue 3.0\$1。
  + **類型：**布林值，**預設：**`false`
+ `strictCheckForQuoting`：寫入 CSV 時，Glue 可能會在解讀為字串的值中加上引號。這樣做是為了防止寫出的內容模糊。為了節省時間，決定要寫入的內容時，Glue 可能會在不需要引號的某些情況下進行引用。啟用嚴格檢查將執行更密集的運算，並且僅在必要時引用。僅適用於 AWS Glue 3.0\$1。
  + **類型：**布林值，**預設：**`false`

## 使用向量化 SIMD CSV 讀取器最佳化讀取效能
<a name="aws-glue-programming-etl-format-simd-csv-reader"></a>

AWS Glue 3.0 版本添加了一個經最佳化的 CSV 讀取器，與以資料行為基礎 CSV 讀取器相比，可以大幅加快整體任務效能。

 經最佳化的閱讀器：
+ 使用 CPU SIMD 指令從磁碟讀取
+ 立即以直欄式格式 (Apache Arrow) 將記錄寫入記憶體 
+ 將記錄分成多個批次

這樣可以節省稍後將記錄分批或轉換為直欄式格式的處理時間。有些範例是變更結構描述或依資料行擷取資料時。

要使用經最佳化的讀取器，請在 `format_options` 或資料表屬性中將 `"optimizePerformance"` 設為 `true`。

```
glueContext.create_dynamic_frame.from_options(
    frame = datasource1,
    connection_type = "s3", 
    connection_options = {"paths": ["s3://s3path"]}, 
    format = "csv", 
    format_options={
        "optimizePerformance": True, 
        "separator": ","
        }, 
    transformation_ctx = "datasink2")
```

**向量化 CSV 讀取器的限制**  
請注意向量化 CSV 讀取器的下列限制：
+ 它不支援 `multiLine` 和 `escaper` 格式選項。它使用雙引號字元 `'"'` 的預設 `escaper`。設定這些選項後，AWS Glue 會自動回退到使用以列為基礎的 CSV 讀取器。
+ 它不支援建立具有 [ChoiceType](https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-pyspark-extensions-types.html#aws-glue-api-crawler-pyspark-extensions-types-awsglue-choicetype) 的 DynamicFrame。
+ 它不支援建立具有[錯誤記錄](https://docs.aws.amazon.com/glue/latest/dg/glue-etl-scala-apis-glue-dynamicframe-class.html#glue-etl-scala-apis-glue-dynamicframe-class-defs-errorsAsDynamicFrame)的 DynamicFrame。
+ 它不支援讀取含有多位元組字元 (例如日文或中文字元) 的 CSV 檔案。

# 在 Glue AWS 中使用 Parquet 格式
<a name="aws-glue-programming-etl-format-parquet-home"></a>

AWS Glue 從來源擷取資料，並將資料寫入以各種資料格式存放和傳輸的目標。如果您的資料是以 Parquet 資料格式存放或傳輸，本文件會介紹在 Glue AWS 中使用資料的可用功能。

AWS Glue 支援使用 Parquet 格式。此格式是效能導向、以資料行為基礎的資料格式。如需標準授權單位的格式簡介，請參閱 [Apache Parquet Documentation Overview](https://parquet.apache.org/docs/overview/) (Apache Parquet 文件概觀)。

您可以使用 AWS Glue 從 Amazon S3 和串流來源讀取 Parquet 檔案，以及將 Parquet 檔案寫入 Amazon S3。您可以從 S3 讀取和寫入包含 Parquet 檔案的 `bzip` 和 `gzip` 封存檔。您可以在 [S3 連線參數](aws-glue-programming-etl-connect-s3-home.md#aws-glue-programming-etl-connect-s3) 上設定壓縮行為，而不是在本頁討論的組態中設定。

下表顯示哪些常見的 AWS Glue 功能支援 Parquet 格式選項。


| 讀取 | 寫入 | 串流讀取 | 對小型檔案進行分組 | 任務書籤 | 
| --- | --- | --- | --- | --- | 
| 支援 | 支援 | 支援 | 不支援 | 支援\$1 | 

\$1 Glue AWS 1.0\$1 版支援

## 範例：從 S3 讀取 Parquet 檔案或資料夾
<a name="aws-glue-programming-etl-format-parquet-read"></a>

**先決條件：**您需要指向希望讀取的 Parquet 檔案或資料夾的 S3 路徑 (`s3path`)。

 **組態：**在您的函數選項中，指定 `format="parquet"`。在您的 `connection_options` 中，使用 `paths` 索引鍵指定 `s3path`。

您可以在 `connection_options` 中設定讀取器與 S3 的互動方式。如需詳細資訊，請參閱 Glue 中 ETL AWS 的連線類型和選項：[S3 連線參數](aws-glue-programming-etl-connect-s3-home.md#aws-glue-programming-etl-connect-s3)。

 您可以在 `format_options` 中設定讀取器解譯 Parquet 檔案的方式。如需詳細資訊，請參閱 [Parquet 組態參考](#aws-glue-programming-etl-format-parquet-reference)。

下列 AWS Glue ETL 指令碼顯示從 S3 讀取 Parquet 檔案或資料夾的程序：

------
#### [ Python ]

在此範例中，使用 [create\$1dynamic\$1frame.from\$1options](aws-glue-api-crawler-pyspark-extensions-glue-context.md#aws-glue-api-crawler-pyspark-extensions-glue-context-create_dynamic_frame_from_options) 方法。

```
# Example: Read Parquet from S3

from pyspark.context import SparkContext
from awsglue.context import GlueContext

sc = SparkContext.getOrCreate()
glueContext = GlueContext(sc)
spark = glueContext.spark_session

dynamicFrame = glueContext.create_dynamic_frame.from_options(
    connection_type = "s3", 
    connection_options = {"paths": ["s3://s3path/"]}, 
    format = "parquet"
)
```

您也可以在指令碼中使用 DataFrames (`pyspark.sql.DataFrame`)。

```
dataFrame = spark.read.parquet("s3://s3path/")
```

------
#### [ Scala ]

在此範例中，使用 [getSourceWithFormat](glue-etl-scala-apis-glue-gluecontext.md#glue-etl-scala-apis-glue-gluecontext-defs-getSourceWithFormat) 方法。

```
// Example: Read Parquet from S3

import com.amazonaws.services.glue.util.JsonOptions
import com.amazonaws.services.glue.{DynamicFrame, GlueContext}
import org.apache.spark.SparkContext

object GlueApp {
  def main(sysArgs: Array[String]): Unit = {
    val spark: SparkContext = new SparkContext()
    val glueContext: GlueContext = new GlueContext(spark)
    
    val dynamicFrame = glueContext.getSourceWithFormat(
      connectionType="s3",
      format="parquet",
      options=JsonOptions("""{"paths": ["s3://s3path"]}""")
    ).getDynamicFrame()
  }
}
```

您也可以在指令碼中使用 DataFrames (`org.apache.spark.sql.DataFrame`)。

```
spark.read.parquet("s3://s3path/")
```

------

## 範例：將 Parquet 檔案和資料夾寫入 S3
<a name="aws-glue-programming-etl-format-parquet-write"></a>

**先決條件：**您需要初始化 DataFrame (`dataFrame`) 或 DynamicFrame (`dynamicFrame`)。您還需要預期的 S3 輸出路徑 `s3path`。

 **組態：**在您的函數選項中，指定 `format="parquet"`。在您的 `connection_options` 中，使用 `paths` 鍵來指定 `s3path`。

您可以在 `connection_options` 中進一步更改寫入器與 S3 的互動方式。如需詳細資訊，請參閱 Glue 中 ETL AWS 的連線類型和選項：[S3 連線參數](aws-glue-programming-etl-connect-s3-home.md#aws-glue-programming-etl-connect-s3)。您可以在 `format_options` 中設定操作如何寫入檔案內容。如需詳細資訊，請參閱 [Parquet 組態參考](#aws-glue-programming-etl-format-parquet-reference)。

下列 AWS Glue ETL 指令碼顯示將 Parquet 檔案和資料夾寫入 S3 的程序。

我們透過 `useGlueParquetWriter` 組態鍵為自訂 Parquet 寫入器提供 DynamicFrames 的效能最佳化。若要判斷此寫入器是否適合您的工作負載，請參閱 [Glue Parquet 寫入器](#aws-glue-programming-etl-format-glue-parquet-writer)。

------
#### [ Python ]

在此範例中，使用 [write\$1dynamic\$1frame.from\$1options](aws-glue-api-crawler-pyspark-extensions-glue-context.md#aws-glue-api-crawler-pyspark-extensions-glue-context-write_dynamic_frame_from_options) 方法。

```
# Example: Write Parquet to S3
# Consider whether useGlueParquetWriter is right for your workflow.

from pyspark.context import SparkContext
from awsglue.context import GlueContext

sc = SparkContext.getOrCreate()
glueContext = GlueContext(sc)

glueContext.write_dynamic_frame.from_options(
    frame=dynamicFrame,
    connection_type="s3",
    format="parquet",
    connection_options={
        "path": "s3://s3path",
    },
    format_options={
        # "useGlueParquetWriter": True,
    },
)
```

您也可以在指令碼中使用 DataFrames (`pyspark.sql.DataFrame`)。

```
df.write.parquet("s3://s3path/")
```

------
#### [ Scala ]

在此範例中，使用 [getSinkWithFormat](glue-etl-scala-apis-glue-gluecontext.md#glue-etl-scala-apis-glue-gluecontext-defs-getSinkWithFormat) 方法。

```
// Example: Write Parquet to S3
// Consider whether useGlueParquetWriter is right for your workflow.

import com.amazonaws.services.glue.util.JsonOptions
import com.amazonaws.services.glue.{DynamicFrame, GlueContext}
import org.apache.spark.SparkContext

object GlueApp {
  def main(sysArgs: Array[String]): Unit = {
    val spark: SparkContext = new SparkContext()
    val glueContext: GlueContext = new GlueContext(spark)
    
    glueContext.getSinkWithFormat(
        connectionType="s3",
        options=JsonOptions("""{"path": "s3://s3path"}"""),
        format="parquet"
    ).writeDynamicFrame(dynamicFrame)
  }
}
```

您也可以在指令碼中使用 DataFrames (`org.apache.spark.sql.DataFrame`)。

```
df.write.parquet("s3://s3path/")
```

------

## Parquet 組態參考
<a name="aws-glue-programming-etl-format-parquet-reference"></a>

只要 Glue AWS 程式庫指定 `format_options`，您就可以使用下列項目`format="parquet"`：
+ `useGlueParquetWriter` – 指定使用具有 DynamicFrame 工作流程效能最佳化的自訂 Parquet 寫入器。如需用量詳細資訊，請參閱 [Glue Parquet 寫入器](#aws-glue-programming-etl-format-glue-parquet-writer)。
  + **類型：**布林值，**預設：**`false`
+ `compression` – 指定使用的壓縮轉碼器。值與 `org.apache.parquet.hadoop.metadata.CompressionCodecName` 完全相容。
  + **類型：**列舉文字，**預設：**`"snappy"`
  + 值：`"uncompressed"`、`"snappy"`、`"gzip"` 和 `"lzo"`
+ `blockSize` – 指定記憶體中將緩衝處理資料列群組的大小，以位元組為單位。您可以使用該值來調校效能。大小應完全分為多個 MB 單位。
  + **類型：**數值，**預設：**`134217728`
  + 預設值等於 128 MB。
+ `pageSize` – 指定分頁的大小，以位元組為單位。您可以使用該值來調校效能。分頁是必須完整讀取才能存取單一記錄之最小單位。
  + **類型：**數值，**預設：**`1048576`
  + 預設值等於 1 MB。

**注意**  
此外，任何底層的 SparkSQL 程式碼所接受的選項均可透過 `connection_options` 對應參數傳送。例如，可為 AWS Glue Spark 讀取器設定 [mergeSchema](https://spark.apache.org/docs/latest/sql-data-sources-parquet.html#schema-merging) 等 Spark 組態以合併所有檔案的結構描述。

## 使用 AWS Glue Parquet 寫入器最佳化寫入效能
<a name="aws-glue-programming-etl-format-glue-parquet-writer"></a>

**注意**  
 過去已透過`glueparquet`格式類型存取 AWS Glue Parquet 寫入器。但現在不再提倡這種存取模式。請改用已啟用 `useGlueParquetWriter` 的 `parquet` 類型。

 AWS Glue Parquet 寫入器具有效能增強功能，允許更快速的 Parquet 檔案寫入。傳統的寫入器會在寫入之前計算結構描述。Parquet 格式不會以可供快速擷取的方式存放結構描述，因此這可能需要一些時間。使用 AWS Glue Parquet 寫入器時，不需要預先計算的結構描述。當資料送達時，寫入器會動態地計算並修改結構描述。

指定 `useGlueParquetWriter` 時，請注意以下限制：
+ 寫入器僅支援結構描述演變 (例如新增或移除資料行)，但不會變更資料行類型，例如使用 `ResolveChoice`。
+ 寫入器不支援寫入空白的 DataFrame，例如，寫入只含結構描述的檔案。透過設定 AWS 與 Glue Data Catalog 整合時`enableUpdateCatalog=True`，嘗試寫入空的 DataFrame 不會更新 Data Catalog。而會在資料目錄建立不含結構描述的資料表。

如果您的轉換不需要這些限制，開啟 AWS Glue Parquet 寫入器應該會提高效能。

# 在 Glue AWS 中使用 XML 格式
<a name="aws-glue-programming-etl-format-xml-home"></a>

AWS Glue 從來源擷取資料，並將資料寫入以各種資料格式存放和傳輸的目標。如果您的資料是以 XML 資料格式存放或傳輸，本文件會介紹在 Glue AWS 中使用資料的可用功能。

AWS Glue 支援使用 XML 格式。此格式表示並非基於資料列或資料行的、高度可設定且嚴格定義的資料結構。XML 是高度標準化的。如需標準授權單位的格式簡介，請參閱 [XML Essentials](https://www.w3.org/standards/xml/core) (XML 基礎知識)。

您可以使用 AWS Glue 從 Amazon S3 讀取 XML 檔案，以及包含 XML 檔案的 `bzip`和 `gzip`封存。您可以在 [S3 連線參數](aws-glue-programming-etl-connect-s3-home.md#aws-glue-programming-etl-connect-s3) 上設定壓縮行為，而不是在本頁討論的組態中設定。

下表顯示哪些常見的 AWS Glue 功能支援 XML 格式選項。


| 讀取 | 寫入 | 串流讀取 | 對小型檔案進行分組 | 任務書籤 | 
| --- | --- | --- | --- | --- | 
| 支援 | 不支援 | 不支援 | 支援 | 支援 | 

## 範例：從 S3 讀取 XML
<a name="aws-glue-programming-etl-format-xml-read"></a>

 XML 讀取器接受 XML 標籤名稱。它會檢查其輸入中包含該標籤的元素，以推斷結構描述，並使用對應的值填入 DynamicFrame。Glue XML AWS 功能的行為類似於 [Apache Spark 的 XML 資料來源](https://github.com/databricks/spark-xml)。您可以透過比較此讀取器與該專案的文件，來獲得基本行為相關的洞見。

**先決條件：**您需要指向希望讀取的 XML 檔案或資料夾的 S3 路徑 (`s3path`) 以及有关 XML 檔案的部分資訊。您還需要希望讀取的 XML 元素的標籤，`xmlTag`。

 **組態：**在您的函數選項中，指定 `format="xml"`。在您的 `connection_options` 中，使用 `paths` 鍵來指定 `s3path`。您可以在 `connection_options` 中进一步設定讀取器與 S3 的互動方式。如需詳細資訊，請參閱 Glue 中 ETL AWS 的連線類型和選項：[S3 連線參數](aws-glue-programming-etl-connect-s3-home.md#aws-glue-programming-etl-connect-s3)。在您的 `format_options` 中，使用 `rowTag` 鍵來指定 `xmlTag`。您可以在 `format_options` 中进一步設定讀取器解譯 XML 檔案的方式。如需詳細資訊，請參閱 [XML 組態參考](#aws-glue-programming-etl-format-xml-reference)。

以下 AWS Glue ETL 指令碼顯示從 S3 讀取 XML 檔案或資料夾的流程。

------
#### [ Python ]

在此範例中，使用 [create\$1dynamic\$1frame.from\$1options](aws-glue-api-crawler-pyspark-extensions-glue-context.md#aws-glue-api-crawler-pyspark-extensions-glue-context-create_dynamic_frame_from_options) 方法。

```
# Example: Read XML from S3
# Set the rowTag option to configure the reader.

from awsglue.context import GlueContext
from pyspark.context import SparkContext

sc = SparkContext.getOrCreate()
glueContext = GlueContext(sc)

dynamicFrame = glueContext.create_dynamic_frame.from_options(
    connection_type="s3",
    connection_options={"paths": ["s3://s3path"]},
    format="xml",
    format_options={"rowTag": "xmlTag"},
)
```

您也可以在指令碼中使用 DataFrames (`pyspark.sql.DataFrame`)。

```
dataFrame = spark.read\
    .format("xml")\
    .option("rowTag", "xmlTag")\
    .load("s3://s3path")
```

------
#### [ Scala ]

在此範例中，使用 [getSourceWithFormat](glue-etl-scala-apis-glue-gluecontext.md#glue-etl-scala-apis-glue-gluecontext-defs-getSourceWithFormat) 操作。

```
// Example: Read XML from S3
// Set the rowTag option to configure the reader.

import com.amazonaws.services.glue.util.JsonOptions
import com.amazonaws.services.glue.GlueContext
import org.apache.spark.sql.SparkSession

val glueContext = new GlueContext(SparkContext.getOrCreate())
val sparkSession: SparkSession = glueContext.getSparkSession

object GlueApp {
  def main(sysArgs: Array[String]): Unit = {
    val dynamicFrame = glueContext.getSourceWithFormat(
      formatOptions=JsonOptions("""{"rowTag": "xmlTag"}"""), 
      connectionType="s3", 
      format="xml", 
      options=JsonOptions("""{"paths": ["s3://s3path"], "recurse": true}""")
    ).getDynamicFrame()
}
```

您也可以在指令碼中使用 DataFrames (`org.apache.spark.sql.DataFrame`)。

```
val dataFrame = spark.read
  .option("rowTag", "xmlTag")
  .format("xml")
  .load("s3://s3path“)
```

------

## XML 組態參考
<a name="aws-glue-programming-etl-format-xml-reference"></a>

只要 Glue AWS 程式庫指定 `format_options`，您就可以使用下列項目`format="xml"`：
+ `rowTag` – 指定要將其當做一列的檔案中的 XML 標籤。Row 標籤不能自動關閉。
  + **類型：**文字，**必要**
+ `encoding` – 指定字元編碼。它可以是我们的執行時間環境支援的 [Charset](https://docs.oracle.com/javase/8/docs/api/java/nio/charset/Charset.html) 名稱或別名。我們不對編碼支援做出具體保證，但主要編碼應可適用。
  + **類型：**文字，**預設：**`"UTF-8"`
+ `excludeAttribute` – 指定是否要排除元素中的屬性。
  + **類型：**布林值，**預設：**`false`
+ `treatEmptyValuesAsNulls` – 指定是否要將空格當做 null 值。
  + **類型：**布林值，**預設：**`false`
+ `attributePrefix` – 屬性的字首，用以和子元素文字作區別。此前綴用於欄位名稱。
  + **類型：**文字，**預設：**`"_"`
+ `valueTag` – 當無子元素的元素有屬性時，此標籤會當做一個值。
  + **類型：**文字，**預設：**`"_VALUE"`
+ `ignoreSurroundingSpaces` – 指定是否要忽略前後均有值的空格。
  + **類型：**布林值，**預設：**`false`
+ `withSchema` – 如果要覆寫推斷的結構描述，则包含預期的結構描述。若不使用此選項，AWS Glue 會從 XML 資料推斷出結構描述。
  + **類型：**文字，**預設：**不適用
  + 此值應為代表 `StructType` 的 JSON 物件。

## 手動指定 XML 結構描述
<a name="aws-glue-programming-etl-format-xml-withschema"></a>

**手動 XML 結構描述範例**

這是使用 `withSchema` 格式選項來指定 XML 資料結構描述的範例。

```
from awsglue.gluetypes import *

schema = StructType([ 
  Field("id", IntegerType()),
  Field("name", StringType()),
  Field("nested", StructType([
    Field("x", IntegerType()),
    Field("y", StringType()),
    Field("z", ChoiceType([IntegerType(), StringType()]))
  ]))
])

datasource0 = create_dynamic_frame_from_options(
    connection_type, 
    connection_options={"paths": ["s3://xml_bucket/someprefix"]},
    format="xml", 
    format_options={"withSchema": json.dumps(schema.jsonValue())},
    transformation_ctx = ""
)
```

# 在 Glue AWS 中使用 Avro 格式
<a name="aws-glue-programming-etl-format-avro-home"></a>

AWS Glue 從來源擷取資料，並將資料寫入以各種資料格式存放和傳輸的目標。如果您的資料是以 Avro 資料格式存放或傳輸，本文件會介紹在 Glue AWS 中使用資料的可用功能。

AWS Glue 支援使用 Avro 格式。此格式是效能導向、以資料列為基礎的資料格式。如需標準授權單位的格式簡介，請參閱 [Apache Avro 1.8.2 Documentation](https://avro.apache.org/docs/1.8.2/)。

您可以使用 AWS Glue 從 Amazon S3 和串流來源讀取 Avro 檔案，以及將 Avro 檔案寫入 Amazon S3。您可以讀取和寫入來自 S3 的包含 Avro 檔案的 `bzip2` 和 `gzip` 封存。此外，您可以寫入 `deflate`、`snappy` 和包含 Avro 檔案的 `xz` 封存。您可以在 [S3 連線參數](aws-glue-programming-etl-connect-s3-home.md#aws-glue-programming-etl-connect-s3) 上設定壓縮行為，而不是在本頁討論的組態中設定。

下表顯示哪些常見的 AWS Glue 操作支援 Avro 格式選項。


| 讀取 | 寫入 | 串流讀取 | 對小型檔案進行分組 | 任務書籤 | 
| --- | --- | --- | --- | --- | 
| 支援 | 支援 | 支援\$1 | 不支援 | 支援 | 

\$1 表示支援，但有所限制。如需詳細資訊，請參閱 [Avro 串流來源的注意事項與限制](add-job-streaming.md#streaming-avro-notes)。

## 範例：從 S3 讀取 Avro 檔案或資料夾
<a name="aws-glue-programming-etl-format-avro-read"></a>

**先決條件：**您需要指向希望讀取的 Avro 檔案或資料夾的 S3 路徑 (`s3path`)。

**組態：**在您的函數選項中，指定 `format="avro"`。在您的 `connection_options` 中，使用 `paths` 鍵來指定 `s3path`。您可以在 `connection_options` 中設定讀取器與 S3 的互動方式。如需詳細資訊，請參閱 Glue 中 ETL AWS 輸入和輸出的資料格式選項：[Amazon S3 連線選項參考](aws-glue-programming-etl-connect-s3-home.md#aws-glue-programming-etl-connect-s3)。您可以在 `format_options` 中設定讀取器解譯 Avro 的方式。如需詳細資訊，請參閱 [Avro 組態參考](#aws-glue-programming-etl-format-avro-reference)。

下列 AWS Glue ETL 指令碼顯示從 S3 讀取 Avro 檔案或資料夾的程序：

------
#### [ Python ]

在此範例中，使用 [create\$1dynamic\$1frame.from\$1options](aws-glue-api-crawler-pyspark-extensions-glue-context.md#aws-glue-api-crawler-pyspark-extensions-glue-context-create_dynamic_frame_from_options) 方法。

```
from pyspark.context import SparkContext
from awsglue.context import GlueContext

sc = SparkContext.getOrCreate()
glueContext = GlueContext(sc)

dynamicFrame = glueContext.create_dynamic_frame.from_options(
    connection_type="s3",
    connection_options={"paths": ["s3://s3path"]},
    format="avro"
)
```

------
#### [ Scala ]

在此範例中，使用 [getSourceWithFormat](glue-etl-scala-apis-glue-gluecontext.md#glue-etl-scala-apis-glue-gluecontext-defs-getSourceWithFormat) 操作。

```
import com.amazonaws.services.glue.util.JsonOptions
import com.amazonaws.services.glue.GlueContext
import org.apache.spark.sql.SparkContext

object GlueApp {
  def main(sysArgs: Array[String]): Unit = {
    val spark: SparkContext = new SparkContext()
    val glueContext: GlueContext = new GlueContext(spark)

    val dynamicFrame = glueContext.getSourceWithFormat(
      connectionType="s3",
      format="avro",
      options=JsonOptions("""{"paths": ["s3://s3path"]}""")
    ).getDynamicFrame()
  }
```

------

## 範例：將 Avro 檔案和資料夾寫入 S3
<a name="aws-glue-programming-etl-format-avro-write"></a>

**先決條件：**您需要初始化 DataFrame (`dataFrame`) 或 DynamicFrame (`dynamicFrame`)。您還需要預期的 S3 輸出路徑 `s3path`。

**組態：**在您的函數選項中，指定 `format="avro"`。在您的 `connection_options` 中，使用 `paths` 索引鍵指定 `s3path`。您可以在 `connection_options` 中進一步更改寫入器與 S3 的互動方式。如需詳細資訊，請參閱 Glue 中 ETL AWS 輸入和輸出的資料格式選項：[Amazon S3 連線選項參考](aws-glue-programming-etl-connect-s3-home.md#aws-glue-programming-etl-connect-s3)。您可以在 `format_options` 中更改寫入器解譯 Avro 檔案的方式。如需詳細資訊，請參閱 [Avro 組態參考](#aws-glue-programming-etl-format-avro-reference)。

下列 AWS Glue ETL 指令碼顯示將 Avro 檔案或資料夾寫入 S3 的程序。

------
#### [ Python ]

在此範例中，使用 [write\$1dynamic\$1frame.from\$1options](aws-glue-api-crawler-pyspark-extensions-glue-context.md#aws-glue-api-crawler-pyspark-extensions-glue-context-write_dynamic_frame_from_options) 方法。

```
from pyspark.context import SparkContext
from awsglue.context import GlueContext

sc = SparkContext.getOrCreate()
glueContext = GlueContext(sc)

glueContext.write_dynamic_frame.from_options(
    frame=dynamicFrame,
    connection_type="s3",
    format="avro",
    connection_options={
        "path": "s3://s3path"
    }
)
```

------
#### [ Scala ]

在此範例中，使用 [getSinkWithFormat](glue-etl-scala-apis-glue-gluecontext.md#glue-etl-scala-apis-glue-gluecontext-defs-getSinkWithFormat) 方法。

```
import com.amazonaws.services.glue.util.JsonOptions
import com.amazonaws.services.glue.{DynamicFrame, GlueContext}
import org.apache.spark.SparkContext

object GlueApp {
  def main(sysArgs: Array[String]): Unit = {
    val spark: SparkContext = new SparkContext()
    val glueContext: GlueContext = new GlueContext(spark)

    glueContext.getSinkWithFormat(
      connectionType="s3",
      options=JsonOptions("""{"path": "s3://s3path"}"""),
      format="avro"
    ).writeDynamicFrame(dynamicFrame)
  }
}
```

------

## Avro 組態參考
<a name="aws-glue-programming-etl-format-avro-reference"></a>

無論 Glue AWS 程式庫在何處指定 ，您都可以使用下列`format_options`值`format="avro"`：
+ `version` — 指定 Apache Avro Reader/Writer 格式支援的版本。預設值為 "1.7"。您可以指定 `format_options={"version": “1.8”}`，以啟用 Avro 邏輯類型的讀取和寫入。如需詳細資訊，請參閱 [Apache Avro 1.7.7 規格](https://avro.apache.org/docs/1.7.7/spec.html)和 [Apache Avro 1.8.2 規格](https://avro.apache.org/docs/1.8.2/spec.html)。

  Apache Avro 1.8 連接器支援以下邏輯類型的轉換：

對於讀取器：此表顯示適用於 Avro Reader 1.7 和 1.8 的 Avro 資料類型 (邏輯類型與 Avro 基本類型) 與 AWS Glue `DynamicFrame` 資料類型之間的轉換。


| Avro 資料類型：邏輯類型 | Avro 資料類型：Avro 基本類型 | GlueDynamicFrame 資料類型：Avro Reader 1.7 | GlueDynamicFrame 資料類型：Avro Reader 1.8 | 
| --- | --- | --- | --- | 
| Decimal (小數) | 位元組 | BINARY | Decimal (小數) | 
| Decimal (小數) | 固定 | BINARY | Decimal (小數) | 
| Date | int | INT | Date | 
| 時間 (毫秒) | int | INT | INT | 
| 時間 (微秒) | long | LONG | LONG | 
| 時間戳記 (毫秒) | long | LONG | 時間戳記 | 
| 時間戳記 (微秒) | long | LONG | LONG | 
| 持續時間 (不是邏輯類型) | 12 (固定) | BINARY | BINARY | 

對於寫入器：此表顯示適用於 Avro Writer 1.7 和 1.8 的 AWS Glue `DynamicFrame` 資料類型與 Avro 資料類型之間的轉換。


| AWS Glue `DynamicFrame` 資料類型 | Avro 資料類型：Avro Writer 1.7 | Avro 資料類型：Avro Writer 1.8 | 
| --- | --- | --- | 
| Decimal (小數) | String | decimal | 
| Date | String | date | 
| 時間戳記 | String | timestamp-micros | 

## Avro Spark DataFrame 支援
<a name="aws-glueprogramming-etl-format-avro-dataframe-support"></a>

為了從 Spark DataFrame API 使用Avro，您需要為相應的 Spark 版本安裝 Spark Avro 外掛程式。任務中可用的 Spark 版本取決於您的 Glue AWS 版本。如需 Spark 版本的詳細資訊，請參閱 [AWS Glue 版本](release-notes.md)。這個外掛程式是由 Apache 維護，我們不作出具體的支援保證。

在 AWS Glue 2.0 中 - 使用 Spark Avro 外掛程式的 2.4.3 版。您可以在 Maven Central 找到此 JAR，請參閱 [org.apache.spark:spark-avro\$12.12:2.4.3](https://search.maven.org/artifact/org.apache.spark/spark-avro_2.12/3.1.1/jar)。

在 AWS Glue 3.0 中 - 使用 Spark Avro 外掛程式的 3.1.1 版。您可以在 Maven Central 找到此 JAR，請參閱 [org.apache.spark:spark-avro\$12.12:3.1.1](https://search.maven.org/artifact/org.apache.spark/spark-avro_2.12/3.1.1/jar)。

若要在 Glue ETL AWS 任務中包含額外的 JARs，請使用 `--extra-jars`任務參數。如需有關任務參數的詳細資訊，請參閱 [在 Glue AWS 任務中使用任務參數](aws-glue-programming-etl-glue-arguments.md)。您也可以在 AWS 管理主控台中設定此參數。

# 在 Glue AWS 中使用 grokLog 格式
<a name="aws-glue-programming-etl-format-grokLog-home"></a>

AWS Glue 從來源擷取資料，並將資料寫入以各種資料格式存放和傳輸的目標。如果您的資料是以結構鬆散的純文字格式存放或傳輸，本文件會介紹透過 Grok 模式在 Glue AWS 中使用資料的可用功能。

AWS Glue 支援使用 Grok 模式。Grok 模式類似於規則表達式擷取群組。它們辨識純文字檔案中字元序列的模式，並為其提供類型和用途。在 AWS Glue 中，其主要目的是讀取日誌。有關作者對 Grok 的介紹，請參閱 [Logstash Reference: Grok filter plugin](https://www.elastic.co/guide/en/logstash/current/plugins-filters-grok.html)。


| 讀取 | 寫入 | 串流讀取 | 對小型檔案進行分組 | 任務書籤 | 
| --- | --- | --- | --- | --- | 
| 支援 | 不適用 | 支援 | 支援 | 不支援 | 

## grokLog 組態參考
<a name="aws-glue-programming-etl-format-groklog-reference"></a>

可以使用下列的 `format_options` 值搭配 `format="grokLog"`：
+ `logFormat` — 指定符合記錄格式的 Grok 模式。
+ `customPatterns` — 指定此處使用的其他 Grok 模式。
+ `MISSING` — 指定用於識別遺漏值的訊號。預設值為 `'-'`。
+ `LineCount` — 指定各個日誌記錄中的行數。預設為 `'1'`，目前也只支援單行記錄。
+ `StrictMode` — 布林值，指定是否要開啟嚴格模式。在嚴格模式下，讀者不可自動轉換類型或復原。預設值為 `"false"`。

# 在 Glue AWS 中使用 Ion 格式
<a name="aws-glue-programming-etl-format-ion-home"></a>

AWS Glue 從來源擷取資料，並將資料寫入以各種資料格式存放和傳輸的目標。如果您的資料是以 Ion 資料格式存放或傳輸，本文件會介紹在 Glue AWS 中使用資料的可用功能。

AWS Glue 支援使用 Ion 格式。此格式以可互換的二進位和純文字表示法表示資料結構（並非基於資料列或資料行的資料結構）。如需作者的格式簡介，請參閱 [Amazon Ion](https://amzn.github.io/ion-docs/)。(如需詳細資訊，請參閱 [Amazon Ion 規格](https://amzn.github.io/ion-docs/spec.html)。)

您可以使用 AWS Glue 從 Amazon S3 讀取 Ion 檔案。您可以讀取 `bzip` 和 `gzip` 來自 S3 的包含 Ion 檔案的封存。您可以在 [S3 連線參數](aws-glue-programming-etl-connect-s3-home.md#aws-glue-programming-etl-connect-s3) 上設定壓縮行為，而不是在本頁討論的組態中設定。

下表顯示哪些常見的 AWS Glue 操作支援 Ion 格式選項。


| 讀取 | 寫入 | 串流讀取 | 對小型檔案進行分組 | 任務書籤 | 
| --- | --- | --- | --- | --- | 
| 支援 | 不支援 | 不支援 | 支援 | 不支援 | 

## 範例：從 S3 讀取 Ion 檔案或資料夾
<a name="aws-glue-programming-etl-format-ion-read"></a>

**先決條件：**您需要指向希望讀取的 Ion 檔案或資料夾的 S3 路徑 (`s3path`)。

**組態：**在您的函數選項中，指定 `format="json"`。在您的 `connection_options` 中，使用 `paths` 索引鍵指定 `s3path`。您可以在 `connection_options` 中設定讀取器與 S3 的互動方式。如需詳細資訊，請參閱 Glue 中 ETL AWS 的連線類型和選項：[Amazon S3 連線選項參考](aws-glue-programming-etl-connect-s3-home.md#aws-glue-programming-etl-connect-s3)。

下列 AWS Glue ETL 指令碼顯示從 S3 讀取 Ion 檔案或資料夾的程序：

------
#### [ Python ]

在此範例中，使用 [create\$1dynamic\$1frame.from\$1options](aws-glue-api-crawler-pyspark-extensions-glue-context.md#aws-glue-api-crawler-pyspark-extensions-glue-context-create_dynamic_frame_from_options) 方法。

```
# Example: Read ION from S3

from pyspark.context import SparkContext
from awsglue.context import GlueContext

sc = SparkContext.getOrCreate()
glueContext = GlueContext(sc)

dynamicFrame = glueContext.create_dynamic_frame.from_options(
    connection_type="s3",
    connection_options={"paths": ["s3://s3path"]},
    format="ion"
)
```

------
#### [ Scala ]

在此範例中，使用 [getSourceWithFormat](glue-etl-scala-apis-glue-gluecontext.md#glue-etl-scala-apis-glue-gluecontext-defs-getSourceWithFormat) 操作。

```
// Example: Read ION from S3

import com.amazonaws.services.glue.util.JsonOptions
import com.amazonaws.services.glue.GlueContext
import org.apache.spark.SparkContext

object GlueApp {
  def main(sysArgs: Array[String]): Unit = {
    val spark: SparkContext = new SparkContext()
    val glueContext: GlueContext = new GlueContext(spark)

    val dynamicFrame = glueContext.getSourceWithFormat(
      connectionType="s3",
      format="ion",
      options=JsonOptions("""{"paths": ["s3://s3path"], "recurse": true}""")
    ).getDynamicFrame()
  }
}
```

------

## Ion 組態參考
<a name="aws-glue-programming-etl-format-ion-reference"></a>

無 `format="ion"` 的 `format_options` 值。

# 在 Glue AWS 中使用 JSON 格式
<a name="aws-glue-programming-etl-format-json-home"></a>

AWS Glue 從來源擷取資料，並將資料寫入以各種資料格式存放和傳輸的目標。如果您的資料是以 JSON 資料格式存放或傳輸，本文件會向您介紹在 Glue AWS 中使用資料的可用功能。

AWS Glue 支援使用 JSON 格式。此格式表示具有一致形狀但內容靈活、且非基於資料列或資料行的資料結構。JSON 是由多個機構發佈的平行標準所定義的，其中之一是 ECMA-404。如需常用參考來源的格式簡介，請參閱 [JSON 簡介](https://www.json.org/)。

您可以使用 AWS Glue 從 Amazon S3 讀取 JSON 檔案，以及 `bzip`和`gzip`壓縮的 JSON 檔案。您可以在 [S3 連線參數](aws-glue-programming-etl-connect-s3-home.md#aws-glue-programming-etl-connect-s3) 上設定壓縮行為，而不是在本頁討論的組態中設定。


| 讀取 | 寫入 | 串流讀取 | 對小型檔案進行分組 | 任務書籤 | 
| --- | --- | --- | --- | --- | 
| 支援 | 支援 | 支援 | 支援 | 支援 | 

## 範例：從 S3 讀取 JSON 檔案或資料夾
<a name="aws-glue-programming-etl-format-json-read"></a>

**先決條件：**您需要指向想要讀取的 JSON 檔案或資料夾的 S3 路徑 (`s3path`)。

**組態：**在您的函數選項中，指定 `format="json"`。在您的 `connection_options` 中，使用 `paths` 索引鍵指定 `s3path`。您可以在連線選項中進一步更改讀取操作將如何周遊 s3，如需詳細資訊，請諮詢 [Amazon S3 連線選項參考](aws-glue-programming-etl-connect-s3-home.md#aws-glue-programming-etl-connect-s3)。您可以在 `format_options` 中設定讀取器解譯 JSON 的方式。如需詳細資訊，請參閱 [JSON 組態參考](#aws-glue-programming-etl-format-json-reference)。

 下列 AWS Glue ETL 指令碼顯示從 S3 讀取 JSON 檔案或資料夾的程序：

------
#### [ Python ]

在此範例中，使用 [create\$1dynamic\$1frame.from\$1options](aws-glue-api-crawler-pyspark-extensions-glue-context.md#aws-glue-api-crawler-pyspark-extensions-glue-context-create_dynamic_frame_from_options) 方法。

```
# Example: Read JSON from S3
# For show, we handle a nested JSON file that we can limit with the JsonPath parameter
# For show, we also handle a JSON where a single entry spans multiple lines
# Consider whether optimizePerformance is right for your workflow.

from pyspark.context import SparkContext
from awsglue.context import GlueContext

sc = SparkContext.getOrCreate()
glueContext = GlueContext(sc)
spark = glueContext.spark_session

dynamicFrame = glueContext.create_dynamic_frame.from_options(
    connection_type="s3",
    connection_options={"paths": ["s3://s3path"]},
    format="json",
    format_options={
        "jsonPath": "$.id",
        "multiline": True,
        # "optimizePerformance": True, -> not compatible with jsonPath, multiline
    }
)
```

您也可以在指令碼中使用 DataFrames (`pyspark.sql.DataFrame`)。

```
dataFrame = spark.read\
    .option("multiline", "true")\
    .json("s3://s3path")
```

------
#### [ Scala ]

在此範例中，使用 [getSourceWithFormat](glue-etl-scala-apis-glue-gluecontext.md#glue-etl-scala-apis-glue-gluecontext-defs-getSourceWithFormat) 操作。

```
// Example: Read JSON from S3
// For show, we handle a nested JSON file that we can limit with the JsonPath parameter
// For show, we also handle a JSON where a single entry spans multiple lines
// Consider whether optimizePerformance is right for your workflow.

import com.amazonaws.services.glue.util.JsonOptions
import com.amazonaws.services.glue.{DynamicFrame, GlueContext}
import org.apache.spark.SparkContext

object GlueApp {
  def main(sysArgs: Array[String]): Unit = {
    val spark: SparkContext = new SparkContext()
    val glueContext: GlueContext = new GlueContext(spark)

    val dynamicFrame = glueContext.getSourceWithFormat(
      formatOptions=JsonOptions("""{"jsonPath": "$.id", "multiline": true, "optimizePerformance":false}"""),
      connectionType="s3",
      format="json",
      options=JsonOptions("""{"paths": ["s3://s3path"], "recurse": true}""")
    ).getDynamicFrame()
  }
}
```

您也可以在指令碼中使用 DataFrames (`pyspark.sql.DataFrame`)。

```
val dataFrame = spark.read
    .option("multiline", "true")
    .json("s3://s3path")
```

------

## 範例：將 JSON 檔案和資料夾寫入 S3
<a name="aws-glue-programming-etl-format-json-write"></a>

**先決條件：**您需要初始化 DataFrame (`dataFrame`) 或 DynamicFrame (`dynamicFrame`)。您還需要預期的 S3 輸出路徑 `s3path`。

**組態：**在您的函數選項中，指定 `format="json"`。在您的 `connection_options` 中，使用 `paths` 鍵來指定 `s3path`。您可以在 `connection_options` 中進一步更改寫入器與 S3 的互動方式。如需詳細資訊，請參閱 Glue AWS 中 ETL 輸入和輸出的資料格式選項：[Amazon S3 連線選項參考](aws-glue-programming-etl-connect-s3-home.md#aws-glue-programming-etl-connect-s3)。您可以在 `format_options` 中設定寫入器解譯 JSON 的方式。如需詳細資訊，請參閱 [JSON 組態參考](#aws-glue-programming-etl-format-json-reference)。

下列 AWS Glue ETL 指令碼顯示從 S3 寫入 JSON 檔案或資料夾的程序：

------
#### [ Python ]

在此範例中，使用 [write\$1dynamic\$1frame.from\$1options](aws-glue-api-crawler-pyspark-extensions-glue-context.md#aws-glue-api-crawler-pyspark-extensions-glue-context-write_dynamic_frame_from_options) 方法。

```
# Example: Write JSON to S3

from pyspark.context import SparkContext
from awsglue.context import GlueContext

sc = SparkContext.getOrCreate()
glueContext = GlueContext(sc)

glueContext.write_dynamic_frame.from_options(
    frame=dynamicFrame,
    connection_type="s3",
    connection_options={"path": "s3://s3path"},
    format="json"
)
```

您也可以在指令碼中使用 DataFrames (`pyspark.sql.DataFrame`)。

```
df.write.json("s3://s3path/")
```

------
#### [ Scala ]

在此範例中，使用 [getSinkWithFormat](glue-etl-scala-apis-glue-gluecontext.md#glue-etl-scala-apis-glue-gluecontext-defs-getSinkWithFormat) 方法。

```
// Example: Write JSON to S3

import com.amazonaws.services.glue.util.JsonOptions
import com.amazonaws.services.glue.{DynamicFrame, GlueContext}
import org.apache.spark.SparkContext

object GlueApp {
  def main(sysArgs: Array[String]): Unit = {
    val spark: SparkContext = new SparkContext()
    val glueContext: GlueContext = new GlueContext(spark)

    glueContext.getSinkWithFormat(
        connectionType="s3",
        options=JsonOptions("""{"path": "s3://s3path"}"""),
        format="json"
    ).writeDynamicFrame(dynamicFrame)
  }
}
```

您也可以在指令碼中使用 DataFrames (`pyspark.sql.DataFrame`)。

```
df.write.json("s3://s3path")
```

------

## Json 組態參考
<a name="aws-glue-programming-etl-format-json-reference"></a>

可以使用下列的 `format_options` 值搭配 `format="json"`：
+ `jsonPath` — [JsonPath](https://github.com/json-path/JsonPath) 表達式，用以識別要讀入記錄的物件。當檔案包含在外部陣列中的巢狀記錄時，這個方法特別實用。舉例而言，下列 JsonPath 表達式會以 JSON 物件的 `id` 欄位為目標：

  ```
  format="json", format_options={"jsonPath": "$.id"}
  ```
+ `multiline` — 布林值，用以指定單項記錄是否可以跨越多行。當欄位內含引用的新行字元時，可能就會發生這種情況。若有任何記錄跨越多行，請務必將此選項設為 `"true"`。預設值為 `"false"`，如此在剖析時會更加積極地分割檔案。
+ `optimizePerformance` — 布林值，指定是否要使用進階 SIMD JSON 讀取器，以及 Apache Arrow 為基礎的直欄式記憶體格式。僅適用於 AWS Glue 3.0。與 `multiline` 或 `jsonPath` 不相容。提供其中一個選項會指示 AWS Glue 回到標準讀取器。
+ `withSchema` — 字串值，以 [手動指定 XML 結構描述](aws-glue-programming-etl-format-xml-home.md#aws-glue-programming-etl-format-xml-withschema) 中所述的格式指定資料表結構描述。僅在從非目錄連線讀取時搭配 `optimizePerformance` 使用。

## 使用向量化 SIMD JSON 讀取器搭配 Apache Arrow 直欄式格式
<a name="aws-glue-programming-etl-format-simd-json-reader"></a>

AWS Glue 3.0 版為 JSON 資料新增向量化讀取器。與標準讀取器相比，它在某些條件下的效能快 2 倍。此讀取器具有使用者在使用前應注意的某些限制, 本區段中給出了這些限制。

要使用最佳化的讀取器，請在 `format_options` 或資料表屬性中將 `"optimizePerformance"` 設為 True。除非從目錄中讀取，否則還需要提供 `withSchema`。`withSchema` 需要輸入，如 [手動指定 XML 結構描述](aws-glue-programming-etl-format-xml-home.md#aws-glue-programming-etl-format-xml-withschema) 中所述。

```
// Read from S3 data source        
glueContext.create_dynamic_frame.from_options(
    connection_type = "s3", 
    connection_options = {"paths": ["s3://s3path"]}, 
    format = "json", 
    format_options={
        "optimizePerformance": True,
        "withSchema": SchemaString
        })    
 
// Read from catalog table
glueContext.create_dynamic_frame.from_catalog(
    database = database, 
    table_name = table, 
    additional_options = {
    // The vectorized reader for JSON can read your schema from a catalog table property.
        "optimizePerformance": True,
        })
```

如需在 Glue 程式庫中建置 *SchemaString* AWS 的詳細資訊，請參閱 [PySpark 延伸模組類型](aws-glue-api-crawler-pyspark-extensions-types.md)。

**向量化 CSV 讀取器的限制**  
注意下列限制：
+ 不支援具有巢狀物件或陣列值的 JSON 元素。如果提供， AWS Glue 會回到標準讀取器。
+ 必須從目錄或使用 `withSchema` 提供結構描述。
+ 與 `multiline` 或 `jsonPath` 不相容。提供其中一個選項會指示 AWS Glue 回到標準讀取器。
+ 提供不符合輸入結構描述的輸入記錄會導致讀取器失敗。
+ [錯誤記錄](https://docs.aws.amazon.com/glue/latest/dg/glue-etl-scala-apis-glue-dynamicframe-class.html#glue-etl-scala-apis-glue-dynamicframe-class-defs-errorsAsDynamicFrame)將不會建立。
+ 不支援含有多位元組字元 (例如日文或中文字元) 的 JSON 檔案。

# 在 Glue AWS 中使用 ORC 格式
<a name="aws-glue-programming-etl-format-orc-home"></a>

AWS Glue 從來源擷取資料，並將資料寫入以各種資料格式存放和傳輸的目標。如果您的資料是以 ORC 資料格式存放或傳輸，本文件會介紹在 Glue AWS 中使用資料的可用功能。

AWS Glue 支援使用 ORC 格式。此格式是效能導向、以資料行為基礎的資料格式。如需標準授權單位的格式簡介，請參閱 [Apache Orc](https://orc.apache.org/docs/)。

您可以使用 AWS Glue 從 Amazon S3 和串流來源讀取 ORC 檔案，以及將 ORC 檔案寫入 Amazon S3。您可以讀取和寫入來自 S3 的包含 ORC 檔案的 `bzip` 和 `gzip` 封存。您可以在 [S3 連線參數](aws-glue-programming-etl-connect-s3-home.md#aws-glue-programming-etl-connect-s3) 上設定壓縮行為，而不是在本頁討論的組態中設定。

下表顯示哪些常見的 AWS Glue 操作支援 ORC 格式選項。


| 讀取 | 寫入 | 串流讀取 | 對小型檔案進行分組 | 任務書籤 | 
| --- | --- | --- | --- | --- | 
| 支援 | 支援 | 支援 | 不支援 | 支援\$1 | 

\$1Glue AWS 1.0\$1 版支援

## 範例：從 S3 讀取 ORC 檔案或資料夾
<a name="aws-glue-programming-etl-format-orc-read"></a>

**先決條件：**您需要指向希望讀取的 ORC 檔案或資料夾的 S3 路徑 (`s3path`)。

**組態：**在您的函數選項中，指定 `format="orc"`。在您的 `connection_options` 中，使用 `paths` 索引鍵指定 `s3path`。您可以在 `connection_options` 中設定讀取器與 S3 的互動方式。如需詳細資訊，請參閱 Glue 中 ETL AWS 的連線類型和選項：[Amazon S3 連線選項參考](aws-glue-programming-etl-connect-s3-home.md#aws-glue-programming-etl-connect-s3)。

 下列 AWS Glue ETL 指令碼顯示從 S3 讀取 ORC 檔案或資料夾的程序：

------
#### [ Python ]

在此範例中，使用 [create\$1dynamic\$1frame.from\$1options](aws-glue-api-crawler-pyspark-extensions-glue-context.md#aws-glue-api-crawler-pyspark-extensions-glue-context-create_dynamic_frame_from_options) 方法。

```
from pyspark.context import SparkContext
from awsglue.context import GlueContext

sc = SparkContext.getOrCreate()
glueContext = GlueContext(sc)

dynamicFrame = glueContext.create_dynamic_frame.from_options(
    connection_type="s3",
    connection_options={"paths": ["s3://s3path"]},
    format="orc"
)
```

您也可以在指令碼中使用 DataFrames (`pyspark.sql.DataFrame`)。

```
dataFrame = spark.read\
    .orc("s3://s3path")
```

------
#### [ Scala ]

在此範例中，使用 [getSourceWithFormat](glue-etl-scala-apis-glue-gluecontext.md#glue-etl-scala-apis-glue-gluecontext-defs-getSourceWithFormat) 操作。

```
import com.amazonaws.services.glue.util.JsonOptions
import com.amazonaws.services.glue.GlueContext
import org.apache.spark.sql.SparkContext

object GlueApp {
  def main(sysArgs: Array[String]): Unit = {
    val spark: SparkContext = new SparkContext()
    val glueContext: GlueContext = new GlueContext(spark)

    val dynamicFrame = glueContext.getSourceWithFormat(
      connectionType="s3",
      format="orc",
      options=JsonOptions("""{"paths": ["s3://s3path"]}""")
    ).getDynamicFrame()
  }
}
```

您也可以在指令碼中使用 DataFrames (`pyspark.sql.DataFrame`)。

```
val dataFrame = spark.read
    .orc("s3://s3path")
```

------

## 範例：將 ORC 檔案和資料夾寫入 S3
<a name="aws-glue-programming-etl-format-orc-write"></a>

**先決條件：**您需要初始化 DataFrame (`dataFrame`) 或 DynamicFrame (`dynamicFrame`)。您還需要預期的 S3 輸出路徑 `s3path`。

**組態：**在您的函數選項中，指定 `format="orc"`。在您的連線選項中，使用 `paths` 鍵指定 `s3path`。您可以在 `connection_options` 中進一步更改寫入器與 S3 的互動方式。如需詳細資訊，請參閱 Glue 中 ETL AWS 輸入和輸出的資料格式選項：[Amazon S3 連線選項參考](aws-glue-programming-etl-connect-s3-home.md#aws-glue-programming-etl-connect-s3)。下列程式碼範例顯示了此程序：

------
#### [ Python ]

在此範例中，使用 [write\$1dynamic\$1frame.from\$1options](aws-glue-api-crawler-pyspark-extensions-glue-context.md#aws-glue-api-crawler-pyspark-extensions-glue-context-write_dynamic_frame_from_options) 方法。

```
from pyspark.context import SparkContext
from awsglue.context import GlueContext

sc = SparkContext.getOrCreate()
glueContext = GlueContext(sc)

glueContext.write_dynamic_frame.from_options(
    frame=dynamicFrame,
    connection_type="s3",
    format="orc",
    connection_options={
        "path": "s3://s3path"
    }
)
```

您也可以在指令碼中使用 DataFrames (`pyspark.sql.DataFrame`)。

```
df.write.orc("s3://s3path/")
```

------
#### [ Scala ]

在此範例中，使用 [getSinkWithFormat](glue-etl-scala-apis-glue-gluecontext.md#glue-etl-scala-apis-glue-gluecontext-defs-getSinkWithFormat) 方法。

```
import com.amazonaws.services.glue.util.JsonOptions
import com.amazonaws.services.glue.{DynamicFrame, GlueContext}
import org.apache.spark.SparkContext

object GlueApp {
  def main(sysArgs: Array[String]): Unit = {
    val spark: SparkContext = new SparkContext()
    val glueContext: GlueContext = new GlueContext(spark)

    glueContext.getSinkWithFormat(
      connectionType="s3",
      options=JsonOptions("""{"path": "s3://s3path"}"""),
      format="orc"
    ).writeDynamicFrame(dynamicFrame)
  }
}
```

您也可以在指令碼中使用 DataFrames (`pyspark.sql.DataFrame`)。

```
df.write.orc("s3://s3path/")
```

------

## ORC 組態參考
<a name="aws-glue-programming-etl-format-orc-reference"></a>

無 `format="orc"` 的 `format_options` 值。不過任何底層的 SparkSQL 程式碼所接受的選項均可透過 `connection_options` 對應參數傳送。

# 搭配 AWS Glue ETL 任務使用資料湖架構
<a name="aws-glue-programming-etl-datalake-native-frameworks"></a>

開放原始碼資料湖架構可為您存放在建置於 Amazon S3. AWS Glue 3.0 及更新版本的資料湖中的檔案簡化增量資料處理，並支援下列開放原始碼資料湖架構：
+ Apache Hudi
+ Linux Foundation Delta Lake
+ Apache Iceberg

我們為這些架構提供原生支援，讓您能夠以交易一致的方式讀取和寫入存放在 Amazon S3 中的資料。您不需要安裝個別的連接器或完成額外的設定步驟，就能在 AWS Glue ETL 任務中使用這些架構。

當您透過 管理資料集時 AWS Glue Data Catalog，您可以使用 AWS Glue Spark DataFrames 來讀取和寫入資料湖資料表。您也可以使用 Spark DataFrame API 讀取和寫入 Amazon S3 資料。

在本影片中，您可以了解有關 Apache Hudi、Apache Iceberg 和 Delta Lake 如何運作的基礎知識。您將了解如何插入、更新和刪除資料湖中的資料，以及這些架構的運作方式。

[![AWS Videos](http://img.youtube.com/vi/https://www.youtube.com/embed/fryfx0Zg7KA/0.jpg)](http://www.youtube.com/watch?v=https://www.youtube.com/embed/fryfx0Zg7KA)


**Topics**
+ [限制](aws-glue-programming-etl-datalake-native-frameworks-limitations.md)
+ [在 Glue 中使用 Hudi AWS 架構](aws-glue-programming-etl-format-hudi.md)
+ [在 Glue AWS 中使用 Delta Lake 架構](aws-glue-programming-etl-format-delta-lake.md)
+ [在 Glue AWS 中使用 Iceberg 架構](aws-glue-programming-etl-format-iceberg.md)

# 限制
<a name="aws-glue-programming-etl-datalake-native-frameworks-limitations"></a>

在搭配 使用資料湖架構之前，請考慮下列限制 AWS Glue。
+ 下列 AWS Glue `GlueContext` DynamicFrame 方法不支援讀取和寫入資料湖架構資料表。改用適用於 DataFrame 或 Spark DataFrame API 的 `GlueContext` 方法。
  + `create_dynamic_frame.from_catalog`
  + `write_dynamic_frame.from_catalog`
  + `getDynamicFrame`
  + `writeDynamicFrame`
+ 下列適用於 DataFrame 的 `GlueContext` 方法支援 Lake Formation 權限控制：
  + `create_data_frame.from_catalog`
  + `write_data_frame.from_catalog`
  + `getDataFrame`
  + `writeDataFrame`
+ 不支援[將小型檔案分組](grouping-input-files.md)。
+ 不支援[任務書籤](monitor-continuations.md)。
+ Apache Hudi 0.10.1 for AWS Glue 3.0 不支援 Hudi 讀取時合併 (MoR) 資料表。
+ `ALTER TABLE … RENAME TO` 不適用於 Apache Iceberg 0.13.1 for AWS Glue 3.0。

## 由 Lake Formation 權限管理的資料湖格式資料表的限制
<a name="w2aac67c11c24c11c31c17b7"></a>

資料湖格式透過 Lake Formation 許可與 AWS Glue ETL 整合。不支援使用 `create_dynamic_frame` 建立 DynamicFrame。如需詳細資訊，請參閱下列範例：
+ [範例：使用 Lake Formation 權限控制讀取和寫入 Iceberg 資料表](https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-format-iceberg.html#aws-glue-programming-etl-format-iceberg-read-write-lake-formation-tables)
+ [範例：使用 Lake Formation 權限控制讀取和寫入 Hudi 資料表](https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-format-hudi.html#aws-glue-programming-etl-format-hudi-read-write-lake-formation-tables)
+ [範例：使用 Lake Formation 權限控制讀取和寫入 Delta Lake 資料表](https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-format-delta-lake.html#aws-glue-programming-etl-format-delta-lake-read-write-lake-formation-tables)

**注意**  
只有 4.0 AWS Glue 版支援透過 Lake Formation 整合 AWS Glue ETL 的 Apache Hudi、Apache Iceberg 和 Delta Lake 許可。

Apache Iceberg 透過 Lake Formation 許可與 AWS Glue ETL 提供最佳整合。其支援幾乎所有操作 (包含 SQL 支援)。

Hudi 支援大多數基本操作 (除管理操作外)。這是因為這些選項通常會透過 DataFrame 寫入完成，並透過 `additional_options` 指定。您需要使用 AWS Glue APIs為您的操作建立 DataFrames，因為 SparkSQL 不受支援。

Delta Lake 僅支援讀取、附加及覆寫資料表資料。Delta Lake 需要使用自有的程式庫才可執行不同任務 (例如，更新)。

下列功能不適用於 Lake Formation 權限管理的 Iceberg 資料表。
+ 使用 AWS Glue ETL 壓縮
+ 透過 AWS Glue ETL 的 Spark SQL 支援

下列為 Lake Formation 權限管理的 Hudi 資料表限制：
+ 移除遺棄的檔案

下列為 Lake Formation 權限管理的 Delta Lake 資料表限制：
+ 插入 Delta Lake 資料表和從其中讀取以外的所有功能。

# 在 Glue 中使用 Hudi AWS 架構
<a name="aws-glue-programming-etl-format-hudi"></a>

AWS Glue 3.0 和更新版本支援資料湖的 Apache Hudi 架構。Hudi 是開放原始碼資料湖儲存架構，可簡化增量資料處理與資料管道開發。本主題涵蓋在 Hudi AWS 資料表中傳輸或存放資料時，在 Glue 中使用資料的可用功能。若要進一步了解 Hudi，請參閱官方 [Apache Hudi 文件](https://hudi.apache.org/docs/overview/)。

您可以使用 AWS Glue 在 Amazon S3 中的 Hudi 資料表上執行讀取和寫入操作，或使用 Glue Data Catalog 使用 Hudi AWS 資料表。還支援其他操作，包括插入、更新和所有 [Apache Spark 操作](https://hudi.apache.org/docs/quick-start-guide/)。

**注意**  
Glue 5.0 中的 Apache Hudi AWS 0.15.0 實作會在內部還原 [HUDI-7001](https://github.com/apache/hudi/pull/9936)。當記錄金鑰包含單一欄位時，不會顯示與複雜金鑰產生相關的迴歸。但是，此行為與 OSS Apache Hudi 0.15.0 不同。  
Apache Hudi 0.10.1 for AWS Glue 3.0 不支援 Hudi 讀取時合併 (MoR) 資料表。

下表列出每個 Glue 版本中包含的 Hudi AWS 版本。


****  

| AWS Glue 版本 | 支援的 Hudi 版本 | 
| --- | --- | 
| 5.1 | 1.0.2 | 
| 5.0 | 0.15.0 | 
| 4.0 | 0.12.1 | 
| 3.0 | 0.10.1 | 

若要進一步了解 AWS Glue 支援的資料湖架構，請參閱 [搭配 AWS Glue ETL 任務使用資料湖架構](aws-glue-programming-etl-datalake-native-frameworks.md)。

## 啟用 Hudi
<a name="aws-glue-programming-etl-format-hudi-enable"></a>

若要啟用 Hudi for AWS Glue，請完成下列任務：
+ 指定 `hudi` 作為 `--datalake-formats` 任務參數的值。如需詳細資訊，請參閱[在 Glue AWS 任務中使用任務參數](aws-glue-programming-etl-glue-arguments.md)。
+ 為您的 Glue 任務建立名為 AWS `--conf`的金鑰，並將其設定為下列值。您也可以選擇在指令碼中使用 `SparkConf` 設定以下組態。這些設定有助於 Apache Spark 正確處理 Hudi 資料表。

  ```
  spark.serializer=org.apache.spark.serializer.KryoSerializer
  ```
+ Glue 4.0 預設會啟用 Hudi AWS 的 Lake Formation 許可支援。讀取/寫入 Lake Formation 註冊的 Hudi 資料表時，不需要其他組態。若要讀取已註冊的 Hudi 資料表，Glue AWS 任務 IAM 角色必須具有 SELECT 許可。若要寫入已註冊的 Hudi 資料表，Glue AWS 任務 IAM 角色必須具有 SUPER 許可。若要進一步了解管理 Lake Formation 權限的資訊，請參閱[授予和撤銷 Data Catalog 資源的權限](https://docs.aws.amazon.com/lake-formation/latest/dg/granting-catalog-permissions.html)。

**使用不同的 Hudi 版本**

若要使用 AWS Glue 不支援的 Hudi 版本，請使用 `--extra-jars`任務參數指定您自己的 Hudi JAR 檔案。請勿包括 `hudi` 作為 `--datalake-formats` 任務參數的值。如果您使用 AWS Glue 5.0 或更新版本，則必須設定`--user-jars-first true`任務參數。

## 範例：將 Hudi 資料表寫入 Amazon S3，並在 AWS Glue Data Catalog 中註冊
<a name="aws-glue-programming-etl-format-hudi-write"></a>

此範例指令碼示範如何將 Hudi 資料表寫入 Amazon S3，並將資料表註冊至 AWS Glue Data Catalog。此範例使用 Hudi [Hive 同步工具](https://hudi.apache.org/docs/syncing_metastore/)來註冊該資料表。

**注意**  
此範例需要您設定`--enable-glue-datacatalog`任務參數，才能使用 AWS Glue Data Catalog 做為 Apache Spark Hive 中繼存放區。如需詳細資訊，請參閱 [在 Glue AWS 任務中使用任務參數](aws-glue-programming-etl-glue-arguments.md)。

------
#### [ Python ]

```
# Example: Create a Hudi table from a DataFrame 
# and register the table to Glue Data Catalog

additional_options={
    "hoodie.table.name": "<your_table_name>",
    "hoodie.database.name": "<your_database_name>",
    "hoodie.datasource.write.storage.type": "COPY_ON_WRITE",
    "hoodie.datasource.write.operation": "upsert",
    "hoodie.datasource.write.recordkey.field": "<your_recordkey_field>",
    "hoodie.datasource.write.precombine.field": "<your_precombine_field>",
    "hoodie.datasource.write.partitionpath.field": "<your_partitionkey_field>",
    "hoodie.datasource.write.hive_style_partitioning": "true",
    "hoodie.datasource.hive_sync.enable": "true",
    "hoodie.datasource.hive_sync.database": "<your_database_name>",
    "hoodie.datasource.hive_sync.table": "<your_table_name>",
    "hoodie.datasource.hive_sync.partition_fields": "<your_partitionkey_field>",
    "hoodie.datasource.hive_sync.partition_extractor_class": "org.apache.hudi.hive.MultiPartKeysValueExtractor",
    "hoodie.datasource.hive_sync.use_jdbc": "false",
    "hoodie.datasource.hive_sync.mode": "hms",
    "path": "s3://<s3Path/>"
}

dataFrame.write.format("hudi") \
    .options(**additional_options) \
    .mode("overwrite") \
    .save()
```

------
#### [ Scala ]

```
// Example: Example: Create a Hudi table from a DataFrame
// and register the table to Glue Data Catalog

val additionalOptions = Map(
  "hoodie.table.name" -> "<your_table_name>",
  "hoodie.database.name" -> "<your_database_name>",
  "hoodie.datasource.write.storage.type" -> "COPY_ON_WRITE",
  "hoodie.datasource.write.operation" -> "upsert",
  "hoodie.datasource.write.recordkey.field" -> "<your_recordkey_field>",
  "hoodie.datasource.write.precombine.field" -> "<your_precombine_field>",
  "hoodie.datasource.write.partitionpath.field" -> "<your_partitionkey_field>",
  "hoodie.datasource.write.hive_style_partitioning" -> "true",
  "hoodie.datasource.hive_sync.enable" -> "true",
  "hoodie.datasource.hive_sync.database" -> "<your_database_name>",
  "hoodie.datasource.hive_sync.table" -> "<your_table_name>",
  "hoodie.datasource.hive_sync.partition_fields" -> "<your_partitionkey_field>",
  "hoodie.datasource.hive_sync.partition_extractor_class" -> "org.apache.hudi.hive.MultiPartKeysValueExtractor",
  "hoodie.datasource.hive_sync.use_jdbc" -> "false",
  "hoodie.datasource.hive_sync.mode" -> "hms",
  "path" -> "s3://<s3Path/>")

dataFrame.write.format("hudi")
  .options(additionalOptions)
  .mode("append")
  .save()
```

------

## 範例：使用 Glue Data Catalog 從 Amazon S3 AWS 讀取 Hudi 資料表
<a name="aws-glue-programming-etl-format-hudi-read"></a>

此範例會讀取您從 Amazon S3 在 [範例：將 Hudi 資料表寫入 Amazon S3，並在 AWS Glue Data Catalog 中註冊](#aws-glue-programming-etl-format-hudi-write) 中建立的 Hudi 資料表。

**注意**  
此範例需要您設定`--enable-glue-datacatalog`任務參數，才能使用 AWS Glue Data Catalog 做為 Apache Spark Hive 中繼存放區。如需詳細資訊，請參閱 [在 Glue AWS 任務中使用任務參數](aws-glue-programming-etl-glue-arguments.md)。

------
#### [ Python ]

在此範例中，使用 `GlueContext.create\$1data\$1frame.from\$1catalog()` 方法。

```
# Example: Read a Hudi table from Glue Data Catalog

from awsglue.context import GlueContext
from pyspark.context import SparkContext

sc = SparkContext()
glueContext = GlueContext(sc)

dataFrame = glueContext.create_data_frame.from_catalog(
    database = "<your_database_name>",
    table_name = "<your_table_name>"
)
```

------
#### [ Scala ]

在此範例中，使用 [getCatalogSource](glue-etl-scala-apis-glue-gluecontext.md#glue-etl-scala-apis-glue-gluecontext-defs-getCatalogSource) 方法。

```
// Example: Read a Hudi table from Glue Data Catalog

import com.amazonaws.services.glue.GlueContext
import org.apache.spark.SparkContext

object GlueApp {
  def main(sysArgs: Array[String]): Unit = {
    val spark: SparkContext = new SparkContext()
    val glueContext: GlueContext = new GlueContext(spark)
    
    val dataFrame = glueContext.getCatalogSource(
      database = "<your_database_name>",
      tableName = "<your_table_name>"
    ).getDataFrame()
  }
}
```

------

## 範例：在 Amazon S3 中更新 `DataFrame` 並將其插入到 Hudi 資料表中
<a name="aws-glue-programming-etl-format-hudi-update-insert"></a>

此範例使用 AWS Glue Data Catalog 將 DataFrame 插入您在 中建立的 Hudi 資料表[範例：將 Hudi 資料表寫入 Amazon S3，並在 AWS Glue Data Catalog 中註冊](#aws-glue-programming-etl-format-hudi-write)。

**注意**  
此範例需要您設定`--enable-glue-datacatalog`任務參數，才能使用 AWS Glue Data Catalog 做為 Apache Spark Hive 中繼存放區。如需詳細資訊，請參閱 [在 Glue AWS 任務中使用任務參數](aws-glue-programming-etl-glue-arguments.md)。

------
#### [ Python ]

在此範例中，使用 `GlueContext.write\$1data\$1frame.from\$1catalog()` 方法。

```
# Example: Upsert a Hudi table from Glue Data Catalog

from awsglue.context import GlueContext
from pyspark.context import SparkContext

sc = SparkContext()
glueContext = GlueContext(sc)

glueContext.write_data_frame.from_catalog(
    frame = dataFrame,
    database = "<your_database_name>",
    table_name = "<your_table_name>",
    additional_options={
        "hoodie.table.name": "<your_table_name>",
        "hoodie.database.name": "<your_database_name>",
        "hoodie.datasource.write.storage.type": "COPY_ON_WRITE",
        "hoodie.datasource.write.operation": "upsert",
        "hoodie.datasource.write.recordkey.field": "<your_recordkey_field>",
        "hoodie.datasource.write.precombine.field": "<your_precombine_field>",
        "hoodie.datasource.write.partitionpath.field": "<your_partitionkey_field>",
        "hoodie.datasource.write.hive_style_partitioning": "true",
        "hoodie.datasource.hive_sync.enable": "true",
        "hoodie.datasource.hive_sync.database": "<your_database_name>",
        "hoodie.datasource.hive_sync.table": "<your_table_name>",
        "hoodie.datasource.hive_sync.partition_fields": "<your_partitionkey_field>",
        "hoodie.datasource.hive_sync.partition_extractor_class": "org.apache.hudi.hive.MultiPartKeysValueExtractor",
        "hoodie.datasource.hive_sync.use_jdbc": "false",
        "hoodie.datasource.hive_sync.mode": "hms"
    }
)
```

------
#### [ Scala ]

在此範例中，使用 [getCatalogSink](glue-etl-scala-apis-glue-gluecontext.md#glue-etl-scala-apis-glue-gluecontext-defs-getCatalogSink) 方法。

```
// Example: Upsert a Hudi table from Glue Data Catalog

import com.amazonaws.services.glue.GlueContext
import com.amazonaws.services.glue.util.JsonOptions
import org.apacke.spark.SparkContext

object GlueApp {
  def main(sysArgs: Array[String]): Unit = {
    val spark: SparkContext = new SparkContext()
    val glueContext: GlueContext = new GlueContext(spark)
    glueContext.getCatalogSink("<your_database_name>", "<your_table_name>",
      additionalOptions = JsonOptions(Map(
        "hoodie.table.name" -> "<your_table_name>",
        "hoodie.database.name" -> "<your_database_name>",
        "hoodie.datasource.write.storage.type" -> "COPY_ON_WRITE",
        "hoodie.datasource.write.operation" -> "upsert",
        "hoodie.datasource.write.recordkey.field" -> "<your_recordkey_field>",
        "hoodie.datasource.write.precombine.field" -> "<your_precombine_field>",
        "hoodie.datasource.write.partitionpath.field" -> "<your_partitionkey_field>",
        "hoodie.datasource.write.hive_style_partitioning" -> "true",
        "hoodie.datasource.hive_sync.enable" -> "true",
        "hoodie.datasource.hive_sync.database" -> "<your_database_name>",
        "hoodie.datasource.hive_sync.table" -> "<your_table_name>",
        "hoodie.datasource.hive_sync.partition_fields" -> "<your_partitionkey_field>",
        "hoodie.datasource.hive_sync.partition_extractor_class" -> "org.apache.hudi.hive.MultiPartKeysValueExtractor",
        "hoodie.datasource.hive_sync.use_jdbc" -> "false",
        "hoodie.datasource.hive_sync.mode" -> "hms"
      )))
      .writeDataFrame(dataFrame, glueContext)
  }
}
```

------

## 範例：使用 Spark 從 Amazon S3 讀取 Hudi 資料表
<a name="aws-glue-programming-etl-format-hudi-read-spark"></a>

此範例使用 Spark DataFrame API 從 Amazon S3 讀取 Hudi 資料表。

------
#### [ Python ]

```
# Example: Read a Hudi table from S3 using a Spark DataFrame

dataFrame = spark.read.format("hudi").load("s3://<s3path/>")
```

------
#### [ Scala ]

```
// Example: Read a Hudi table from S3 using a Spark DataFrame

val dataFrame = spark.read.format("hudi").load("s3://<s3path/>")
```

------

## 範例：使用 Spark 將 Hudi 資料表寫入 Amazon S3
<a name="aws-glue-programming-etl-format-hudi-write-spark"></a>

此範例使用 Spark 將 Hudi 資料表寫入 Amazon S3。

------
#### [ Python ]

```
# Example: Write a Hudi table to S3 using a Spark DataFrame

dataFrame.write.format("hudi") \
    .options(**additional_options) \
    .mode("overwrite") \
    .save("s3://<s3Path/>)
```

------
#### [ Scala ]

```
// Example: Write a Hudi table to S3 using a Spark DataFrame

dataFrame.write.format("hudi")
  .options(additionalOptions)
  .mode("overwrite")
  .save("s3://<s3path/>")
```

------

## 範例：使用 Lake Formation 權限控制讀取和寫入 Hudi 資料表
<a name="aws-glue-programming-etl-format-hudi-read-write-lake-formation-tables"></a>

此範例會使用 Lake Formation 權限控制讀取和寫入 Hudi 資料表。

1. 建立 Hudi 資料表，並在 Lake Formation 中進行註冊。

   1. 若要啟用 Lake Formation 權限控制，您將需要先在 Lake Formation 中註冊資料表 Amazon S3 路徑。如需詳細資訊，請參閱 [Registering an Amazon S3 location](https://docs.aws.amazon.com/lake-formation/latest/dg/register-location.html) (註冊 Amazon S3 位置)。您可以從 Lake Formation 主控台或使用 CLI AWS 註冊：

      ```
      aws lakeformation register-resource --resource-arn arn:aws:s3:::<s3-bucket>/<s3-folder> --use-service-linked-role --region <REGION>
      ```

      註冊 Amazon S3 位置後，指向位置 （或其任何子位置） 的任何 AWS Glue 資料表都會在`GetTable`呼叫中傳回 `IsRegisteredWithLakeFormation` 參數的值為 true。

   1. 建立透過 Spark DataFrame API 指向註冊之 Amazon S3 路徑的 Hudi 資料表：

      ```
      hudi_options = {
          'hoodie.table.name': table_name,
          'hoodie.database.name': database_name,
          'hoodie.datasource.write.storage.type': 'COPY_ON_WRITE',
          'hoodie.datasource.write.recordkey.field': 'product_id',
          'hoodie.datasource.write.table.name': table_name,
          'hoodie.datasource.write.operation': 'upsert',
          'hoodie.datasource.write.precombine.field': 'updated_at',
          'hoodie.datasource.write.hive_style_partitioning': 'true',
          'hoodie.upsert.shuffle.parallelism': 2,
          'hoodie.insert.shuffle.parallelism': 2,
          'path': <S3_TABLE_LOCATION>,
          'hoodie.datasource.hive_sync.enable': 'true',
          'hoodie.datasource.hive_sync.database': database_name,
          'hoodie.datasource.hive_sync.table': table_name,
          'hoodie.datasource.hive_sync.use_jdbc': 'false',
          'hoodie.datasource.hive_sync.mode': 'hms'
      }
      
      df_products.write.format("hudi")  \
          .options(**hudi_options)  \
          .mode("overwrite")  \
          .save()
      ```

1. 將 Lake Formation 許可授予 AWS Glue 任務 IAM 角色。您可以從 Lake Formation 主控台授予許可，或使用 AWS CLI。如需詳細資訊，請參閱[使用 Lake Formation 主控台和具名資源方法授予資料表權限](https://docs.aws.amazon.com/lake-formation/latest/dg/granting-table-permissions.html)。

1.  讀取在 Lake Formation 中註冊的 Hudi 資料表。該程式碼與讀取未註冊之 Hudi 資料表的程式碼相同。請注意，Glue AWS 任務 IAM 角色需要具有 SELECT 許可才能成功讀取。

   ```
    val dataFrame = glueContext.getCatalogSource(
         database = "<your_database_name>",
         tableName = "<your_table_name>"
       ).getDataFrame()
   ```

1. 寫入在 Lake Formation 中註冊的 Hudi 資料表。該程式碼與寫入未註冊之 Hudi 資料表的程式碼相同。請注意，Glue AWS 任務 IAM 角色需要具有 SUPER 許可才能成功寫入。

   ```
   glueContext.getCatalogSink("<your_database_name>", "<your_table_name>",
         additionalOptions = JsonOptions(Map(
           "hoodie.table.name" -> "<your_table_name>",
           "hoodie.database.name" -> "<your_database_name>",
           "hoodie.datasource.write.storage.type" -> "COPY_ON_WRITE",
           "hoodie.datasource.write.operation" -> "<write_operation>",
           "hoodie.datasource.write.recordkey.field" -> "<your_recordkey_field>",
           "hoodie.datasource.write.precombine.field" -> "<your_precombine_field>",
           "hoodie.datasource.write.partitionpath.field" -> "<your_partitionkey_field>",
           "hoodie.datasource.write.hive_style_partitioning" -> "true",
           "hoodie.datasource.hive_sync.enable" -> "true",
           "hoodie.datasource.hive_sync.database" -> "<your_database_name>",
           "hoodie.datasource.hive_sync.table" -> "<your_table_name>",
           "hoodie.datasource.hive_sync.partition_fields" -> "<your_partitionkey_field>",
           "hoodie.datasource.hive_sync.partition_extractor_class" -> "org.apache.hudi.hive.MultiPartKeysValueExtractor",
           "hoodie.datasource.hive_sync.use_jdbc" -> "false",
           "hoodie.datasource.hive_sync.mode" -> "hms"
         )))
         .writeDataFrame(dataFrame, glueContext)
   ```

# 在 Glue AWS 中使用 Delta Lake 架構
<a name="aws-glue-programming-etl-format-delta-lake"></a>

AWS Glue 3.0 和更新版本支援 Linux Foundation Delta Lake 架構。Delta Lake 是開放原始碼資料湖儲存架構，可協助您執行 ACID 交易、擴充中繼資料處理，以及統一串流與批次資料處理。本主題涵蓋在 Delta Lake AWS 資料表中傳輸或存放資料時，在 Glue 中使用資料的可用功能。若要進一步了解 Delta Lake，請參閱官方 [Delta Lake 文件](https://docs.delta.io/latest/delta-intro.html)。

您可以使用 AWS Glue 在 Amazon S3 中的 Delta Lake 資料表上執行讀取和寫入操作，或使用 Glue Data Catalog 使用 Delta Lake AWS 資料表。插入、更新和[資料表批次讀取和寫入](https://docs.delta.io/0.7.0/api/python/index.html)等操作也受到支援。使用 Delta Lake 資料表時，您還可以選擇使用 Delta Lake Python 程式庫中的方法，例如 `DeltaTable.forPath`。如需有關 Delta Lake Python 程式庫的詳細資訊，請參閱 Delta Lake 的 Python 文件。

下表列出每個 Glue 版本中包含的 Delta Lake AWS 版本。


****  

| AWS Glue 版本 | 支援的 Delta Lake 版本 | 
| --- | --- | 
| 5.1 | 3.3.2 | 
| 5.0 | 3.3.0 | 
| 4.0 | 2.1.0 | 
| 3.0 | 1.0.0 | 

若要進一步了解 Glue AWS 支援的資料湖架構，請參閱 [搭配 AWS Glue ETL 任務使用資料湖架構](aws-glue-programming-etl-datalake-native-frameworks.md)。

## 啟用 Delta Lake for AWS Glue
<a name="aws-glue-programming-etl-format-delta-lake-enable"></a>

若要啟用 Delta Lake for AWS Glue，請完成下列任務：
+ 指定 `delta` 作為 `--datalake-formats` 任務參數的值。如需詳細資訊，請參閱[在 Glue AWS 任務中使用任務參數](aws-glue-programming-etl-glue-arguments.md)。
+ 為您的 Glue 任務建立名為 AWS `--conf`的金鑰，並將其設定為下列值。您也可以選擇在指令碼中使用 `SparkConf` 設定以下組態。這些設定有助於 Apache Spark 正確處理 Delta Lake 資料表。

  ```
  spark.sql.extensions=io.delta.sql.DeltaSparkSessionExtension --conf spark.sql.catalog.spark_catalog=org.apache.spark.sql.delta.catalog.DeltaCatalog --conf spark.delta.logStore.class=org.apache.spark.sql.delta.storage.S3SingleDriverLogStore
  ```
+ Glue 4.0 預設會啟用 Delta 資料表的 Lake Formation AWS 許可支援。讀取/寫入 Lake Formation 註冊的 Delta 資料表時，不需要其他組態。若要讀取已註冊的 Delta AWS 資料表，Glue 任務 IAM 角色必須具有 SELECT 許可。若要寫入已註冊的 Delta AWS 資料表，Glue 任務 IAM 角色必須具有 SUPER 許可。若要進一步了解管理 Lake Formation 權限的資訊，請參閱[授予和撤銷 Data Catalog 資源的權限](https://docs.aws.amazon.com/lake-formation/latest/dg/granting-catalog-permissions.html)。

**使用不同的 Delta Lake 版本**

若要使用 AWS Glue 不支援的 Delta lake 版本，請使用 `--extra-jars`任務參數指定您自己的 Delta Lake JAR 檔案。請勿包括 `delta` 作為 `--datalake-formats` 任務參數的值。如果您使用 AWS Glue 5.0 或更新版本，則必須設定`--user-jars-first true`任務參數。若要在此案例中使用 Delta Lake Python 程式庫，您必須使用 `--extra-py-files` 任務參數指定程式庫 JAR 檔案。Python 程式庫封裝在 Delta Lake JAR 檔案中。

## 範例：將 Delta Lake 資料表寫入 Amazon S3，並將其註冊到 AWS Glue Data Catalog
<a name="aws-glue-programming-etl-format-delta-lake-write"></a>

下列 AWS Glue ETL 指令碼示範如何將 Delta Lake 資料表寫入 Amazon S3，並將資料表註冊至 AWS Glue Data Catalog。

------
#### [ Python ]

```
# Example: Create a Delta Lake table from a DataFrame 
# and register the table to Glue Data Catalog

additional_options = {
    "path": "s3://<s3Path>"
}
dataFrame.write \
    .format("delta") \
    .options(**additional_options) \
    .mode("append") \
    .partitionBy("<your_partitionkey_field>") \
    .saveAsTable("<your_database_name>.<your_table_name>")
```

------
#### [ Scala ]

```
// Example: Example: Create a Delta Lake table from a DataFrame
// and register the table to Glue Data Catalog

val additional_options = Map(
  "path" -> "s3://<s3Path>"
)
dataFrame.write.format("delta")
  .options(additional_options)
  .mode("append")
  .partitionBy("<your_partitionkey_field>")
  .saveAsTable("<your_database_name>.<your_table_name>")
```

------

## 範例：使用 Glue Data Catalog 從 Amazon S3 AWS 讀取 Delta Lake 資料表
<a name="aws-glue-programming-etl-format-delta-lake-read"></a>

下列 AWS Glue ETL 指令碼會讀取您在 中建立的 Delta Lake 資料表[範例：將 Delta Lake 資料表寫入 Amazon S3，並將其註冊到 AWS Glue Data Catalog](#aws-glue-programming-etl-format-delta-lake-write)。

------
#### [ Python ]

在此範例中，使用 [create\$1data\$1frame.from\$1catalog](aws-glue-api-crawler-pyspark-extensions-glue-context.md#aws-glue-api-crawler-pyspark-extensions-glue-context-create-dataframe-from-catalog) 方法。

```
# Example: Read a Delta Lake table from Glue Data Catalog

from awsglue.context import GlueContext
from pyspark.context import SparkContext

sc = SparkContext()
glueContext = GlueContext(sc)

df = glueContext.create_data_frame.from_catalog(
    database="<your_database_name>",
    table_name="<your_table_name>",
    additional_options=additional_options
)
```

------
#### [ Scala ]

在此範例中，使用 [getCatalogSource](glue-etl-scala-apis-glue-gluecontext.md#glue-etl-scala-apis-glue-gluecontext-defs-getCatalogSource) 方法。

```
// Example: Read a Delta Lake table from Glue Data Catalog

import com.amazonaws.services.glue.GlueContext
import org.apacke.spark.SparkContext

object GlueApp {
  def main(sysArgs: Array[String]): Unit = {
    val spark: SparkContext = new SparkContext()
    val glueContext: GlueContext = new GlueContext(spark)
    val df = glueContext.getCatalogSource("<your_database_name>", "<your_table_name>",
      additionalOptions = additionalOptions)
      .getDataFrame()
  }
}
```

------

## 範例：使用 Glue Data Catalog 將 插入 Amazon S3 中的 `DataFrame` Delta Lake AWS 資料表
<a name="aws-glue-programming-etl-format-delta-lake-insert"></a>

此範例會將資料插入您在 [範例：將 Delta Lake 資料表寫入 Amazon S3，並將其註冊到 AWS Glue Data Catalog](#aws-glue-programming-etl-format-delta-lake-write) 中建立的 Delta Lake 資料表中。

**注意**  
此範例需要您設定`--enable-glue-datacatalog`任務參數，才能使用 AWS Glue Data Catalog 做為 Apache Spark Hive 中繼存放區。如需詳細資訊，請參閱 [在 Glue AWS 任務中使用任務參數](aws-glue-programming-etl-glue-arguments.md)。

------
#### [ Python ]

在此範例中，使用 [write\$1data\$1frame.from\$1catalog](aws-glue-api-crawler-pyspark-extensions-glue-context.md#aws-glue-api-crawler-pyspark-extensions-glue-context-write_data_frame_from_catalog) 方法。

```
# Example: Insert into a Delta Lake table in S3 using Glue Data Catalog

from awsglue.context import GlueContext
from pyspark.context import SparkContext

sc = SparkContext()
glueContext = GlueContext(sc)

glueContext.write_data_frame.from_catalog(
    frame=dataFrame,
    database="<your_database_name>",
    table_name="<your_table_name>",
    additional_options=additional_options
)
```

------
#### [ Scala ]

在此範例中，使用 [getCatalogSink](glue-etl-scala-apis-glue-gluecontext.md#glue-etl-scala-apis-glue-gluecontext-defs-getCatalogSink) 方法。

```
// Example: Insert into a Delta Lake table in S3 using Glue Data Catalog

import com.amazonaws.services.glue.GlueContext
import org.apacke.spark.SparkContext

object GlueApp {
  def main(sysArgs: Array[String]): Unit = {
    val spark: SparkContext = new SparkContext()
    val glueContext: GlueContext = new GlueContext(spark)
    glueContext.getCatalogSink("<your_database_name>", "<your_table_name>",
      additionalOptions = additionalOptions)
      .writeDataFrame(dataFrame, glueContext)
  }
}
```

------

## 範例：使用 Spark API 從 Amazon S3 讀取 Delta Lake 資料表
<a name="aws-glue-programming-etl-format-delta_lake-read-spark"></a>

此範例使用 Spark API 從 Amazon S3 讀取 Delta Lake 資料表。

------
#### [ Python ]

```
# Example: Read a Delta Lake table from S3 using a Spark DataFrame

dataFrame = spark.read.format("delta").load("s3://<s3path/>")
```

------
#### [ Scala ]

```
// Example: Read a Delta Lake table from S3 using a Spark DataFrame

val dataFrame = spark.read.format("delta").load("s3://<s3path/>")
```

------

## 範例：使用 Spark 將 Delta Lake 資料表寫入 Amazon S3
<a name="aws-glue-programming-etl-format-delta_lake-write-spark"></a>

此範例會使用 Spark 將 Delta Lake 資料表寫入 Amazon S3。

------
#### [ Python ]

```
# Example: Write a Delta Lake table to S3 using a Spark DataFrame

dataFrame.write.format("delta") \
    .options(**additional_options) \
    .mode("overwrite") \
    .partitionBy("<your_partitionkey_field>")
    .save("s3://<s3Path>")
```

------
#### [ Scala ]

```
// Example: Write a Delta Lake table to S3 using a Spark DataFrame

dataFrame.write.format("delta")
  .options(additionalOptions)
  .mode("overwrite")
  .partitionBy("<your_partitionkey_field>")
  .save("s3://<s3path/>")
```

------

## 範例：使用 Lake Formation 權限控制讀取和寫入 Delta Lake 資料表
<a name="aws-glue-programming-etl-format-delta-lake-read-write-lake-formation-tables"></a>

此範例會讀取和寫入具有 Lake Formation 權限控制的 Delta Lake 資料表。

1. 建立 Delta 資料表，並在 Lake Formation 中進行註冊

   1. 若要啟用 Lake Formation 權限控制，您將需要先在 Lake Formation 中註冊資料表 Amazon S3 路徑。如需詳細資訊，請參閱 [Registering an Amazon S3 location](https://docs.aws.amazon.com/lake-formation/latest/dg/register-location.html) (註冊 Amazon S3 位置)。您可以從 Lake Formation 主控台或使用 CLI AWS 註冊：

      ```
      aws lakeformation register-resource --resource-arn arn:aws:s3:::<s3-bucket>/<s3-folder> --use-service-linked-role --region <REGION>
      ```

      註冊 Amazon S3 位置後，指向位置 （或其任何子位置） 的任何 AWS Glue 資料表都會在`GetTable`呼叫中傳回 `IsRegisteredWithLakeFormation` 參數的值為 true。

   1. 建立透過 Spark 指向註冊之 Amazon S3 路徑的 Delta 資料表：
**注意**  
下列為 Python 範例。

      ```
      dataFrame.write \
      	.format("delta") \
      	.mode("overwrite") \
      	.partitionBy("<your_partitionkey_field>") \
      	.save("s3://<the_s3_path>")
      ```

      將資料寫入 Amazon S3 之後，請使用 AWS Glue 爬蟲程式建立新的 Delta 目錄資料表。如需詳細資訊，請參閱[使用 Glue 爬蟲程式介紹原生 Delta Lake AWS 資料表支援](https://aws.amazon.com/blogs/big-data/introducing-native-delta-lake-table-support-with-aws-glue-crawlers/)。

      您也可以透過 Glue `CreateTable` API AWS 手動建立資料表。

1. 將 Lake Formation 許可授予 AWS Glue 任務 IAM 角色。您可以從 Lake Formation 主控台或使用 AWS CLI 授予許可。如需詳細資訊，請參閱[使用 Lake Formation 主控台和具名資源方法授予資料表權限](https://docs.aws.amazon.com/lake-formation/latest/dg/granting-table-permissions.html)。

1.  讀取在 Lake Formation 中註冊的 Delta 資料表。該程式碼與讀取未註冊之 Delta 資料表的程式碼相同。請注意，Glue AWS 任務 IAM 角色需要具有 SELECT 許可才能成功讀取。

   ```
   # Example: Read a Delta Lake table from Glue Data Catalog
   
   df = glueContext.create_data_frame.from_catalog(
       database="<your_database_name>",
       table_name="<your_table_name>",
       additional_options=additional_options
   )
   ```

1. 寫入在 Lake Formation 中註冊的 Delta 資料表。該程式碼與寫入未註冊之 Delta 資料表的程式碼相同。請注意，Glue AWS 任務 IAM 角色需要具有 SUPER 許可才能成功寫入。

   根據預設，Glue AWS 會使用 `Append`做為 saveMode。您可以透過設定 `additional_options` 中的 saveMode 選項進行變更。如需有關 Delta 資料表之 saveMode 支援的資訊，請參閱[寫入資料表](https://docs.delta.io/latest/delta-batch.html#write-to-a-table)。

   ```
   glueContext.write_data_frame.from_catalog(
       frame=dataFrame,
       database="<your_database_name>",
       table_name="<your_table_name>",
       additional_options=additional_options
   )
   ```

# 在 Glue AWS 中使用 Iceberg 架構
<a name="aws-glue-programming-etl-format-iceberg"></a>

AWS Glue 3.0 和更新版本支援資料湖的 Apache Iceberg 架構。Iceberg 提供高效能的資料表格式，其運作方式就像 SQL 資料表一樣。本主題涵蓋在 Iceberg AWS 資料表中傳輸或存放資料時，在 Glue 中使用資料的可用功能。若要進一步了解 Iceberg，請參閱官方 [Apache Iceberg 文件](https://iceberg.apache.org/docs/latest/)。

您可以使用 AWS Glue 在 Amazon S3 中的 Iceberg 資料表上執行讀取和寫入操作，或使用 Glue Data Catalog 使用 Iceberg AWS 資料表。還支援包括插入和所有 [Spark 查詢](https://iceberg.apache.org/docs/latest/spark-queries/) [Spark 寫入](https://iceberg.apache.org/docs/latest/spark-writes/)在內的其他操作。Iceberg 資料表不支援更新。

**注意**  
`ALTER TABLE … RENAME TO` 不適用於 AWS Glue 3.0 的 Apache Iceberg 0.13.1。

下表列出每個 Glue 版本中包含的 Iceberg AWS 版本。


****  

| AWS Glue 版本 | 支援的 Iceberg 版本 | 
| --- | --- | 
| 5.1 | 1.10.0 | 
| 5.0 | 1.7.1 | 
| 4.0 | 1.0.0 | 
| 3.0 | 0.13.1 | 

若要進一步了解 AWS Glue 支援的資料湖架構，請參閱 [搭配 AWS Glue ETL 任務使用資料湖架構](aws-glue-programming-etl-datalake-native-frameworks.md)。

## 啟用 Iceberg 架構
<a name="aws-glue-programming-etl-format-iceberg-enable"></a>

若要啟用 Iceberg for AWS Glue，請完成下列任務：
+ 指定 `iceberg` 作為 `--datalake-formats` 任務參數的值。如需詳細資訊，請參閱[在 Glue AWS 任務中使用任務參數](aws-glue-programming-etl-glue-arguments.md)。
+ 為您的 Glue 任務建立名為 AWS `--conf`的金鑰，並將其設定為下列值。您也可以選擇在指令碼中使用 `SparkConf` 設定以下組態。這些設定有助於 Apache Spark 正確處理 Iceberg 資料表。

  ```
  spark.sql.extensions=org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions 
  --conf spark.sql.catalog.glue_catalog=org.apache.iceberg.spark.SparkCatalog 
  --conf spark.sql.catalog.glue_catalog.warehouse=s3://<your-warehouse-dir>/ 
  --conf spark.sql.catalog.glue_catalog.catalog-impl=org.apache.iceberg.aws.glue.GlueCatalog 
  --conf spark.sql.catalog.glue_catalog.io-impl=org.apache.iceberg.aws.s3.S3FileIO
  ```

  如果您要讀取或寫入已向 Lake Formation 註冊的 Iceberg 資料表，請遵循 AWS Glue 5.0 和更新[搭配 AWS 使用 Glue AWS Lake Formation 進行精細存取控制](security-lf-enable.md)版本中的指引。在 AWS Glue 4.0 中，新增下列組態以啟用 Lake Formation 支援。

  ```
  --conf spark.sql.catalog.glue_catalog.glue.lakeformation-enabled=true
  --conf spark.sql.catalog.glue_catalog.glue.id=<table-catalog-id>
  ```

  如果您將 AWS Glue 3.0 與 Iceberg 0.13.1 搭配使用，則必須將下列其他組態設定為使用 Amazon DynamoDB 鎖定管理員以確保原子交易。 AWS Glue 4.0 或更新版本預設使用樂觀鎖定。如需詳細資訊，請參閱官方 Apache [Iceberg 文件中的 Iceberg AWS 整合](https://iceberg.apache.org/docs/latest/aws/#dynamodb-lock-manager)。

  ```
  --conf spark.sql.catalog.glue_catalog.lock-impl=org.apache.iceberg.aws.glue.DynamoLockManager 
  --conf spark.sql.catalog.glue_catalog.lock.table=<your-dynamodb-table-name>
  ```

**使用不同的 Iceberg 版本**

若要使用 AWS Glue 不支援的 Iceberg 版本，請使用 `--extra-jars`任務參數指定您自己的 Iceberg JAR 檔案。請勿包括 `iceberg` 作為 `--datalake-formats` 參數的值。如果您使用 AWS Glue 5.0 或更新版本，則必須設定`--user-jars-first true`任務參數。

**啟用 Iceberg 資料表的加密**

**注意**  
Iceberg 資料表具有自己的機制來啟用伺服器端加密。除了 Glue AWS 的安全組態之外，您應該啟用此組態。

若要在 Iceberg 資料表上啟用伺服器端加密，請檢閱 [Iceberg 文件](https://iceberg.apache.org/docs/latest/aws/#s3-server-side-encryption)中的指引。

**新增 Iceberg 跨區域的 Spark 組態**

若要使用 Glue Data Catalog 為 Iceberg 跨區域資料表存取新增額外的 Spark AWS 組態 AWS Lake Formation，請遵循下列步驟：

1. 建立[多區域存取點](https://docs.aws.amazon.com/AmazonS3/latest/userguide/multi-region-access-point-create-examples.html)。

1. 設定下列 Spark 屬性：

   ```
   -----
       --conf spark.sql.catalog.my_catalog.s3.use-arn-region-enabled=true \
       --conf spark.sql.catalog.{CATALOG}.s3.access-points.bucket1", "arn:aws:s3::<account-id>:accesspoint/<mrap-id>.mrap \
       --conf spark.sql.catalog.{CATALOG}.s3.access-points.bucket2", "arn:aws:s3::<account-id>:accesspoint/<mrap-id>.mrap
   -----
   ```

## 範例：將 Iceberg 資料表寫入 Amazon S3，並將其註冊到 AWS Glue Data Catalog
<a name="aws-glue-programming-etl-format-iceberg-write"></a>

此範例指令碼示範如何將 Iceberg 資料表寫入 Amazon S3。此範例使用 [Iceberg AWS 整合](https://iceberg.apache.org/docs/latest/aws/)將資料表註冊至 AWS Glue Data Catalog。

------
#### [ Python ]

```
# Example: Create an Iceberg table from a DataFrame 
# and register the table to Glue Data Catalog

dataFrame.createOrReplaceTempView("tmp_<your_table_name>")

query = f"""
CREATE TABLE glue_catalog.<your_database_name>.<your_table_name>
USING iceberg
TBLPROPERTIES ("format-version"="2")
AS SELECT * FROM tmp_<your_table_name>
"""
spark.sql(query)
```

------
#### [ Scala ]

```
// Example: Example: Create an Iceberg table from a DataFrame
// and register the table to Glue Data Catalog

dataFrame.createOrReplaceTempView("tmp_<your_table_name>")

val query = """CREATE TABLE glue_catalog.<your_database_name>.<your_table_name>
USING iceberg
TBLPROPERTIES ("format-version"="2")
AS SELECT * FROM tmp_<your_table_name>
"""
spark.sql(query)
```

------

或者，您可使用 Spark 方法將 Iceberg 資料表寫入 Amazon S3 和 Data Catalog。

先決條件：您需要佈建目錄才能使用 Iceberg 程式庫。使用 AWS Glue Data Catalog 時， AWS Glue 會直接執行此操作。Glue Data Catalog AWS 已預先設定為供 Spark 程式庫使用，做為 `glue_catalog`。資料目錄資料表由 *databaseName* 和 *tableName* 識別。如需 AWS Glue Data Catalog 的詳細資訊，請參閱 [中的資料探索和目錄編製 AWS Glue](catalog-and-crawler.md)。

如果您不是使用 AWS Glue Data Catalog，則需要透過 Spark APIs佈建目錄。如需詳細資訊，請參閱 Iceberg 文件中的 [Spark 組態](https://iceberg.apache.org/docs/latest/spark-configuration/)。

此範例使用 Spark 將 Iceberg 資料表寫入至 Amazon S3 和 Data Catalog。

------
#### [ Python ]

```
# Example: Write an Iceberg table to S3 on the Glue Data Catalog

# Create (equivalent to CREATE TABLE AS SELECT)
dataFrame.writeTo("glue_catalog.databaseName.tableName") \
    .tableProperty("format-version", "2") \
    .create()

# Append (equivalent to INSERT INTO)
dataFrame.writeTo("glue_catalog.databaseName.tableName") \
    .tableProperty("format-version", "2") \
    .append()
```

------
#### [ Scala ]

```
// Example: Write an Iceberg table to S3 on the Glue Data Catalog

// Create (equivalent to CREATE TABLE AS SELECT)
dataFrame.writeTo("glue_catalog.databaseName.tableName")
    .tableProperty("format-version", "2")
    .create()

// Append (equivalent to INSERT INTO)
dataFrame.writeTo("glue_catalog.databaseName.tableName")
    .tableProperty("format-version", "2")
    .append()
```

------

## 範例：使用 Glue Data Catalog 從 Amazon S3 AWS 讀取 Iceberg 資料表
<a name="aws-glue-programming-etl-format-iceberg-read"></a>

此範例會讀取您在 [範例：將 Iceberg 資料表寫入 Amazon S3，並將其註冊到 AWS Glue Data Catalog](#aws-glue-programming-etl-format-iceberg-write) 中建立的 Iceberg 資料表。

------
#### [ Python ]

在此範例中，使用 `GlueContext.create\$1data\$1frame.from\$1catalog()` 方法。

```
# Example: Read an Iceberg table from Glue Data Catalog

from awsglue.context import GlueContext
from pyspark.context import SparkContext

sc = SparkContext()
glueContext = GlueContext(sc)

df = glueContext.create_data_frame.from_catalog(
    database="<your_database_name>",
    table_name="<your_table_name>",
    additional_options=additional_options
)
```

------
#### [ Scala ]

在此範例中，使用 [getCatalogSource](glue-etl-scala-apis-glue-gluecontext.md#glue-etl-scala-apis-glue-gluecontext-defs-getCatalogSource) 方法。

```
// Example: Read an Iceberg table from Glue Data Catalog

import com.amazonaws.services.glue.GlueContext
import org.apacke.spark.SparkContext

object GlueApp {
  def main(sysArgs: Array[String]): Unit = {
    val spark: SparkContext = new SparkContext()
    val glueContext: GlueContext = new GlueContext(spark)
    val df = glueContext.getCatalogSource("<your_database_name>", "<your_table_name>",
      additionalOptions = additionalOptions)
      .getDataFrame()
  }
}
```

------

## 範例：使用 Glue Data Catalog 將 `DataFrame`插入 Amazon S3 中的 Iceberg AWS 資料表
<a name="aws-glue-programming-etl-format-iceberg-insert"></a>

此範例會將資料插入您在 [範例：將 Iceberg 資料表寫入 Amazon S3，並將其註冊到 AWS Glue Data Catalog](#aws-glue-programming-etl-format-iceberg-write) 中建立的 Iceberg 資料表中。

**注意**  
此範例需要您設定`--enable-glue-datacatalog`任務參數，才能使用 AWS Glue Data Catalog 做為 Apache Spark Hive 中繼存放區。如需詳細資訊，請參閱 [在 Glue AWS 任務中使用任務參數](aws-glue-programming-etl-glue-arguments.md)。

------
#### [ Python ]

在此範例中，使用 `GlueContext.write\$1data\$1frame.from\$1catalog()` 方法。

```
# Example: Insert into an Iceberg table from Glue Data Catalog

from awsglue.context import GlueContext
from pyspark.context import SparkContext

sc = SparkContext()
glueContext = GlueContext(sc)

glueContext.write_data_frame.from_catalog(
    frame=dataFrame,
    database="<your_database_name>",
    table_name="<your_table_name>",
    additional_options=additional_options
)
```

------
#### [ Scala ]

在此範例中，使用 [getCatalogSink](glue-etl-scala-apis-glue-gluecontext.md#glue-etl-scala-apis-glue-gluecontext-defs-getCatalogSink) 方法。

```
// Example: Insert into an Iceberg table from Glue Data Catalog

import com.amazonaws.services.glue.GlueContext
import org.apacke.spark.SparkContext

object GlueApp {
  def main(sysArgs: Array[String]): Unit = {
    val spark: SparkContext = new SparkContext()
    val glueContext: GlueContext = new GlueContext(spark)
    glueContext.getCatalogSink("<your_database_name>", "<your_table_name>",
      additionalOptions = additionalOptions)
      .writeDataFrame(dataFrame, glueContext)
  }
}
```

------

## 範例：使用 Spark 從 Amazon S3 讀取 Iceberg 資料表
<a name="aws-glue-programming-etl-format-iceberg-read-spark"></a>

先決條件：您需要佈建目錄才能使用 Iceberg 程式庫。使用 AWS Glue Data Catalog 時， AWS Glue 會直接執行此操作。Glue Data Catalog AWS 已預先設定為供 Spark 程式庫使用，做為 `glue_catalog`。資料目錄資料表由 *databaseName* 和 *tableName* 識別。如需 AWS Glue Data Catalog 的詳細資訊，請參閱 [中的資料探索和目錄編製 AWS Glue](catalog-and-crawler.md)。

如果您不是使用 AWS Glue Data Catalog，則需要透過 Spark APIs佈建目錄。如需詳細資訊，請參閱 Iceberg 文件中的 [Spark 組態](https://iceberg.apache.org/docs/latest/spark-configuration/)。

此範例使用 Spark 從資料目錄讀取 Amazon S3 中的 Iceberg 資料表。

------
#### [ Python ]

```
# Example: Read an Iceberg table on S3 as a DataFrame from the Glue Data Catalog

dataFrame = spark.read.format("iceberg").load("glue_catalog.databaseName.tableName")
```

------
#### [ Scala ]

```
// Example: Read an Iceberg table on S3 as a DataFrame from the Glue Data Catalog

val dataFrame = spark.read.format("iceberg").load("glue_catalog.databaseName.tableName")
```

------

## 範例：使用 Lake Formation 權限控制讀取和寫入 Iceberg 資料表
<a name="aws-glue-programming-etl-format-iceberg-read-write-lake-formation-tables"></a>

此範例會使用 Lake Formation 權限控制讀取和寫入 Iceberg 資料表。

**注意**  
此範例僅適用於 AWS Glue 4.0。在 AWS Glue 5.0 和更新版本中，請遵循 中的指引。 [搭配 AWS 使用 Glue AWS Lake Formation 進行精細存取控制](security-lf-enable.md)

1. 建立 Iceberg 資料表，並在 Lake Formation 進行註冊：

   1. 若要啟用 Lake Formation 權限控制，您將需要先在 Lake Formation 中註冊資料表 Amazon S3 路徑。如需詳細資訊，請參閱 [Registering an Amazon S3 location](https://docs.aws.amazon.com/lake-formation/latest/dg/register-location.html) (註冊 Amazon S3 位置)。您可以從 Lake Formation 主控台或使用 CLI AWS 註冊：

      ```
      aws lakeformation register-resource --resource-arn arn:aws:s3:::<s3-bucket>/<s3-folder> --use-service-linked-role --region <REGION>
      ```

      註冊 Amazon S3 位置後，指向位置 （或其任何子位置） 的任何 AWS Glue 資料表都會在`GetTable`呼叫中傳回 `IsRegisteredWithLakeFormation` 參數的值為 true。

   1. 建立透過 Spark SQL 指向註冊之路徑的 Iceberg 資料表：
**注意**  
下列為 Python 範例。

      ```
      dataFrame.createOrReplaceTempView("tmp_<your_table_name>")
      
      query = f"""
      CREATE TABLE glue_catalog.<your_database_name>.<your_table_name>
      USING iceberg
      AS SELECT * FROM tmp_<your_table_name>
      """
      spark.sql(query)
      ```

      您也可以透過 Glue `CreateTable` API AWS 手動建立資料表。如需詳細資訊，請參閱[建立 Apache Iceberg 資料表](https://docs.aws.amazon.com/lake-formation/latest/dg/creating-iceberg-tables.html)。
**注意**  
`UpdateTable` API 目前不支援 Iceberg 資料表格式作為操作的輸入。

1. 將 Lake Formation 權限授予任務 IAM 角色。您可以從 Lake Formation 主控台授予許可，或使用 AWS CLI。如需詳細資訊，請參閱：https://docs.aws.amazon.com/lake-formation/latest/dg/granting-table-permissions.html

1. 讀取向 Lake Formation 註冊的 Iceberg 資料表。該程式碼與讀取未註冊之 Iceberg 資料表的程式碼相同。請注意，您的 AWS Glue 任務 IAM 角色需要具有 SELECT 許可，才能成功讀取。

   ```
   # Example: Read an Iceberg table from the AWS Glue Data Catalog
   from awsglue.context import GlueContextfrom pyspark.context import SparkContext
   
   sc = SparkContext()
   glueContext = GlueContext(sc)
   
   df = glueContext.create_data_frame.from_catalog(
       database="<your_database_name>",
       table_name="<your_table_name>",
       additional_options=additional_options
   )
   ```

1. 寫入向 Lake Formation 註冊的 Iceberg 資料表。該程式碼與寫入未註冊之 Iceberg 資料表的程式碼相同。請注意，您的 AWS Glue 任務 IAM 角色需要具有 SUPER 許可才能成功寫入。

   ```
   glueContext.write_data_frame.from_catalog(
       frame=dataFrame,
       database="<your_database_name>",
       table_name="<your_table_name>",
       additional_options=additional_options
   )
   ```

## 共用的組態參考
<a name="aws-glue-programming-etl-format-shared-reference"></a>

 您可以將以下 `format_options` 值與任何格式類型搭配使用。
+ `attachFilename`：以適當格式作為資料欄名稱使用的字串。如果您提供此選項，記錄的來源檔案名稱會附加到記錄中。參數值將用作資料欄名稱。
+ `attachTimestamp`：以適當格式作為資料欄名稱使用的字串。如果您提供此選項，記錄的來源檔案修改時間會附加到記錄中。參數值將用作資料欄名稱。