Spark:加载多个文件,单独分析,合并结果并保存

时间:2019-04-14 16:25:03

标签: python apache-spark pyspark hdfs

我是Spark的新手,也不怎么问这个问题(使用哪些术语等),所以这是我在概念上试图实现的目标的图片:

Conceptual need diagram

我有很多小的,单独的.txt“分类帐”文件(例如,带有时戳和属性值的行分隔文件)。

我想:

  1. 将每个“分类帐”文件读取到单独的数据帧中(读取:不合并为一个大数据帧);

  2. 对每个单独的数据帧执行一些基本计算,从而导致一行新的数据值;然后

  3. 将所有单独的结果行合并到最终对象中,并将其保存在以行分隔的文件中的磁盘中。

似乎(当使用谷歌搜索相关术语时)我发现的几乎每个答案都是关于将多个文件加载到单个RDD或DataFrame中,但是我确实找到了以下Scala代码:

val data = sc.wholeTextFiles("HDFS_PATH")
val files = data.map { case (filename, content) => filename}
def doSomething(file: String) = { 
println (file);

 // your logic of processing a single file comes here

 val logData = sc.textFile(file);
 val numAs = logData.filter(line => line.contains("a")).count();
 println("Lines with a: %s".format(numAs));

 // save rdd of single file processed data to hdfs comes here
}

files.collect.foreach( filename => {
    doSomething(filename)
})

...但是:

A。我不知道这是否可以并行执行读取/分析操作,并且

B。我认为它不能将结果合并为一个对象。

任何方向或建议都将不胜感激!

更新

似乎我要执行的操作(在多个文件上并行运行脚本,然后合并结果)可能需要类似thread pools(?)的内容。

为清楚起见,这是我要对通过读取“分类帐”文件创建的DataFrame执行的计算示例:

from dateutil.relativedelta import relativedelta
from datetime import datetime
from pyspark.sql.functions import to_timestamp

# Read "ledger file"
df = spark.read.json("/path/to/ledger-filename.txt")

# Convert string ==> timestamp & sort
df = (df.withColumn("timestamp", to_timestamp(df.timestamp, 'yyyy-MM-dd HH:mm:ss'))).sort('timestamp')

columns_with_age = ("location", "status")
columns_without_age = ("wh_id")

# Get the most-recent values (from the last row of the df)
row_count = df.count()
last_row = df.collect()[row_count-1]

# Create an empty "final row" dictionary
final_row = {}

# For each column for which we want to calculate an age value ...
for c in columns_with_age:

    # Initialize loop values
    target_value = last_row.__getitem__(c)
    final_row[c] = target_value
    timestamp_at_lookback = last_row.__getitem__("timestamp")
    look_back = 1
    different = False

    while not different:
        previous_row = df.collect()[row_count - 1 - look_back]
        if previous_row.__getitem__(c) == target_value:
            timestamp_at_lookback = previous_row.__getitem__("timestamp")
            look_back += 1

        else:
            different = True

    # At this point, a difference has been found, so calculate the age
    final_row["days_in_{}".format(c)] = relativedelta(datetime.now(), timestamp_at_lookback).days

因此,这样的分类帐:

+---------+------+-------------------+-----+
| location|status|          timestamp|wh_id|
+---------+------+-------------------+-----+
|  PUTAWAY|     I|2019-04-01 03:14:00|   20|
|PICKABLE1|     X|2019-04-01 04:24:00|   20|
|PICKABLE2|     X|2019-04-01 05:33:00|   20|
|PICKABLE2|     A|2019-04-01 06:42:00|   20|
|  HOTPICK|     A|2019-04-10 05:51:00|   20|
| ICEXCEPT|     A|2019-04-10 07:04:00|   20|
| ICEXCEPT|     X|2019-04-11 09:28:00|   20|
+---------+------+-------------------+-----+

可以减少到(假设计算是在2019-04-14进行的):

{ '_id': 'ledger-filename', 'location': 'ICEXCEPT', 'days_in_location': 4, 'status': 'X', 'days_in_status': 3, 'wh_id': 20 }

2 个答案:

答案 0 :(得分:0)

不建议使用wholeTextFiles,因为它将立即将整个文件加载到内存中。如果您真的要为每个文件创建一个单独的数据框,则可以简单地使用完整路径而不是目录。但是,不建议这样做,这很可能导致不良的资源利用。相反,请考虑使用input_file_path https://spark.apache.org/docs/2.4.0/api/java/org/apache/spark/sql/functions.html#input_file_name--

例如:

spark
.read
  .textFile("path/to/files")
  .withColumn("file", input_file_name())
  .filter($"value" like "%a%")
  .groupBy($"file")
  .agg(count($"value"))
  .show(10, false)
+----------------------------+------------+
|file                        |count(value)|
+----------------------------+------------+
|path/to/files/1.txt         |2           |
|path/to/files/2.txt         |4           |
+----------------------------+------------+

因此文件可以单独处理,然后再组合。

答案 1 :(得分:0)

您可以在hdfs中获取文件路径

import  org.apache.hadoop.fs.{FileSystem,Path}

val files=FileSystem.get( sc.hadoopConfiguration ).listStatus( new Path(your_path)).map( x => x.getPath ).map(x=> "hdfs://"+x.toUri().getRawPath())

为每个路径创建唯一的数据框

val arr_df= files.map(spark.read.format("csv").option("delimeter", ",").option("header", true).load(_))

在合并到一个数据帧之前应用过滤器或任何变换

val df= arr_df.map(x=> x.where(your_filter)).reduce(_ union _)
相关问题