2016-05-18 15 views
6

Tôi có một thùng chứa S3 chứa 1000 tệp. Mỗi khoảng 1 GB. Tôi muốn đọc mẫu ngẫu nhiên của các tập tin này. Giả sử 5% của tất cả các tệp. Đây là cách tôi làm điều đóĐọc mẫu ngẫu nhiên các tập tin trên S3 với Pyspark

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

Nhưng có vẻ như ở trên mã sẽ đọc tất cả các tập tin và sau đó lấy mẫu. Trong khi tôi muốn lấy mẫu các tập tin và đọc chúng. Ai đó có thể giúp?

+0

Self.path là gì? Nó có sử dụng globbing không? – nkadwa

+0

_self.path_ là một biến tự trong Python. – neikusc

Trả lời

2

Sử dụng phương pháp ưa thích của bạn vào danh sách các file theo đường dẫn, lấy mẫu trong những cái tên, và sau đó sử dụng RDD đoàn:

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) 

Dưới đây là một khả năng thực hiện nhanh chóng và bẩn "list_files" mà sẽ liệt kê các tệp trong "thư mục" trên 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 
+0

Đây là một ý tưởng tuyệt vời. Cảm ơn bạn rất nhiều vì câu trả lời của bạn! – neikusc

Các vấn đề liên quan