Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ดึงนิยามตาราง (Table Definition) จากฐานข้อมูลใน AWS Glue Data Catalog ด้วย Boto3

ใช้ Boto3 ดึงนิยามตารางทั้งหมด หรือตารางที่ Match ตาม Regular Expression จาก Database ใน AWS Glue Data Catalog

ตัวอย่าง

ดึงนิยามตารางใน Database QA-test ตาราง security และ employee

ขั้นตอน/อัลกอริทึม

  1. Import boto3 และ botocore.exceptions.ClientError
  2. database_name บังคับ, regular_expression_for_table_name ทางเลือก
  3. สร้าง AWS Session และ Glue Client
  4. เรียก get_tables(DatabaseName=database_name, Expression=regular_expression_for_table_name)
  5. คืนค่ารายการตาราง
  6. จัดการ Exception

ตัวอย่างโค้ด

import boto3
from botocore.exceptions import ClientError

def retrieves_tables_detail(database_name, regular_expression_for_table_name=None):
    session = boto3.session.Session()
    glue_client = session.client('glue')
    try:
        response = glue_client.get_tables(DatabaseName=database_name, Expression=regular_expression_for_table_name)
        return response
    except ClientError as e:
        raise Exception("boto3 client error in retrieves_tables_detail: " + e.__str__())
    except Exception as e:
        raise Exception("Unexpected error in retrieves_tables_detail: " + e.__str__())

print(retrieves_tables_detail('QA-test'))

ผลลัพธ์

{'TableList': [{'Name': 'security', 'DatabaseName': 'QA-test', 'Owner': 'owner', 'CreateTime': datetime.datetime(2020, 9, 10, 22, 27, 24, tzinfo=tzlocal()), 'UpdateTime': datetime.datetime(2021, 3, 1, 11, 43, 49, tzinfo=tzlocal()), 'LastAccessTime': datetime.datetime(2020, 9, 10, 22, 27, 24, tzinfo=tzlocal()), 'Retention': 0, 'StorageDescriptor': {'Columns': [{'Name': 'assettypecode', 'Type': 'string'}, {'Name': 'industrysector', 'Type': 'varchar'}, ...], 'Location': 's3://test/security/', 'InputFormat': 'org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat', 'OutputFormat': 'org.apache.hadoop.hive.ql.io.parquet.MapredParquetOutputFormat', 'Compressed': False, 'NumberOfBuckets': -1, 'SerdeInfo': {'SerializationLibrary': 'org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe', 'Parameters': {'serialization.format': '1'}}, 'BucketColumns': [], 'SortColumns': [], 'Parameters': {'CrawlerSchemaDeserializerVersion': '1.0', 'CrawlerSchemaSerializerVersion': '1.0', 'UPDATED_BY_CRAWLER': 'security', 'averageRecordSize': '181', 'classification': 'parquet', 'compressionType': 'none', 'objectCount': '5', 'recordCount': '154800', 'sizeKey': '20337230', 'typeOfData': 'file'}, 'StoredAsSubDirectories': False}, 'PartitionKeys': [], 'TableType': 'EXTERNAL_TABLE', 'Parameters': {...}, 'CreatedBy': 'arn:aws:sts::*********:assumed-role/glue-role/AWS-Crawler', 'VersionId': '2'}, {'Name': 'employee', ...}], 'ResponseMetadata': {...}}