在 Databricks SQL (Spark SQL) 中,有没有一种方法可以按表、模式和目录计算行数?

问题描述 投票:0回答:2

我需要在 Databricks 中创建一个仪表板来汇总当前工作区中的行数。

有没有办法创建一个 SQL 查询来计算表、模式和目录的行数?预期的结果是:

目录 架构 桌子
example_catalog_1 金融 table_example_1 1567000
example_catalog_1 金融 table_example_2 67000
example_catalog_2 采购 table_example_1 45324888
example_catalog_2 采购 table_example_2 89765987
example_catalog_2 采购 table_example_3 145000

目前,我正在研究纯 SQL 工作流。所以我想知道是否可以使用 SQL 执行这样的操作,因为据我所知,Databricks 中的仪表板不接受 PySpark 代码。

我正在寻找一种方法来做到这一点。我知道可以使用

system.information_schema.tables
访问工作区中的表,但是如何使用它来计算那里显示的每个表的总行数?

我正在通过 SQL Server 检查是否可以通过

sys schema
dynamic query
BEGIN...END
子句。我在 Databricks 中找不到这样做的方法。

apache-spark apache-spark-sql databricks azure-databricks databricks-sql
2个回答
1
投票

我强烈怀疑您是否可以在数据块仪表板中运行那种查询。 @Sharma 共享的链接更多是关于如何使用数据框获取记录计数,而不是如何将其与数据块仪表板链接。


0
投票

我想到构建它的方法是调整@Sharma 建议的代码。当我使用 Unity Catalog 时需要它,并且此更改对于迭代目录是必要的。


_sql = """
select
  concat_ws('.', table_catalog, table_schema, table_name) as address,
  table_catalog,
  table_schema,
  table_name
from
  system.information_schema.tables as table_list
  inner join (
    select
      catalog_name
    from
      system.information_schema.catalogs
    where
      catalog_name not in ('system')
  ) as table_choose on table_choose.catalog_name = table_list.table_catalog
where
  table_schema <> 'information_schema'
  and table_type <> 'VIEW'
"""

df_result = sqlContext.sql(_sql)
df_pandas = df_result.toPandas()

for index, row in df_pandas.iterrows():
    table_address = row['address']
    print('Calculating for -> ', index +1 , ' - ' , table_address)
    _sql_query = f'select count(*) myrowcnt from {table_address}'
    
    try:
        _tmp_df = spark.sql(_sql_query)
        row_count = _tmp_df.collect()[0]['myrowcnt'] 
        print('>> Result: ', row_count)
        df_pandas.loc[index, 'total_rows'] = row_count

        _size = spark.sql(f"describe detail {table_address}").select("sizeInBytes").collect()[0]['sizeInBytes'] 
        df_pandas.loc[index, 'size_mb'] = _size/1000000
    except:
        print("!!! An error occurred !!!")
        print('Query: ', _sql_query)
        pass
© www.soinside.com 2019 - 2024. All rights reserved.