【问题标题】:Read random sample of files on S3 with Pyspark使用 Pyspark 读取 S3 上的随机文件样本
【发布时间】:2016-09-15 12:04:28
【问题描述】:

我在 S3 上有一个包含 1000 个文件的存储桶。每个大约 1GB。我想阅读这些文件的随机样本。假设所有文件的 5%。我就是这样做的

fileDF = sqlContext.jsonRDD(self.sc.textFile(self.path).sample(withReplacement=False, fraction=0.05, seed=42).repartition(160))

但上面的代码似乎会读取所有文件然后进行采样。虽然我想提取文件样本并阅读它们。有人可以帮忙吗?

【问题讨论】:

  • 什么是self.path?它使用通配符吗?
  • self.path 是 Python 中的 self 变量。

标签: python amazon-s3 apache-spark pyspark amazon-emr


【解决方案1】:

用你喜欢的方法列出路径下的文件,取名字的样本,然后使用RDD union:

import pyspark
import random

sc = pyspark.SparkContext(appName = "Sampler")
file_list = list_files(path)
desired_pct = 5
file_sample = random.sample(file_list, int(len(file_list) * desired_pct / 100))
file_sample_rdd = sc.emptyRDD()
for f in file_sample:
    file_sample_rdd = file_sample_rdd.union(sc.textFile(f))
sample_data_rdd = file_sample_rdd.repartition(160)

这是“list_files”的一种可能的快速而肮脏的实现,它将列出 S3 上“目录”下的文件:

import os
def list_files(path, profile = None):
    if not path.endswith("/"):
        raise Exception("not handled...")
    command = 'aws s3 ls %s' % path
    if profile is not None:
        command = 'aws --profile %s s3 ls %s' % (profile, path)
    result = os.popen(command)
    _r = result.read().strip().split('\n')
    _r = [path + i.strip().split(' ')[-1] for i in _r]
    return _r

【讨论】:

  • 这是个好主意。非常感谢您的回答!
  • for-loop 是单线程运行的吗?我不相信,但我可能错了。我希望获得相同的结果,但使用 Spark 并行读取大量“随机指定”文件路径。
猜你喜欢
  • 2018-08-08
  • 1970-01-01
  • 2022-01-11
  • 1970-01-01
  • 1970-01-01
  • 2021-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多