我正在尝试从一个数据框中读取数据并在另一个数据框中使用它。我怎么能优雅地做到这一点?
val query = s"select distinct p_id, lower(regexp_replace(p_id,'[^a-zA-Z0-9]+','_')) as p_id_formatted, lower(regexp_extract(f_id,'^([^\\.]+)\\.?',1)) as f_id_formatted, column_name from default.rc_pcoders"
val run_query = sql(query)
val table_name = run_query.select(concat(lit("nepp"), lit("_"),$"p_id_formatted", lit("_") ,$"f_id_formatted ").alias("tablename"),$"column_name")
这给了我以下输出,它基本上代表了一个表名
+------------------+-----------+
|tablename |column_name|
+------------------+-----------+
|nepp_148hl16011_cm|cmtrt |
|nepp_148hl16011_mh|mhaspe |
|nepp_148hl16011_ae|aeputt |
+------------------+-----------+
如何从每个表中获取列名?类似的东西(下面的查询不起作用)
val whole_query = sql("show columns in "table_name.tablename"")
答案 0 :(得分:1)
首先,收集要加载的表的所有名称:
val tableNames = df.collect().map(row => row.getAs[String]("tablename")).toSeq
其次,获取对相应DataFrame的引用,将它们与列名相关联
val sqlCtx: SQLContext = // your SQL context ref
val dfToColumns = tableNames.map(table => {
val columnNames = sqlCtx.table(table).schema.fieldNames.toSeq
(table, columnNames)
}).toMap
dfToColumns
是Map[String, Seq[String]]
,其中DataFrame名称为键,其各自列名称的Seq为值。