

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# EMR Serverless에 대한 메타스토어 구성
<a name="metastore-config"></a>

*Hive 메타스토어*는 스키마, 파티션 이름 및 데이터 유형을 포함하여 테이블에 대한 구조 정보를 저장하는 중앙 집중식 위치입니다. EMR Serverless를 사용하면 작업에 액세스할 수 있는 메타스토어에서 이 테이블 메타데이터를 유지할 수 있습니다.

Hive 메타스토어에 대한 두 가지 옵션이 있습니다.
+  AWS Glue 데이터 카탈로그
+ 외부 Apache Hive 메타스토어

## Glue 데이터 카탈로그를 AWS 메타스토어로 사용
<a name="glue-metastore"></a>

Glue 데이터 카탈로그를 AWS 메타스토어로 사용하도록 Spark 및 Hive 작업을 구성할 수 있습니다. 영구 메타스토어가 필요하거나 여러 애플리케이션, 서비스 또는 AWS 계정에서 메타스토어를 공유해야 하는 경우에 이 구성을 사용하는 것이 좋습니다. 데이터 카탈로그에 대한 자세한 내용은 [AWS Glue 데이터 카탈로그 채우기를 참조하세요](https://docs.aws.amazon.com/glue/latest/dg/populate-data-catalog.html). AWS Glue 요금에 대한 자세한 내용은 [AWS Glue 요금을](https://aws.amazon.com/glue/pricing) 참조하세요.

애플리케이션 AWS 계정 과 동일한 또는 다른에서 AWS Glue 데이터 카탈로그를 사용하도록 EMR Serverless 작업을 구성할 수 있습니다 AWS 계정.

### AWS Glue 데이터 카탈로그 구성
<a name="glue-metastore-configure"></a>

Data Catalog를 구성하려면 사용할 EMR Serverless 애플리케이션 유형을 선택합니다.

------
#### [ Spark ]

EMR Studio를 사용하여 EMR Serverless Spark 애플리케이션에서 작업을 실행하는 경우 Glue 데이터 카탈로그가 기본 AWS 메타스토어입니다.

SDKs 사용하는 경우 작업 실행의 `sparkSubmit` 파라미터`com.amazonaws.glue.catalog.metastore.AWSGlueDataCatalogHiveClientFactory`에서 `spark.hadoop.hive.metastore.client.factory.class` 구성을 로 AWS CLI설정합니다. 다음 예제에서는 AWS CLI를 사용하여 Data Catalog를 구성하는 방법을 보여줍니다.

```
aws emr-serverless start-job-run \
    --application-id application-id \
    --execution-role-arn job-role-arn \
    --job-driver '{
        "sparkSubmit": {
            "entryPoint": "s3://amzn-s3-demo-bucket/code/pyspark/extreme_weather.py",
            "sparkSubmitParameters": "--conf spark.hadoop.hive.metastore.client.factory.class=com.amazonaws.glue.catalog.metastore.AWSGlueDataCatalogHiveClientFactory --conf spark.driver.cores=1 --conf spark.driver.memory=3g --conf spark.executor.cores=4 --conf spark.executor.memory=3g"
        }
    }'
```

또는 Spark 코드에서 새 `SparkSession`을 생성할 때 이 구성을 설정할 수 있습니다.

```
from pyspark.sql import SparkSession

spark = (
    SparkSession.builder.appName("SparkSQL")
    .config(
        "spark.hadoop.hive.metastore.client.factory.class",
        "com.amazonaws.glue.catalog.metastore.AWSGlueDataCatalogHiveClientFactory",
    )
    .enableHiveSupport()
    .getOrCreate()
)

# we can query tables with SparkSQL
spark.sql("SHOW TABLES").show()

# we can also them with native Spark
print(spark.catalog.listTables())
```

------
#### [ Hive ]

EMR Serverless Hive 애플리케이션의 경우 Data Catalog가 기본 메타스토어입니다. 즉, EMR Serverless Hive 애플리케이션에서 작업을 실행하면 Hive는 애플리케이션 AWS 계정 과 동일한의 데이터 카탈로그에 메타스토어 정보를 기록합니다. Data Catalog를 메타스토어로 사용하기 위해 가상 프라이빗 클라우드(VPC)가 필요하지 않습니다.

Hive 메타스토어 테이블에 액세스하려면 AWS Glue에 [대한 IAM 권한 설정에 설명된 필수 AWS Glue](https://docs.aws.amazon.com/glue/latest/dg/getting-started-access.html) 정책을 추가합니다.

------

### EMR Serverless 및 AWS Glue 데이터 카탈로그에 대한 교차 계정 액세스 구성
<a name="glue-metastore-cross-account"></a>

EMR Serverless에 대한 교차 계정 액세스를 설정하려면 먼저 AWS 계정다음에 로그인합니다.
+ `AccountA` - EMR Serverless 애플리케이션을 생성한 AWS 계정 입니다.
+ `AccountB` - EMR Serverless 작업이 액세스하도록 실행하려는 AWS Glue 데이터 카탈로그가 AWS 계정 포함된 입니다.

1. `AccountB`의 관리자 또는 기타 승인된 자격 증명이 `AccountB`의 Data Catalog에 리소스 정책을 연결해야 합니다. 이 정책은 `AccountB` 카탈로그의 리소스에서 작업을 수행할 수 있는 `AccountA`별 교차 계정 권한을 부여합니다.

------
#### [ JSON ]

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": [
       {
         "Effect": "Allow",
         "Action": [
           "glue:GetDatabase",
           "glue:CreateDatabase",
           "glue:GetDataBases",
           "glue:CreateTable",
           "glue:GetTable",
           "glue:UpdateTable",
           "glue:DeleteTable",
           "glue:GetTables",
           "glue:GetPartition",
           "glue:GetPartitions",
           "glue:CreatePartition",
           "glue:BatchCreatePartition",
           "glue:GetUserDefinedFunctions"
         ],
         "Resource": [
           "arn:aws:glue:*:123456789012:catalog"
         ],
         "Sid": "AllowGLUEGetdatabase"
       }
     ]
   }
   ```

------

1. 역할이 `AccountB`의 Data Catalog 리소스에 액세스할 수 있도록 `AccountA`에서 EMR Serverless 작업 런타임 역할에 IAM 정책을 추가합니다.

------
#### [ JSON ]

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": [
       {
         "Effect": "Allow",
         "Action": [
           "glue:GetDatabase",
           "glue:CreateDatabase",
           "glue:GetDataBases",
           "glue:CreateTable",
           "glue:GetTable",
           "glue:UpdateTable",
           "glue:DeleteTable",
           "glue:GetTables",
           "glue:GetPartition",
           "glue:GetPartitions",
           "glue:CreatePartition",
           "glue:BatchCreatePartition",
           "glue:GetUserDefinedFunctions"
         ],
         "Resource": [
           "arn:aws:glue:*:123456789012:catalog"
         ],
         "Sid": "AllowGLUEGetdatabase"
       }
     ]
   }
   ```

------

1.  작업 실행을 시작합니다. 이 단계는 `AccountA`의 EMR Serverless 애플리케이션 유형에 따라 약간 다릅니다.

------
#### [ Spark ]

   다음 예제와 같이 `spark.hadoop.hive.metastore.glue.catalogid`에서 `sparkSubmitParameters` 속성을 설정합니다. *`AccountB-catalog-id`*를 `AccountB`의 Data Catalog ID로 바꿉니다.

   ```
   aws emr-serverless start-job-run \
   --application-id "application-id" \
   --execution-role-arn "job-role-arn" \
   --job-driver '{
       "sparkSubmit": {
           "entryPoint": "s3://amzn-s3-demo-bucket/scripts/test.py",
            "sparkSubmitParameters": "--conf spark.hadoop.hive.metastore.client.factory.class=com.amazonaws.glue.catalog.metastore.AWSGlueDataCatalogHiveClientFactory --conf spark.hadoop.hive.metastore.glue.catalogid=AccountB-catalog-id --conf spark.executor.cores=1 --conf spark.executor.memory=1g --conf spark.driver.cores=1 --conf spark.driver.memory=1g --conf spark.executor.instances=1"
       }
     }' \
   --configuration-overrides '{
       "monitoringConfiguration": {
       "s3MonitoringConfiguration": {
       "logUri": "s3://amzn-s3-demo-bucket/logs/"
       }
     }
   }'
   ```

------
#### [ Hive ]

   다음 예제와 같이 `hive.metastore.glue.catalogid` 분류에서 `hive-site` 속성을 설정합니다. *`AccountB-catalog-id`*를 `AccountB`의 Data Catalog ID로 바꿉니다.

   ```
   aws emr-serverless start-job-run \
   --application-id "application-id" \
   --execution-role-arn "job-role-arn" \
   --job-driver '{
       "hive": {
       "query": "s3://amzn-s3-demo-bucket/hive/scripts/create_table.sql",
       "parameters": "--hiveconf hive.exec.scratchdir=s3://amzn-s3-demo-bucket/hive/scratch --hiveconf hive.metastore.warehouse.dir=s3://amzn-s3-demo-bucket/hive/warehouse"
       }
   }' \
   --configuration-overrides '{
       "applicationConfiguration": [{
           "classification": "hive-site",
           "properties": {
               "hive.metastore.glue.catalogid": "AccountB-catalog-id"
           }
       }]
   }'
   ```

------

### AWS Glue 데이터 카탈로그 사용 시 고려 사항
<a name="glue-metastore-considerations"></a>

Hive 스크립트에서 `ADD JAR`을 사용하여 보조 JAR을 추가할 수 있습니다. 추가 고려 사항은 [AWS Glue 데이터 카탈로그 사용 시 고려 사항을](https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-hive-metastore-glue.html#emr-hive-glue-considerations-hive) 참조하세요.

# 외부 Hive 메타스토어 사용
<a name="external-metastore"></a>

Amazon Aurora 또는 Amazon RDS for MySQL과 같은 외부 Hive 메타스토어에 연결하도록 EMR Serverless Spark 및 Hive 작업을 구성할 수 있습니다. 이 섹션에서는 Amazon RDS Hive 메타스토어를 설정하고, VPC를 구성하며, 외부 메타스토어를 사용하도록 EMR Serverless 작업을 구성하는 방법을 설명합니다.

## 외부 Hive 메타스토어 생성
<a name="external-metastore-create"></a>

1. [VPC 생성](https://docs.aws.amazon.com/vpc/latest/userguide/working-with-vpcs.html#Create-VPC)의 지침에 따라 프라이빗 서브넷이 있는 Amazon Virtual Private Cloud(Amazon VPC)를 생성합니다.

1. 새 Amazon VPC 및 프라이빗 서브넷을 사용하여 EMR Serverless 애플리케이션을 생성합니다. VPC에서 EMR Serverless 애플리케이션을 구성하는 경우 먼저 지정한 각 서브넷에 대해 탄력적 네트워크 인터페이스를 프로비저닝합니다. 그러면 지정된 보안 그룹이 해당 네트워크 인터페이스에 연결합니다. 이렇게 하면 애플리케이션 액세스 제어 기능이 지원됩니다. VPC를 설정하는 방법에 대한 자세한 내용은 [데이터에 연결하도록 EMR Serverless 애플리케이션에 대한 VPC 액세스 구성](vpc-access.md) 섹션을 참조하세요.

1. Amazon VPC의 프라이빗 서브넷에서 MySQL 또는 Aurora PostgreSQL 데이터베이스를 생성합니다. Amazon RDS 데이터베이스 생성 방법에 대한 자세한 내용은 [Amazon RDS DB 인스턴스 생성](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_CreateDBInstance.html)을 참조하세요.

1. [Amazon RDS DB 인스턴스 수정](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Overview.DBInstance.Modifying.html)의 단계에 따라 EMR Serverless 보안 그룹에서 JDBC 연결을 허용하도록 MySQL 또는 Aurora 데이터베이스의 보안 그룹을 수정합니다. EMR Serverless 보안 그룹 중 하나에서 RDS 보안 그룹에 인바운드 트래픽 규칙을 추가합니다.    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/emr/latest/EMR-Serverless-UserGuide/external-metastore.html)

## Spark 옵션 구성
<a name="external-metastore-spark"></a>

**JDBC 사용**

Amazon RDS for MySQL 또는 Amazon Aurora MySQL 인스턴스를 기반으로 Hive 메타스토어에 연결하도록 EMR Serverless Spark 애플리케이션을 구성하려면 JDBC 연결을 사용합니다. 작업 실행의 `spark-submit` 파라미터에서 `--jars`와 함께 `mariadb-connector-java.jar`을 전달합니다.

```
aws emr-serverless start-job-run \
  --application-id "application-id" \
  --execution-role-arn "job-role-arn" \
  --job-driver '{
        "sparkSubmit": {
            "entryPoint": "s3://amzn-s3-demo-bucket/scripts/spark-jdbc.py",
            "sparkSubmitParameters": "--jars s3://amzn-s3-demo-bucket/mariadb-connector-java.jar 
            --conf spark.hadoop.javax.jdo.option.ConnectionDriverName=org.mariadb.jdbc.Driver 
            --conf spark.hadoop.javax.jdo.option.ConnectionUserName=<connection-user-name> 
            --conf spark.hadoop.javax.jdo.option.ConnectionPassword=<connection-password>
            --conf spark.hadoop.javax.jdo.option.ConnectionURL=<JDBC-Connection-string> 
            --conf spark.driver.cores=2
            --conf spark.executor.memory=10G 
            --conf spark.driver.memory=6G 
            --conf spark.executor.cores=4"
        }
    }' \
    --configuration-overrides '{
        "monitoringConfiguration": {
        "s3MonitoringConfiguration": {
            "logUri": "s3://amzn-s3-demo-bucket/spark/logs/"
        }
    }
}'
```

다음 코드 예제는 Amazon RDS에서 Hive 메타스토어와 상호 작용하는 Spark 진입점 스크립트입니다.

```
from os.path import expanduser, join, abspath
from pyspark.sql import SparkSession
from pyspark.sql import Row
# warehouse_location points to the default location for managed databases and tables
warehouse_location = abspath('spark-warehouse')
spark = SparkSession \
    .builder \
    .config("spark.sql.warehouse.dir", warehouse_location) \
    .enableHiveSupport() \
    .getOrCreate()
spark.sql("SHOW DATABASES").show()
spark.sql("CREATE EXTERNAL TABLE `sampledb`.`sparknyctaxi`(`dispatching_base_num` string, `pickup_datetime` string, `dropoff_datetime` string, `pulocationid` bigint, `dolocationid` bigint, `sr_flag` bigint) STORED AS PARQUET LOCATION 's3://<s3 prefix>/nyctaxi_parquet/'")
spark.sql("SELECT count(*) FROM sampledb.sparknyctaxi").show()
spark.stop()
```

**Thrift 서비스 사용**

Amazon RDS for MySQL 또는 Amazon Aurora MySQL 인스턴스를 기반으로 Hive 메타스토어에 연결하도록 EMR Serverless Hive 애플리케이션을 구성할 수 있습니다. 이를 수행하려면 기존 Amazon EMR 클러스터의 기본 노드에서 Thrift 서버를 실행합니다. 이 옵션은 EMR Serverless 작업 구성을 단순화하는 데 사용할 Thrift 서버가 있는 Amazon EMR 클러스터가 이미 있는 경우에 적합합니다.

```
aws emr-serverless start-job-run \
  --application-id "application-id" \
  --execution-role-arn "job-role-arn" \
  --job-driver '{
        "sparkSubmit": {
            "entryPoint": "s3://amzn-s3-demo-bucket/thriftscript.py",
            "sparkSubmitParameters": "--jars s3://amzn-s3-demo-bucket/mariadb-connector-java.jar 
            --conf spark.driver.cores=2
            --conf spark.executor.memory=10G 
            --conf spark.driver.memory=6G 
            --conf spark.executor.cores=4"
        }
    }' \
    --configuration-overrides '{
        "monitoringConfiguration": {
        "s3MonitoringConfiguration": {
            "logUri": "s3://amzn-s3-demo-bucket/spark/logs/"
        }
    }
}'
```

다음 코드 예제는 Thrift 프로토콜을 사용하여 Hive 메타스토어에 연결하는 진입점 스크립트(`thriftscript.py`)입니다. `hive.metastore.uris` 속성은 외부 Hive 메타스토어에서 읽도록 설정해야 합니다.

```
from os.path import expanduser, join, abspath
from pyspark.sql import SparkSession
from pyspark.sql import Row
# warehouse_location points to the default location for managed databases and tables
warehouse_location = abspath('spark-warehouse')
spark = SparkSession \
    .builder \
    .config("spark.sql.warehouse.dir", warehouse_location) \
    .config("hive.metastore.uris","thrift://thrift-server-host:thift-server-port") \
    .enableHiveSupport() \
    .getOrCreate()
spark.sql("SHOW DATABASES").show()
spark.sql("CREATE EXTERNAL TABLE sampledb.`sparknyctaxi`( `dispatching_base_num` string, `pickup_datetime` string, `dropoff_datetime` string, `pulocationid` bigint, `dolocationid` bigint, `sr_flag` bigint) STORED AS PARQUET LOCATION 's3://<s3 prefix>/nyctaxi_parquet/'")
spark.sql("SELECT * FROM sampledb.sparknyctaxi").show()
spark.stop()
```

## Hive 옵션 구성
<a name="external-metastore-hive"></a>

**JDBC 사용**

Amazon RDS MySQL 또는 Amazon Aurora 인스턴스에서 외부 Hive 데이터베이스 위치를 지정하려는 경우 기본 메타스토어 구성을 재정의할 수 있습니다.

**참고**  
Hive에서 메타스토어 테이블에 대한 여러 쓰기를 동시에 수행할 수 있습니다. 두 클러스터 사이에서 메타스토어 정보를 공유하는 경우, 동일한 메타스토어 테이블의 다른 파티션에 쓰고 있지 않은 한, 동시에 동일한 메타스토어 테이블에 쓰지 않도록 해야 합니다.

`hive-site` 분류에서 다음 구성을 설정하여 외부 Hive 메타스토어를 활성화합니다.

```
{
    "classification": "hive-site",
    "properties": {
        "hive.metastore.client.factory.class": "org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClientFactory",
        "javax.jdo.option.ConnectionDriverName": "org.mariadb.jdbc.Driver",
        "javax.jdo.option.ConnectionURL": "jdbc:mysql://db-host:db-port/db-name",
        "javax.jdo.option.ConnectionUserName": "username",
        "javax.jdo.option.ConnectionPassword": "password"
    }
}
```

**Thrift 서버 사용**

Amazon RDS for MySQL 또는 Amazon Aurora MySQL 인스턴스를 기반으로 Hive 메타스토어에 연결하도록 EMR Serverless Hive 애플리케이션을 구성할 수 있습니다. 이를 수행하려면 기존 Amazon EMR 클러스터의 메인 노드에서 Thrift 서버를 실행합니다. 이 옵션은 Thrift 서버를 실행하고 EMR Serverless 작업 구성을 사용하려는 Amazon EMR 클러스터가 이미 있는 경우에 적합합니다.

EMR Serverless가 원격 Thrift 메타스토어에 액세스할 수 있도록 `hive-site` 분류에서 다음 구성을 설정합니다. 외부 Hive 메타스토어에서 읽도록 `hive.metastore.uris` 속성을 설정해야 합니다.

```
{
    "classification": "hive-site",
    "properties": {
        "hive.metastore.client.factory.class": "org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClientFactory",
        "hive.metastore.uris": "thrift://thrift-server-host:thirft-server-port"
    }
}
```

# EMR Serverless에서 AWS Glue 다중 카탈로그 계층 구조 작업
<a name="external-metastore-glue-multi"></a>

 AWS Glue 다중 카탈로그 계층 구조에서 작동하도록 EMR Serverless 애플리케이션을 구성할 수 있습니다. 다음 예제에서는 AWS Glue 다중 카탈로그 계층 구조에서 EMR-S Spark를 사용하는 방법을 보여줍니다.

다중 카탈로그 계층 구조에 대해 자세히 알아보려면 [Amazon EMR에서 Spark를 사용하여 AWS Glue Data Catalog의 다중 카탈로그 계층 구조 작업을 참조하세요](https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-multi-catalog.html).

## Iceberg 및 AWS Glue 데이터 카탈로그와 함께 Redshift Managed Storage(RMS) 사용
<a name="emr-serverless-lf-enable-spark-session-glue"></a>

다음은 Iceberg와 AWS Glue 데이터 카탈로그의 통합을 위해 Spark를 구성하는 방법을 보여줍니다.

```
aws emr-serverless start-job-run \
    --application-id application-id \
    --execution-role-arn job-role-arn \
    --job-driver '{
        "sparkSubmit": {
            "entryPoint": "s3://amzn-s3-demo-bucket/myscript.py",
            "sparkSubmitParameters": "--conf spark.sql.catalog.nfgac_rms = org.apache.iceberg.spark.SparkCatalog
             --conf spark.sql.catalog.rms.type=glue 
             --conf spark.sql.catalog.rms.glue.id=Glue RMS catalog ID 
             --conf spark.sql.defaultCatalog=rms
             --conf spark.sql.extensions=org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions"
        }
    }'
```

통합 후 카탈로그에 있는 테이블의 샘플 쿼리:

```
SELECT * FROM my_rms_schema.my_table
```

## Iceberg REST API 및 AWS Glue 데이터 카탈로그와 함께 Redshift Managed Storage(RMS) 사용
<a name="emr-serverless-lf-enable-spark-session-rest"></a>

다음은 Spark를 Iceberg REST 카탈로그와 함께 작동하도록 구성하는 방법을 보여줍니다.

```
aws emr-serverless start-job-run \
--application-id application-id \
--execution-role-arn job-role-arn \
--job-driver '{
"sparkSubmit": {
"entryPoint": "s3://amzn-s3-demo-bucket/myscript.py",
    "sparkSubmitParameters": "
    --conf spark.sql.catalog.rms=org.apache.iceberg.spark.SparkCatalog
    --conf spark.sql.catalog.rms.type=rest
    --conf spark.sql.catalog.rms.warehouse=Glue RMS catalog ID
    --conf spark.sql.catalog.rms.uri=Glue endpoint URI/iceberg
    --conf spark.sql.catalog.rms.rest.sigv4-enabled=true
    --conf spark.sql.catalog.rms.rest.signing-name=glue
    --conf spark.sql.extensions=org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions"
    }
  }'
```

카탈로그에 있는 테이블의 샘플 쿼리:

```
SELECT * FROM my_rms_schema.my_table
```

# 외부 메타스토어 사용 시 고려 사항
<a name="external-metastore-considerations"></a>
+ MariaDB JDBC와 호환되는 데이터베이스를 메타스토어로 구성할 수 있습니다. 이러한 데이터베이스의 예로는, RDS for MariaDB, MySQL, Amazon Aurora가 있습니다.
+ 메타스토어는 자동으로 초기화되지 않습니다. 메타스토어가 Hive 버전의 스키마로 초기화되지 않은 경우 [Hive 스키마 도구](https://cwiki.apache.org/confluence/display/Hive/Hive+Schema+Tool)를 사용합니다.
+ EMR Serverless는 Kerberos 인증을 지원하지 않습니다. EMR Serverless Spark 또는 Hive 작업에서는 Kerberos 인증과 함께 Thrift 메타스토어 서버를 사용할 수 없습니다.
+ 다중 카탈로그 계층 구조를 사용하도록 VPC 액세스를 구성합니다.