首页 > 解决方案 > AWS Glue - 如何使用 BOTO3 更改 Glue 目录表中的列名?

问题描述

我正在使用 AWS Glue Crawlers 从 S3 zip 文件(没有标题)中读取并填充 Glue 目录。

列默认命名:col_0, col_1...

如何使用例如 python boto3 模块更改这些列名并直接与 AWS Glue 目录交互?

是否有执行此操作的示例代码段?

谢谢。

标签: pythonamazon-web-servicesboto3aws-glue

解决方案


您可以尝试拉表并更新名称。这是我会做的一个例子。

首先,我们将尝试检索表:

    database_name = 'ENTER TABLE NAME'
    table_name = 'ENTER TABLE NAME'
    response = self.glue_client.get_table(DatabaseName=database_name,table_name=Name)
    old_table = response['Table']

接下来,我们将使用我们想要更改的值更新表。我们创建的新表只能包含某些字段,以便 update_table 接受它。因此,我们将执行以下操作。

    field_names = [
      "Name",
      "Description",
      "Owner",
      "LastAccessTime",
      "LastAnalyzedTime",
      "Retention",
      "StorageDescriptor",
      "PartitionKeys",
      "ViewOriginalText",
      "ViewExpandedText",
      "TableType",
      "Parameters"
    ]
    new_table = dict()
    for key in field_names:
     if key in old_table:
      new_table[key] = old_table[key]

现在我们有了更新的表,我们可以操作列名。这是将“col_0”更改为“new_col”的示例

    for col in new_table['StorageDescriptor']['Columns']:
      if col['Name'] == 'col_0':
        col['Name'] = 'new_col' 
    response=self.glue_client.update_table(DatabaseName=database_name,TableInput=new_table)

希望这会有所帮助!


推荐阅读