

# Amazon DocumentDB 연결
<a name="aws-glue-programming-etl-connect-documentdb-home"></a>

AWS Glue for Spark를 사용하여 Amazon DocumentDB 데이터베이스의 테이블에서 읽고 쓸 수 있습니다. AWS Glue 연결을 통해 AWS Secrets Manager에 저장된 보안 인증 정보를 사용하여 Amazon DocumentDB에 연결할 수 있습니다.

Amazon DocumentDB에 대한 자세한 내용은 [Amazon DocumentDB 설명서](https://docs.aws.amazon.com/documentdb/latest/developerguide/what-is.html)를 참조하세요.

**참고**  
Amazon DocumentDB Elastic Clusters는 현재 AWS Glue 커넥터를 사용하는 경우 지원되지 않습니다. Elastic Clusters에 대한 자세한 내용은 [Using Amazon DocumentDB elastic clusters](https://docs.aws.amazon.com/documentdb/latest/developerguide/docdb-using-elastic-clusters.html)를 참조하세요.

## Amazon DocumentDB 컬렉션 읽기 및 쓰기
<a name="aws-glue-programming-etl-connect-documentdb-read-write"></a>

**참고**  
Amazon DocumentDB에 연결하는 ETL 작업을 생성할 때 `Connections` 작업 속성에 대해 Amazon DocumentDB가 실행 중인 Virtual Private Cloud(VPC)를 지정하는 연결 객체를 지정해야 합니다. 연결 객체의 경우 연결 유형은 `JDBC`여야 하며 `JDBC URL`은 `mongo://<DocumentDB_host>:27017`이어야 합니다.

**참고**  
이 코드 샘플은 AWS Glue 3.0용으로 개발되었습니다. AWS Glue 4.0으로 마이그레이션하려면 [MongoDB](migrating-version-40.md#migrating-version-40-connector-driver-migration-mongodb) 섹션을 참조하세요. `uri` 파라미터가 변경되었습니다.

**참고**  
Amazon DocumentDB를 사용하는 경우 작성된 문서에서 `_id`를 지정하는 경우와 같은 특정 상황에서는 `retryWrites`를 false로 설정해야 합니다. 자세한 내용은 Amazon DocumentDB 설명서에서 [Functional Differences with MongoDB](https://docs.aws.amazon.com/documentdb/latest/developerguide/functional-differences.html#functional-differences.retryable-writes)를 참조하세요.

다음 Python 스크립트는 Amazon DocumentDB를 읽고 쓰기 위한 연결 유형 및 연결 옵션을 사용하는 방법을 보여줍니다.

```
import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext, SparkConf
from awsglue.context import GlueContext
from awsglue.job import Job
import time

## @params: [JOB_NAME]
args = getResolvedOptions(sys.argv, ['JOB_NAME'])

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

job = Job(glueContext)
job.init(args['JOB_NAME'], args)

output_path = "s3://some_bucket/output/" + str(time.time()) + "/"
documentdb_uri = "mongodb://<mongo-instanced-ip-address>:27017"
documentdb_write_uri = "mongodb://<mongo-instanced-ip-address>:27017"

read_docdb_options = {
    "uri": documentdb_uri,
    "database": "test",
    "collection": "coll",
    "username": "username",
    "password": "1234567890",
    "ssl": "true",
    "ssl.domain_match": "false",
    "partitioner": "MongoSamplePartitioner",
    "partitionerOptions.partitionSizeMB": "10",
    "partitionerOptions.partitionKey": "_id"
}

write_documentdb_options = {
    "retryWrites": "false",
    "uri": documentdb_write_uri,
    "database": "test",
    "collection": "coll",
    "username": "username",
    "password": "pwd"
}

# Get DynamicFrame from  DocumentDB
dynamic_frame2 = glueContext.create_dynamic_frame.from_options(connection_type="documentdb",
                                                               connection_options=read_docdb_options)

# Write DynamicFrame to MongoDB and DocumentDB
glueContext.write_dynamic_frame.from_options(dynamic_frame2, connection_type="documentdb",
                                             connection_options=write_documentdb_options)

job.commit()
```

다음 Scala 스크립트는 Amazon DocumentDB를 읽고 쓰기 위한 연결 유형 및 연결 옵션을 사용하는 방법을 보여줍니다.

```
import com.amazonaws.services.glue.GlueContext
import com.amazonaws.services.glue.MappingSpec
import com.amazonaws.services.glue.errors.CallSite
import com.amazonaws.services.glue.util.GlueArgParser
import com.amazonaws.services.glue.util.Job
import com.amazonaws.services.glue.util.JsonOptions
import com.amazonaws.services.glue.DynamicFrame
import org.apache.spark.SparkContext
import scala.collection.JavaConverters._

object GlueApp {
  val DOC_URI: String = "mongodb://<mongo-instanced-ip-address>:27017"
  val DOC_WRITE_URI: String = "mongodb://<mongo-instanced-ip-address>:27017"
  lazy val documentDBJsonOption = jsonOptions(DOC_URI)
  lazy val writeDocumentDBJsonOption = jsonOptions(DOC_WRITE_URI)
  def main(sysArgs: Array[String]): Unit = {
    val spark: SparkContext = new SparkContext()
    val glueContext: GlueContext = new GlueContext(spark)
    val args = GlueArgParser.getResolvedOptions(sysArgs, Seq("JOB_NAME").toArray)
    Job.init(args("JOB_NAME"), glueContext, args.asJava)

    // Get DynamicFrame from DocumentDB
    val resultFrame2: DynamicFrame = glueContext.getSource("documentdb", documentDBJsonOption).getDynamicFrame()

    // Write DynamicFrame to DocumentDB
    glueContext.getSink("documentdb", writeJsonOption).writeDynamicFrame(resultFrame2)

    Job.commit()
  }

  private def jsonOptions(uri: String): JsonOptions = {
    new JsonOptions(
      s"""{"uri": "${uri}",
         |"database":"test",
         |"collection":"coll",
         |"username": "username",
         |"password": "pwd",
         |"ssl":"true",
         |"ssl.domain_match":"false",
         |"partitioner": "MongoSamplePartitioner",
         |"partitionerOptions.partitionSizeMB": "10",
         |"partitionerOptions.partitionKey": "_id"}""".stripMargin)
  }
}
```

## Amazon DocumentDB 연결 옵션 참조
<a name="aws-glue-programming-etl-connect-documentdb"></a>

Amazon DocumentDB에 대한 연결을 지정합니다(MongoDB와 호환).

연결 옵션은 소스 연결 및 싱크 연결에 따라 다릅니다.

### 소스로서의 "connectionType": "Documentdb"
<a name="etl-connect-documentdb-as-source"></a>

소스로서의 `"connectionType": "documentdb"`에는 다음 연결 옵션을 사용합니다.
+ `"uri"`: (필수 사항) 읽을 소스 Amazon DocumentDB 호스트로, `mongodb://<host>:<port>` 포맷입니다.
+ `"database"`: (필수) 읽을 소스 Amazon DocumentDB 데이터베이스입니다.
+ `"collection"`: (필수) 읽을 소스 Amazon DocumentDB 컬렉션입니다.
+ `"username"`: (필수) Amazon DocumentDB 사용자 이름입니다.
+ `"password"`: (필수) Amazon DocumentDB 암호입니다.
+ `"ssl"`: (SSL을 사용하는 경우 필수) 연결에서 SSL을 사용하는 경우 `"true"` 값과 함께 이 옵션을 포함해야 합니다.
+ `"ssl.domain_match"`: (SSL을 사용하는 경우 필수) 연결에서 SSL을 사용하는 경우 `"false"` 값과 함께 이 옵션을 포함해야 합니다.
+ `"batchSize"`: (선택 사항) 내부 배치의 커서 내에서 사용되는 배치당 반환할 문서 수입니다.
+ `"partitioner"`: (선택 사항) Amazon DocumentDB에서 입력 데이터를 읽는 파티셔너의 클래스 이름입니다. 커넥터는 다음 파티셔너를 제공합니다.
  + `MongoDefaultPartitioner`(기본값)(AWS Glue 4.0에서는 지원되지 않음)
  + `MongoSamplePartitioner`(AWS Glue 4.0에서는 지원되지 않음)
  + `MongoShardedPartitioner`
  + `MongoSplitVectorPartitioner`
  + `MongoPaginateByCountPartitioner`
  + `MongoPaginateBySizePartitioner`(AWS Glue 4.0에서는 지원되지 않음)
+ `"partitionerOptions"`: (선택 사항) 지정된 파티셔너에 대한 옵션입니다. 각 파티셔너에 대해 다음 옵션이 지원됩니다.
  + `MongoSamplePartitioner`: `partitionKey`, `partitionSizeMB`, `samplesPerPartition`
  + `MongoShardedPartitioner`: `shardkey`
  + `MongoSplitVectorPartitioner`: `partitionKey`, partitionSizeMB
  + `MongoPaginateByCountPartitioner`: `partitionKey`, `numberOfPartitions`
  + `MongoPaginateBySizePartitioner`: `partitionKey`, partitionSizeMB

  이러한 옵션에 대한 자세한 내용은 MongoDB 설명서의 [파티셔너 구성](https://docs.mongodb.com/spark-connector/master/configuration/#partitioner-conf)을 참조하십시오.

### 싱크로서의 "connectionType": "Documentdb"
<a name="etl-connect-documentdb-as-sink"></a>

싱크로서의 `"connectionType": "documentdb"`에는 다음 연결 옵션을 사용합니다.
+ `"uri"`: (필수 사항) 쓸 대상 Amazon DocumentDB 호스트로, `mongodb://<host>:<port>` 포맷입니다.
+ `"database"`: (필수) 쓸 대상 Amazon DocumentDB 데이터베이스입니다.
+ `"collection"`: (필수) 쓸 대상 소스 Amazon DocumentDB 컬렉션입니다.
+ `"username"`: (필수) Amazon DocumentDB 사용자 이름입니다.
+ `"password"`: (필수) Amazon DocumentDB 암호입니다.
+ `"extendedBsonTypes"`: (선택 사항) `true`이면 데이터를 Amazon DocumentDB에 쓸 때 확장 BSON 유형을 허용합니다. 기본값은 `true`입니다.
+ `"replaceDocument"`: (선택 사항) `true`이면 `_id` 필드가 포함된 데이터 세트를 저장할 때 전체 문서를 대체합니다. `false`이면 데이터 세트의 필드와 일치하는 문서의 필드만 업데이트됩니다. 기본값은 `true`입니다.
+ `"maxBatchSize"`: (선택 사항) 데이터를 저장할 때 대량 작업의 최대 배치 크기입니다. 기본값은 512입니다.
+ `"retryWrites"`: (선택 사항): AWS Glue에서 네트워크 오류가 발생하는 경우 특정 쓰기 작업을 한 번 자동으로 재시도합니다.