正确使用flatMap

时间:2017-02-22 15:40:43

标签: csv apache-spark pyspark bigdata

为什么每次我尝试RDD&动作时都会出现此错误如何解决?

/databricks/spark/python/lib/py4j-0.10.4-src.zip/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name)
    317                 raise Py4JJavaError(
    318                     "An error occurred while calling {0}{1}{2}.\n".
--> 319                     format(target_id, ".", name), value)
    320             else:
    321                 raise Py4JError(

我试图找出哪个是我可以执行操作的最后一个RDD及其ratingByUser,它表示问题出在flatMap中。

我尝试做的是我使用CSV(userID,movieID,rating)并且我希望为每个userID创建具有评级的movieID的唯一组合,但不同的用户可以生成相同的movieID对,ex为此CSV:

1,2000,5

1,2001,2

1,2002,3

2,2000,4

2,2001,1

2,2004,5

我想要RDD:

key(2000,2001),value(5,2,1)

key(2000,2002),value(5,3,1)

key(2001,2002),value(2,3,1)

key(2000,2001),value(4,1,1)

key(2000,2004),value(4,5,1)

key(2001,2004),value(1,5,1)

# First Map function - gets line and returns key(userID) value(movieID,rating)
def parseLine(line):
  fields=line.split(",")
  userID=int(fields[0])
  movieID=int(fields[1])
  rating=int(fields[2])
  return userID, (movieID,rating)
# Function to create movie unique pairs with ratings
# all pair start with the lowest ID
# returns key (movieIDj,movieIDi) & value (rating-j,rating-i,1)
# the 1 in value is added in order to count number of ratings in the reduce

def createPairs(userRatings):
  pairs=[]
  for i1 in range(len(userRatings[1])-1):
    for i2 in range(i1+1,len(userRatings[1])):
      if userRatings[i1][0]<userRatings[1][i2][0]:
        pairs.append(((userRatings[1][i1][0],userRatings[1][i2][0]),(userRatings[1][i1][1],userRatings[1][i2][1],1)))
      else:
        pairs.append(((userRatings[1][i2][0],userRatings[1][i1][0]),(userRatings[1][i2][1],userRatings[1][i1][1],1)))
  return pairs

# Create SC object from the ratings file
lines = sc.textFile("/FileStore/tables/dvmlbdnj1487603982330/ratings.csv")
# Map lines to Key(userID),Value(movieID,rating)
movieRatings = lines.map(parseLine)
# Join all rating by same user into one key
# (UserID1,(movie1,rating1)),(UserID1,(movie2,rating2)) --> UserID1,[(movie1,rating1),(movie2,rating2)]
ratingsPerUser = movieRatings.groupByKey()
# activate createPairs func
# We use flatMap, since each user have different number of ratings --> different number pairs
pairsOfMovies = ratingsPerUser.flatMap(createPairs)

1 个答案:

答案 0 :(得分:1)

问题是函数传递给flatMap而不是flatMap。  按键分组返回迭代器:

  • 无法多次遍历
  • 无法编入索引。

首先转换为列表:

ratingsPerUser.mapValues(list).flatMap(createPairs)