我在Spark中创建了数据然后执行了连接操作,最后我必须将输出保存到分区文件。
我正在将数据框转换为RDD,然后保存为允许我使用多字符分隔符的文本文件。我的问题是在这种情况下如何使用dataframe列作为自定义分区。
我不能使用以下选项进行自定义分区,因为它不支持多字符分隔符:
public static void main(final String[] args) {
try {
final String baseURL = "https://safebrowsing.googleapis.com/v4/threatMatches:find?key=xxx";
final URL url = new URL(baseURL);
// Get a URLConnection object, to write to POST method
final HttpURLConnection connect = (HttpURLConnection) url.openConnection();
connect.setRequestMethod("POST");
connect.setRequestProperty("Content-Type", "application/json");
// Specify connection settings
connect.setDoInput(true);
connect.setDoOutput(true);
final ClientInfo clientInfo = new Ggooggle().getClientInfo();
final ThreatInfo threatInfo = new Ggooggle().getThreatInfo();
final FindThreatMatchesRequest request = new FindThreatMatchesRequest();
request.setClient(clientInfo);
request.setThreatInfo(threatInfo);
要使用多字符分隔符,我已将其转换为RDD,如下面的代码:
dfMainOutput.write.partitionBy("DataPartiotion","StatementTypeCode")
.format("csv")
.option("delimiter", "^")
.option("nullValue", "")
.option("codec", "gzip")
.save("s3://trfsdisu/SPARK/FinancialLineItem/output")
但是在上面的选项中我将如何根据列" DataPartiotion"进行自定义分区。和#34; StatementTypeCode"?
我是否必须再次从RDD转换回数据帧?
这是我尝试过的代码
dfMainOutput.rdd.map(x=>x.mkString("|^|")).saveAsTextFile("dir path to store")
答案 0 :(得分:1)
这可以通过使用concat_ws
来完成,此功能与mkString
的工作方式类似,但可以直接在数据帧上执行。这使得转换步骤变为冗余,并且可以使用df.write.partitionBy()
方法。一个将连接所有可用列的小例子,
import org.apache.spark.sql.functions._
import spark.implicits._
val df = Seq(("01", "20000", "45.30"), ("01", "30000", "45.30"))
.toDF("col1", "col2", "col3")
val df2 = df.select($"DataPartiotion", $"StatementTypeCode",
concat_ws("|^|", df.schema.fieldNames.map(c => col(c)): _*).as("concatenated"))
这将为您提供这样的结果数据框,
+--------------+-----------------+------------------+
|DataPartiotion|StatementTypeCode| concatenated|
+--------------+-----------------+------------------+
| 01| 20000|01|^|20000|^|45.30|
| 01| 30000|01|^|30000|^|45.30|
+--------------+-----------------+------------------+