- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathspark-sql.py
More file actions
Latest commit
25 lines (19 loc) · 887 Bytes
/
Copy pathspark-sql.py
File metadata and controls
25 lines (19 loc) · 887 Bytes
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
frompysparkimportSparkConf, SparkContext
frompyspark.sqlimportSQLContext, Row
importcollections
conf=SparkConf().setMaster("local").setAppName("SparkSQL")
sc=SparkContext(conf=conf)
sqlContext=SQLContext(sc)
defmapper(line):
fields=line.split(',')
returnRow( ID=int(fields[0]), name=fields[1].encode("utf-8"), age=int(fields[2]), numFriends=int(fields[3]) )
lines=sc.textFile("fakefriends.csv")
people=lines.map(mapper)
# Infer the schema, and register the DataFrame as a table.
schemaPeople=sqlContext.createDataFrame(people)
schemaPeople.registerTempTable("people")
# SQL can be run over DataFrames that have been registered as a table.
teenagers=sqlContext.sql("SELECT * FROM people WHERE age >= 13 AND age <= 19")
# The results of SQL queries are RDDs and support all the normal RDD operations.
forteeninteenagers.collect():
print(teen)