【问题标题】:how to read all the files under a directory in s3 using spark df?如何使用spark df读取s3目录下的所有文件?
【发布时间】:2022-01-18 17:49:53
【问题描述】:

我在这个模式中有 490 个 JSON 文件 657438009821376.json 不同文件的所有不同数字。

我可以用吗 '''val input = spark.read.option("header", true).json("/path/to/data/[0-9]*.json")'''

我需要将所有 490 个文件读入单个 DF

【问题讨论】:

  • 我需要使用 JSON 文件的最后一位来抓取所有文件。那么,我可以使用这个____________________[0-9]*.json

标签: amazon-s3 pyspark bigdata


【解决方案1】:

您提供文件路径或目录路径作为源。 https://spark.apache.org/docs/latest/sql-data-sources-json.html

没有选项可以在实际加载之前过滤掉特定文件。加载它们,您可以映射它们的源文件名并过滤掉不必要的文件,但我不建议这样做

我建议你可以分几步完成:

  • 使用 boto3 客户端列出来自 s3 存储桶的所有匹配文件,就像那样
import boto
import boto.s3
import re

pattern = re.compile("your_regexp_pattern")

bucket = boto.s3.connect_to_region('eu-central-1').get_bucket("BUCKET_NAME")
files = bucket.list("","/path/to-dir")
filteredFiles = filter(lambda filename: pattern.match(filename), files)

  • 为从 s3 读取为 json 的 spark 提供文件列表
your_schema_class = StructType() \
    .add("first_name", StringType()) \
    .add("last_name", StringType())

# From step 1:
# files = ["s3://1.json", "s3://2.json"]
df = spark.read.json(files, your_schema_class)
df.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-20
    • 2018-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-01
    • 1970-01-01
    相关资源
    最近更新 更多