

# Creación de la tabla para los registros de CloudTrail en Athena mediante la proyección de particiones
<a name="create-cloudtrail-table-partition-projection"></a>

Dado que los registros de CloudTrail tienen una estructura conocida cuyo esquema de partición puede especificar de antemano, puede reducir el tiempo de ejecución de las consultas y automatizar la administración de particiones mediante la característica de proyección de particiones de Athena. La proyección de particiones agrega de forma automática nuevas particiones a medida que se agregan nuevos datos. Esto hace que no sea necesario agregar particiones manualmente mediante `ALTER TABLE ADD PARTITION`. 

En el siguiente ejemplo, la instrucción `CREATE TABLE` utiliza automáticamente la proyección de particiones en los registros de CloudTrail desde una fecha especificada hasta el presente para una sola Región de AWS. En las cláusulas `LOCATION` y `storage.location.template`, reemplace los marcadores de posición {{bucket}}, {{account-id}} y {{aws-region}} por valores idénticos en consecuencia. Para `projection.timestamp.range`, reemplace {{2020}}/{{01}}/{{01}} por la fecha de inicio que quiere utilizar. Una vez ejecutada la consulta correctamente, puede consultar la tabla. No tiene que ejecutar `ALTER TABLE ADD PARTITION` para cargar las particiones.

```
CREATE EXTERNAL TABLE cloudtrail_logs_pp(
    eventversion STRING,
    useridentity STRUCT<
        type: STRING,
        principalid: STRING,
        arn: STRING,
        accountid: STRING,
        invokedby: STRING,
        accesskeyid: STRING,
        username: STRING,
        onbehalfof: STRUCT<
             userid: STRING,
             identitystorearn: STRING>,
        sessioncontext: STRUCT<
            attributes: STRUCT<
                mfaauthenticated: STRING,
                creationdate: STRING>,
            sessionissuer: STRUCT<
                type: STRING,
                principalid: STRING,
                arn: STRING,
                accountid: STRING,
                username: STRING>,
            ec2roledelivery:string,
            webidfederationdata: STRUCT<
                federatedprovider: STRING,
                attributes: map<string,string>>
        >
    >,
    eventtime STRING,
    eventsource STRING,
    eventname STRING,
    awsregion STRING,
    sourceipaddress STRING,
    useragent STRING,
    errorcode STRING,
    errormessage STRING,
    requestparameters STRING,
    responseelements STRING,
    additionaleventdata STRING,
    requestid STRING,
    eventid STRING,
    readonly STRING,
    resources ARRAY<STRUCT<
        arn: STRING,
        accountid: STRING,
        type: STRING>>,
    eventtype STRING,
    apiversion STRING,
    recipientaccountid STRING,
    serviceeventdetails STRING,
    sharedeventid STRING,
    vpcendpointid STRING,
    vpcendpointaccountid STRING,
    eventcategory STRING,
    addendum STRUCT<
      reason:STRING,
      updatedfields:STRING,
      originalrequestid:STRING,
      originaleventid:STRING>,
    sessioncredentialfromconsole STRING,
    edgedevicedetails STRING,
    tlsdetails STRUCT<
      tlsversion:STRING,
      ciphersuite:STRING,
      clientprovidedhostheader:STRING>
  )
PARTITIONED BY (
   `timestamp` string)
ROW FORMAT SERDE 'org.apache.hive.hcatalog.data.JsonSerDe'
STORED AS INPUTFORMAT 'com.amazon.emr.cloudtrail.CloudTrailInputFormat'
OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
LOCATION
  's3://amzn-s3-demo-bucket/AWSLogs/{{account-id}}/{{CloudTrail}}/{{aws-region}}'
TBLPROPERTIES (
  'projection.enabled'='true', 
  'projection.timestamp.format'='yyyy/MM/dd', 
  'projection.timestamp.interval'='1', 
  'projection.timestamp.interval.unit'='DAYS', 
  'projection.timestamp.range'='{{2020}}/{{01}}/{{01}},NOW', 
  'projection.timestamp.type'='date', 
  'storage.location.template'='s3://amzn-s3-demo-bucket/AWSLogs/{{account-id}}/{{CloudTrail}}/{{aws-region}}/${timestamp}')
```

Para obtener más información sobre la proyección de particiones, consulte [Uso de proyección de particiones con Amazon Athena](partition-projection.md).