我想要查找某些Hive表中满足特定条件的所有列。然而,我写的代码非常慢,因为Spark并不是一个特别喜欢循环的人:
matches = {}
for table in table_list:
matching_cols = [c for c in spark.read.table(table).columns if substring in c]
if matching_cols:
matches[table] = matching_cols
我想要这样的东西:
matches = {'table1': ['column1', 'column2'], 'table2': ['column2']}
我怎样才能更有效地达到同样的效果?
发布于 2018-08-01 02:59:18
一位同事刚刚发现了这个问题。这是修改后的解决方案:
matches = {}
for table in table_list:
matching_cols = spark.sql("describe {}".format(table)) \
.where(col('col_name').rlike(substring)) \
.collect()
if matching_cols:
matches[table] = [c.col_name for c in matching_cols]
这里的关键区别在于,在我之前的示例中,Spark似乎正在缓存分区信息,因此它在每个循环中变得越来越停滞。访问元数据来抓取列,而不是表本身,可以绕过这个问题。
发布于 2018-08-01 08:45:18
如果表字段有注释上面的代码将进入额外的信息(注释)的问题,也侧记HBase链接表也将被发布…
示例:
create TABLE deck_test (
COLOR string COMMENT 'COLOR Address',
SUIT string COMMENT '4 type Suits',
PIP string)
ROW FORMAT DELIMITED FIELDS TERMINATED by '|'
STORED AS TEXTFILE;
describe deck_test;
color string COLOR Address
suit string 4 type Suits
pip string
处理评论问题的小改动可能会有所帮助……
matches = {}
for table in table_list:
matching_cols = spark.sql("show columns in {}".format(table)).where(col('result').rlike(substring)).collect()
if matching_cols:
matches[table] = [c.col_name for c in matching_cols]
https://stackoverflow.com/questions/51619464
复制相似问题