有没有办法一次清除多个表?

时间:2020-04-27 04:03:39

标签: google-cloud-platform google-bigquery

我想清除存储在bigquery特定数据集中的表。

在控制台屏幕上,您无法一次删除多个表。

也无法使用bq CLI中的*删除。

是否可以一次清除多个表?

2 个答案:

答案 0 :(得分:1)

虽然在documentation中,您一次只能删除一个表,但可以使用Python脚本提出API请求,以便删除数据集中的所有表。

我创建并测试了以下脚本:

from google.cloud import bigquery

#construct BigQuery client object
client = bigquery.Client()

#select your dataset and list the tables within it 
dataset_id='project_id.dataset'
tables = client.list_tables(dataset_id)  

#inititalizing the list of tables
list_tables=[]
    
for table in tables:
    #Create a list with the able reference for deletion 'project.dataset_id.table_id'
    id =".".join([table.project,table.dataset_id,table.table_id])
    list_tables.append(id)
    
    #List of tables
    print(list_tables)

#Delete all the tables inside the list of tables     
for table in list_tables:
    #print(table)
    client.delete_table(table)
    
print("{} {}".format("Number of deleted tables in the dataset:", len(list_tables)))

我使用带有Python 3的Jupyter Notebook执行了以上代码。如果在云Shell环境中运行它,请确保安装了所有依赖项pip install --upgrade google-cloud-bigquery

答案 1 :(得分:0)

我也遇到类似的情况,并使用下面的Java代码删除了大量表。

替换数据集和table_prefix值。

将服务帐户JSON密钥文件路径设置为GOOGLE_APPLICATION_CREDENTIALS环境变量。

代码:

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;

public class TableKiller {
    String dataset = "MY_DATASET";
    String table_prefix = "temp_table_";

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        new TableKiller().deleteAll();
    }

    public void deleteAll() throws InterruptedException, ExecutionException {
        ArrayList<String> tableNames = new ArrayList<>();
        BigQuery bigQuery = BigQueryOptions.getDefaultInstance().getService();
        int i = 1;

        bigQuery.listTables(dataset, BigQuery.TableListOption.pageSize(1000))
                .iterateAll()
                .forEach(table -> {
                    String tableName = table.getTableId().getTable();
                    if (tableName.startsWith(table_prefix)) {
                        tableNames.add(tableName);
                        System.out.println("Added " + tableName + i);
                    }
                });

        ForkJoinPool forkJoinPool = new ForkJoinPool(200);
        forkJoinPool.submit(() -> tableNames
                .parallelStream()
                .forEach(this::deleteTable)).get();

    }

    private void deleteTable(String tableName) {
        BigQuery bigQuery = BigQueryOptions.getDefaultInstance().getService();
        bigQuery.delete(TableId.of(dataset, tableName));
        System.out.println("Deleted " + tableName);
    }
}