V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
checgg
V2EX  ›  问与答

spark 的 map 和 flatMap 应该怎样理解?

  •  
  •   checgg · 2016-08-05 10:08:23 +08:00 · 2375 次点击
    这是一个创建于 2792 天前的主题,其中的信息可能已经有所发展或是发生改变。
    conf = SparkConf().setAppName("Simple App").setMaster("local")
    sc = SparkContext(conf=conf)
    file = "./README.md"
    “”“
    111 aaa bcd
    22 qqq www
    ”“”
    dataFile = sc.textFile(file)
    test = dataFile.map(lambda s : s)
    print test.collect() # [u'111 aaa bcd', u'22 qqq www']
    test = dataFile.flatMap(lambda s : s)
    print test.collect() # [u'1', u'1', u'1', u' ', u'a', u'a', u'a', u' ', u'b', u'c', u'd', u'2', u'2', u' ', u'q', u'q', u'q', u' ', u'w', u'w', u'w'


    map 文档是这样解释的: Return a new distributed dataset formed by passing each element of the source through a function func.
    我的理解是对 rdd 的每一个 element 进行 func,最后返回的数量应该是等于 element 的数量的。

    flatMap 是这样解释:Similar to map, but each input item can be mapped to 0 or more output items (so func should return a Seq rather than a single item).

    这里不懂为什么 flatMap 结果是一个个字母?
    3 条回复    2016-08-06 01:59:56 +08:00
    wayslog
        1
    wayslog  
       2016-08-05 10:26:54 +08:00 via Android
    很简单啊… map 是一对一转成其他的值, flatMap 是有可能一个值转成
    wayslog
        2
    wayslog  
       2016-08-05 10:27:39 +08:00 via Android
    接上面,一个值转成了不限数量个值……
    SoloCompany
        3
    SoloCompany  
       2016-08-06 01:59:56 +08:00
    map 是一阶函数转换,比如 a -> a.name
    map 之后元素个数不变是 n -> n 变换

    flatMap 是二阶函数转换,把树结构摊平,比如 a -> lambda (x -> x.children)
    摊平之后的元素是遍历所有叶结点的结果, 可以近似看做 n -> n^2 变换
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2678 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 15:46 · PVG 23:46 · LAX 08:46 · JFK 11:46
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.