spark 操作map中执行self.方法报错

python 复制代码
class model(object):
    def __init__(self):
        self.data = sc.textFile('path/to/data.csv')
        # other misc setup
    def run_model(self):
        self.data = self.data.map(self.transformation_function)
    def transformation_function(self,row):
        row = row.split(',')
        return row[0]+row[1]
test = model()
test.run_model()
test.data.take(10)

在pyspark中调用类方法,报错

Could not serialize object: Exception: It appears that you are attempting to broadcast an RDD or reference an RDD from an action or transformation. RDD transformations and actions can only be invoked by the driver, not inside of other transformations; for example, rdd1.map(lambda x: rdd2.values.count() * x) is invalid because the values transformation and count action cannot be performed inside of the rdd1.map transformation. For more information, see SPARK-5063.
原因

spark不允许在action或transformation中访问SparkContext,如果你的action或transformation中引用了self,那么spark会将整个对象进行序列化,并将其发到工作节点上,来确保每个执行任务的节点都能够访问到该方法以及它所依赖的类实例状态,但是序列化有一个限制,那就是不是所有的对象都可以被序列化。例如,SparkContext、SparkSession、打开的文件句柄、数据库连接等都不能被序列化,因为它们通常绑定到特定的运行环境,无法在网络上传输或在远程节点上复原。spark把对象序列化时这其中就保留了SparkContext,即使没有显式的访问它,它也会在闭包内被引用,所以会出错。
解决

将调用的类方法定义为静态方法 @staticmethod

python 复制代码
class model(object):
    @staticmethod
    def transformation_function(row):
        row = row.split(',')
        return row[0]+row[1]

    def __init__(self):
        self.data = sc.textFile('some.csv')

    def run_model(self):
        self.data = self.data.map(model.transformation_function)
相关推荐
Hylan_J2 小时前
【VSCode】MicroPython环境配置
ide·vscode·python·编辑器
莫忘初心丶2 小时前
在 Ubuntu 22 上使用 Gunicorn 启动 Flask 应用程序
python·ubuntu·flask·gunicorn
失败尽常态5235 小时前
用Python实现Excel数据同步到飞书文档
python·excel·飞书
2501_904447745 小时前
OPPO发布新型折叠屏手机 起售价8999
python·智能手机·django·virtualenv·pygame
青龙小码农5 小时前
yum报错:bash: /usr/bin/yum: /usr/bin/python: 坏的解释器:没有那个文件或目录
开发语言·python·bash·liunx
大数据追光猿5 小时前
Python应用算法之贪心算法理解和实践
大数据·开发语言·人工智能·python·深度学习·算法·贪心算法
Leuanghing6 小时前
【Leetcode】11. 盛最多水的容器
python·算法·leetcode
xinxiyinhe7 小时前
如何设置Cursor中.cursorrules文件
人工智能·python
快手技术7 小时前
Blaze RangePartitioning 算子Native实现全解析
spark·naive
诸神缄默不语7 小时前
如何用Python 3自动打开exe程序
python·os·subprocess·python 3