1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| from pyspark.sql import SparkSession from pyspark.sql import functions as func from pyspark.sql.types import StructType, StructField, IntegerType, LongType import codecs
print("Starting Session")
def loadMovieNames(): movieNames = {} with codecs.open("ml-100k/u.item","r", encoding="ISO-8859-1", errors ="ignore") as f: for line in f: fields = line.split("|") movieNames[int(fields[0])] = fields[1] return movieNames
spark = SparkSession.builder.appName("PopularMovies").getOrCreate()
nameDict = spark.sparkContext.broadcast(loadMovieNames())
schema = StructType( [ StructField("userID",IntegerType(), True) , StructField("movieID",IntegerType(), True) , StructField("rating", IntegerType(), True) , StructField("timestamp", LongType(), True) ] )
print("Schema is done")
movies_df = spark.read.option("sep","\t").schema(schema).csv("ml-100k/u.logs")
topMovieIds = movies_df.groupby("movieID").count()
def lookupName(movieID): return nameDict.value[movieID]
lookupNameUDF = func.udf(lookupName)
moviesWithNames = topMovieIds.withColumn("movietitle",lookupNameUDF(func.col("movieID")))
final_df = moviesWithNames.orderBy(func.desc("count"))
print(final_df.show(10))
spark.stop()
|