【AWS】AWS Glue ~ Boto3 / DB・テーブル操作編 ~

■ はじめに

https://dk521123.hatenablog.com/entry/2021/06/09/113458

の続き。

今回は、Glue で使用するテーブル情報取得および作成について扱う。

 (本当は、テーブル操作までにするつもりだったが)
「【2】テーブル作成」の際に「EntityNotFoundException」が発生した際に
DBがないっとのエラーだったので、「【4】DB作成」についても扱ってみる

目次

【0】Boto3 API仕様
【1】テーブル情報取得
【2】テーブル削除
【3】テーブル作成
【4】DB作成

【0】Boto3 API仕様

* 前回同様に、以下を探れば、使用したいAPIは見つかるはず。

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/glue.html#client

【1】テーブル情報取得

* get_table() を使う

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/glue.html#Glue.Client.get_table

response = client.get_table(
    CatalogId='string',
    DatabaseName='string',
    Name='string'
)

Exceptions

Glue.Client.exceptions.EntityNotFoundException
Glue.Client.exceptions.InvalidInputException
Glue.Client.exceptions.InternalServiceException
Glue.Client.exceptions.OperationTimeoutException
Glue.Client.exceptions.GlueEncryptionException

サンプル

import boto3
try:
  from botocore.exceptions import BotoCoreError, ClientError
except ImportError:
  pass

# 取得対象の情報
target_db = 'sample_db'
target_table = 'person'

try:
  glue_client = boto3.client('glue', region_name='us-west-2')

  response = glue_client.get_table(
      DatabaseName=target_db,
      TableName=target_table,
      PartitionValues=[target_partition_value]
  )
  table_info = response['Table']
  print(table_info)
except(BotoCoreError, ClientError) as ex:
  if ex.response['Error']['Code'] == 'EntityNotFoundException':
    print(f'The table [{target_db}.{target_table}] has been not found...')
  else:
    print('Error ' + str(ex))

print("Done")

【2】テーブル削除

* delete_table() / batch_delete_table() を使う
 => 「【3】テーブル作成」で例外「AlreadyExistsException」が発生した際に
  テーブル削除してから、再作成するなどに使える

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/glue.html#Glue.Client.delete_table
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/glue.html#Glue.Client.batch_delete_table

response = client.delete_table(
    CatalogId='string',
    DatabaseName='string',
    Name='string'
)

【3】テーブル作成

* create_table() を使う

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/glue.html#Glue.Client.create_table

response = client.create_table(
    CatalogId='string',
    DatabaseName='string',
    TableInput={
        'Name': 'string',
       ・・・略・・・
        'StorageDescriptor': {
            'Columns': [
                {
                    'Name': 'string',
                    'Type': 'string',
                    'Comment': 'string',
                    'Parameters': {
                        'string': 'string'
                    }
                },
            ],
            'Location': 'string',
            'InputFormat': 'string',
            'OutputFormat': 'string',
            'Compressed': True|False,
            ・・・略・・・
            },
・・・略・・・
)

Exceptions

Glue.Client.exceptions.AlreadyExistsException
Glue.Client.exceptions.InvalidInputException
Glue.Client.exceptions.EntityNotFoundException ... ※
Glue.Client.exceptions.ResourceNumberLimitExceededException
Glue.Client.exceptions.InternalServiceException
Glue.Client.exceptions.OperationTimeoutException
Glue.Client.exceptions.GlueEncryptionException

※
 ブログの冒頭でも触れたが、テーブル作成するのに、
なんで「EntityNotFoundException」があるんだろうって思ったが
指定するDB名がない場合に、発生するみたい

サンプル

import boto3
try:
  from botocore.exceptions import BotoCoreError, ClientError
except ImportError:
  pass

# 作成対象の情報
target_db = 'sample_db'
target_table = 'person'

try:
  glue_client = boto3.client('glue', region_name='us-west-2')

  input_table = {
         'Name': target_table ,
     # ... 略 ...
  }
  response = glue_client.create_table(
      DatabaseName=target_db,
      TableInput=input_table
  )
  print(response)
except(BotoCoreError, ClientError) as ex:
  if ex.response['Error']['Code'] == 'AlreadyExistsException':
    print(f'The table [{target_db}.{target_table}] already exists...')

    print(f'Delete and create the table [{target_db}.{target_table}].')
    glue_client.delete_table(DatabaseName=target_db, Name=target_table)
    glue_client.create_table(DatabaseName=target_db, TableInput=input_table)
  else:
    print('Error ' + str(ex))

print("Done")

【4】DB作成

* create_database() を使う
 => ただ、後から知ったが、
  AWS Management Console画面の [Databases]-[Add database]でも作成は可能。

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/glue.html#Glue.Client.create_database
Exceptions

Glue.Client.exceptions.InvalidInputException
Glue.Client.exceptions.AlreadyExistsException
Glue.Client.exceptions.ResourceNumberLimitExceededException
Glue.Client.exceptions.InternalServiceException
Glue.Client.exceptions.OperationTimeoutException
Glue.Client.exceptions.GlueEncryptionException

サンプル

import boto3
try:
  from botocore.exceptions import BotoCoreError, ClientError
except ImportError:
  pass

# 作成対象の情報
target_db = 'sample_db'

try:
  glue_client = boto3.client('glue', region_name='us-west-2')

  response = glue_client.create_database(
      DatabaseInput={
        'Name': target_db,
        'Description': 'For test'
      }
  )
  print(response)
except(BotoCoreError, ClientError) as ex:
  if ex.response['Error']['Code'] == 'AlreadyExistsException':
    print(f'The DB [{target_db}] already exists...')
  else:
    print('Error ' + str(ex))

print("Done")

関連記事

AWS Glue ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2019/10/01/221926
AWS Glue ~ 基本編 / クローラ ~ https://dk521123.hatenablog.com/entry/2019/12/01/003455
AWS Glue ~ Boto3 / 入門編 ~
https://dk521123.hatenablog.com/entry/2019/10/14/000000
AWS Glue ~ Boto3 / 基本編 ~
https://dk521123.hatenablog.com/entry/2021/04/17/001930
AWS Glue ~ Boto3 / セキュリティ設定編 ~
https://dk521123.hatenablog.com/entry/2020/04/08/171208
AWS Glue ~ Boto3 / Glue connection編 ~
https://dk521123.hatenablog.com/entry/2020/01/29/224525
AWS Glue ~ Boto3 / パーティション操作編 ~
https://dk521123.hatenablog.com/entry/2021/06/09/113458