如何使用Boto3从AWS Glue Data Catalog获取数据库中表的定义
让我们看看一个用户如何从AWS Glue数据目录中检索与正则表达式匹配的所有表或部分表的定义。
阅读更多:Python 教程
示例
检索数据库 ‘QA-test’ 中所有表的表定义和表 ‘security’ 和 ’employee’ .
解决此问题的方法/算法
- 步骤1: 导入 boto3 和 botocore 异常以处理异常情况。
-
步骤2: database_name 是必填参数,而 regular_expression_for_table_name 是可选参数。如果用户想要获取所有表的详细信息,则无需提供正则表达式。但是,如果只需要获取一些表,那么需要提供一个正则表达式。在编写正则表达式时要小心,因为如果编写不正确,结果可能会发生变化。
-
步骤3: 使用 boto3 lib 创建一个AWS会话。确保在默认配置文件中指定了 region_name 。如果没有指定,则在创建会话时显式传递region_name。
-
步骤4: 为 glue 创建一个AWS客户端。
-
步骤5: 现在使用get_tables函数,传递 database_name 作为DatabaseName和 regular_expression_for_table_name 作为Expression参数。
-
步骤6: 它返回给定数据库中所有或匹配表的定义。
-
步骤7: 如果在检查工作时出现任何问题,请处理通用异常。
示例代码
以下代码从给定的数据库中检索所有表的表定义 −
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'}, {'Name': 'securitycode', 'Type': 'char'}, {'Name': 'contractsize', 'Type': 'string'}, {'Name': 'conversionperiodenddate', 'Type': 'string'}, {'Name': 'conversionperiodstartdate', 'Type': 'string'}, {'Name': 'expirationdate', 'Type': 'string'}, {'Name': 'issuercountrycode', 'Type': 'string'}, {'Name': 'issuercountrydesc', 'Type': 'string'}, {'Name': 'originalissuedate', 'Type': 'string'}, {'Name': 'securitynamelong', 'Type': 'string'}, {'Name': 'issueshortname', 'Type': 'string'}, {'Name': 'gicssector', 'Type': 'string'}, {'Name': 'maturitydate', 'Type': 'string'}, {'Name': 'optioncode', 'Type': 'string'}, {'Name': 'optiontypename', 'Type': 'string'}, {'Name': 'paramount', 'Type': 'string'}, {'Name': 'priceindex', 'Type': 'string'}, {'Name': 'countrycoderisk', 'Type': 'string'}, {'Name': 'countrydescrisk', 'Type': 'string'}, {'Name': 'countrycode', 'Type': 'string'}], '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': {'CrawlerSchemaDeserializerVersion': '1.0', 'CrawlerSchemaSerializerVersion': '1.0', 'UPDATED_BY_CRAWLER': 'security', 'averageRecordSize': '181', 'classification': 'parquet', 'compressionType': 'none', 'objectCount': '5', 'recordCount': '154800', 'sizeKey': '20337230', 'typeOfData': 'file'}, 'CreatedBy': 'arn:aws:sts::*********:assumed-role/glue-role/AWS-Crawler'}, 'VersionId': '2'},
{'Name': 'employee', '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'}, {'Name': 'code', 'Type': 'char'}, {'Name': 'size', 'Type': 'string'}, {'Name': 'countrycode', 'Type': 'string'}, {'Name': 'countrydesc', 'Type': 'string'}], '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': {'CrawlerSchemaDeserializerVersion': '1.0', 'CrawlerSchemaSerializerVersion': '1.0', 'UPDATED_BY_CRAWLER': 'employee', 'averageRecordSize': '181', 'classification': 'parquet', 'compressionType': 'none', 'objectCount': '5', 'recordCount': '154800', 'sizeKey': '20337230', 'typeOfData': 'file'}, 'CreatedBy': 'arn:aws:sts::*********:assumed-role/glue-role/AWS-Crawler'}, 'VersionId': '2'}, 'ResponseMetadata': {'RequestId': '431db171-*******************0', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Mon, 01 Mar 2021 06:15:30 GMT', 'content-type': 'application/x-amz-json-1.1', 'content-length': '3916', 'connection': 'keep-alive', 'x-amzn-requestid': '431db171-*****************0'}, 'RetryAttempts': 0}}
极客教程