【问题标题】:spark-xml on jupyter notebookjupyter笔记本上的spark-xml
【发布时间】:2021-06-14 18:35:24
【问题描述】:

我正在尝试在我的 jupyter 笔记本上运行 spark-xml,以便使用 spark 读取 xml 文件。

from os import environ
environ['PYSPARK_SUBMIT_ARGS'] = '--packages com.databricks:spark-xml_2.10:0.4.1 pyspark-shell' 

我发现这是使用它的方式。但是当我尝试导入 com.databricks.spark.xml._ 时,我收到一个错误提示

没有名为“com”的模块

【问题讨论】:

  • spark-xml 主要用于 Scala,而不是 Python。见readme
  • Python 导入也没有下划线,那么您为什么认为复制 Scala 代码会起作用?
  • 我在这里提供了类似问题的详细答案:stackoverflow.com/questions/63951922/…

标签: apache-spark pyspark jupyter-notebook


【解决方案1】:

正如我所见,您无法使用 pyspark 和 databricks 库按原样加载 xml 文件,这个问题发生了,请尝试从您的终端或笔记本电脑作为 shell 命令运行此命令:

 pyspark --packages com.databricks:spark-xml_2.11:0.4.1

如果它不起作用,您可以尝试解决此问题,因为您可以将文件作为文本读取然后解析它。

#define your parser function: input is rdd: 
def parse_xml(rdd):
    """
    Read the xml string from rdd, parse and extract the elements,
    then return a list of list.
    """


    return results

#read the file as text at a RDD level
file_rdd = spark.read.text("/path/to/data/*.xml", wholetext=True).rdd
# parse xml tree, extract the records and transform to new RDD
records_rdd = file_rdd.flatMap(parse_xml)
# convert RDDs to DataFrame with the pre-defined schema
output_df = records_rdd.toDF(my_schema)

如果 .toDf 不起作用,请导入 spark.implicit。

【讨论】:

  • 你好,我是用第二种方式来解析xml文件的。但这仅发生在一个分区上,即使在我将 rdd 转换为数据帧并在其上运行我的 udfs 之后,它也仅发生在 1 个分区上。我不想手动控制分区。有解决办法吗?
猜你喜欢
  • 2017-09-24
  • 1970-01-01
  • 2018-10-13
  • 1970-01-01
  • 2021-06-26
  • 2021-10-17
  • 2022-07-21
  • 1970-01-01
  • 2019-05-10
相关资源
最近更新 更多