UDF仅从Spark SQL中的路径中提取文件名

cin*_*ata 5 java scala apache-spark apache-spark-sql spark-dataframe

Apache Spark中有input_file_name函数,我用它来向Dataset添加新列,其中包含当前正在处理的文件名.

问题是我想以某种方式自定义此函数以仅返回文件名,在s3上省略它的完整路径.

现在,我正在使用map函数替换第二步中的路径:

val initialDs = spark.sqlContext.read
.option("dateFormat", conf.dateFormat)
.schema(conf.schema)
.csv(conf.path).withColumn("input_file_name", input_file_name)
...
...
def fromFile(fileName: String): String = {
  val baseName: String = FilenameUtils.getBaseName(fileName)
  val tmpFileName: String = baseName.substring(0, baseName.length - 8) //here is magic conversion ;)
  this.valueOf(tmpFileName)
}
Run Code Online (Sandbox Code Playgroud)

但我想用类似的东西

val initialDs = spark.sqlContext.read
    .option("dateFormat", conf.dateFormat)
    .schema(conf.schema)
    .csv(conf.path).withColumn("input_file_name", **customized_input_file_name_function**)
Run Code Online (Sandbox Code Playgroud)

mrs*_*vas 8

在斯卡拉:

#register udf
spark.udf
  .register("get_only_file_name", (fullPath: String) => fullPath.split("/").last)

#use the udf to get last token(filename) in full path
val initialDs = spark.read
  .option("dateFormat", conf.dateFormat)
  .schema(conf.schema)
  .csv(conf.path)
  .withColumn("input_file_name", get_only_file_name(input_file_name))
Run Code Online (Sandbox Code Playgroud)

编辑:在Java中根据评论

#register udf
spark.udf()
  .register("get_only_file_name", (String fullPath) -> {
     int lastIndex = fullPath.lastIndexOf("/");
     return fullPath.substring(lastIndex, fullPath.length - 1);
    }, DataTypes.StringType);

import org.apache.spark.sql.functions.input_file_name    

#use the udf to get last token(filename) in full path
Dataset<Row> initialDs = spark.read()
  .option("dateFormat", conf.dateFormat)
  .schema(conf.schema)
  .csv(conf.path)
  .withColumn("input_file_name", get_only_file_name(input_file_name()));
Run Code Online (Sandbox Code Playgroud)


aar*_*ers 5

借用这里的相关问题,以下方法更加可移植,并且不需要自定义 UDF。

Spark SQL 代码片段: reverse(split(path, '/'))[0]

Spark SQL 示例:

WITH sample_data as (
SELECT 'path/to/my/filename.txt' AS full_path
)
SELECT
      full_path
    , reverse(split(full_path, '/'))[0] as basename
FROM sample_data
Run Code Online (Sandbox Code Playgroud)

说明:split()函数将路径分成多个块,并将reverse()最后一项(文件名)放在数组前面,以便[0]可以仅提取文件名。

完整代码示例在这里:

  spark.sql(
    """
      |WITH sample_data as (
      |    SELECT 'path/to/my/filename.txt' AS full_path
      |  )
      |  SELECT
      |  full_path
      |  , reverse(split(full_path, '/'))[0] as basename
      |  FROM sample_data
      |""".stripMargin).show(false)

Run Code Online (Sandbox Code Playgroud)

结果 :

+-----------------------+------------+
|full_path              |basename    |
+-----------------------+------------+
|path/to/my/filename.txt|filename.txt|
+-----------------------+------------+
Run Code Online (Sandbox Code Playgroud)