gpt4 book ai didi

hadoop - 在 sparksql 中设置 textinputformat.record.delimiter

转载 作者:可可西里 更新时间:2023-11-01 15:10:04 26 4
gpt4 key购买 nike

在 spark2.0.1 和 hadoop2.6.0 中,我有很多文件用 '!@!\r' 分隔,而不是通常的换行符\n,例如:

=========================================

2001810086 rongq 2001 810!@!
2001810087 hauaa 2001 810!@!
2001820081 hello 2001 820!@!
2001820082 jaccy 2001 820!@!
2002810081 cindy 2002 810!@!

=========================================

我尝试根据Setting textinputformat.record.delimiter in spark提取数据set textinputformat.record.delimiter='!@!\r';set textinputformat.record.delimiter='!@!\n';但仍然无法提取数据

在 spark-sql 中,我这样做:===== ================================

create table ceshi(id int,name string, year string, major string)
row format delimited
fields terminated by '\t';

load data local inpath '/data.txt' overwrite into table ceshi;
select count(*) from ceshi;

结果是 5,但我尝试 set textinputformat.record.delimiter='!@!\r';然后 select count(*) from ceshi; 结果是 1,分隔符不工作;

我还检查了hadoop2.6.0的源代码,TextInputFormat.java中RecordReader的方法,我注意到默认的textinputformat.record.delimiter为null,然后LineReader.java使用方法readDefaultLine读取由CR、LF 或 CRLF 之一(CR ='\r',LF ='\n')。

最佳答案

您应该使用 sparkContexthadoopConfiguration api 将 textinputformat.record.delimiter 设置为

sc.hadoopConfiguration.set("textinputformat.record.delimiter", "!@!\r")

然后,如果您使用 sparkContext 作为

读取文本文件
sc.textFile("the input file path")

你应该没问题。

已更新

我注意到保存时带有分隔符 \r 的文本文件更改为 \n 分隔符。

所以,下面的格式应该对你有用,就像对我一样

sc.hadoopConfiguration.set("textinputformat.record.delimiter", "!@!\n")
val data = sc.textFile("the input file path")
val df = data.map(line => line.split("\t"))
.map(array => ceshi(array(0).toInt, array(1), array(2), array(3)))
.toDF

需要一个名为ceshi案例类

case class ceshi(id: Int, name: String, year: String, major :String)

应该给数据框作为

+----------+-----+-----+-----+
|id |name |year |major|
+----------+-----+-----+-----+
|2001810086|rongq| 2001|810 |
|2001810087|hauaa| 2001|810 |
|2001820081|hello| 2001|820 |
|2001820082|jaccy| 2001|820 |
|2002810081|cindy| 2002|810 |
+----------+-----+-----+-----+

现在你可以点击count函数了

import org.apache.spark.sql.functions._
df.select(count("*")).show(false)

输出为

+--------+
|count(1)|
+--------+
|5 |
+--------+

关于hadoop - 在 sparksql 中设置 textinputformat.record.delimiter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45250048/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com