您的位置:首页 > 其它

Spark学习笔记一

2016-02-17 16:28 162 查看
安装并使用pyspark进入python shell后,就可以开始使用spark 了。

lines = sc.textFile(“README.md”) # Create an RDD called lines

pythonLines = lines.filter(lambda line: “Python” in line)

“README.md”是安装spark后,在安装目录中的一个文件。通常在/usr/local/Cellar/apache-spark/版本号 下。 这里通过使用 SparkContext对象来访问Spark, 这个对象 represents a connection to a computing cluster. In the shell, a SparkContext is automatically created for you, as the variable called sc.

resilient distributed datasets, or RDDs

sc.testFile则创建了一个RDD对象,名为lines。在lines的基础上又创建了第二个RDD对象,pythonLines。Spark会记录RDD对象之间的血统关系(lineage),也就是说RDD之间会形成一张关系图。其用途以后再涉及。

虽然我们可以在python shell中执行spark命令,但更多时候我们需要将复杂逻辑存储在python脚本中,并直接运行。此时有两种方式:

In Python, you simply write applications as Python scripts, but you must instead run them using a special bin/spark-submit script included in Spark. This script sets up the environment for Spark’s Python API to function. Simply run your script with:

bin/spark-submit my_script.py

如果不想使用上面的工具执行python脚本,则需要自行在python脚本中设置spark环境变量等。典型的代码如下:

import sys
import os
SPARK_HOME = "/usr/local/Cellar/apache-spark/1.5.2" # Set this to wherever you have compiled Spark
os.environ["SPARK_HOME"] = SPARK_HOME # Add Spark path
os.environ["SPARK_LOCAL_IP"] = "127.0.0.1" # Set Local IP
sys.path.append( SPARK_HOME + "/libexec/python") # Add python files to Python Path

from pyspark import SparkConf, SparkContext

def getSparkContext():
conf = (SparkConf()
.setMaster("local") # run on local
.setAppName("Logistic Regression") # Name of App
.set("spark.executor.memory", "1g")) # Set 1 gig of memory
sc = SparkContext(conf = conf)
return sc

lines = sc.textFile("README.md")


然后就像运行普通python脚本一样运行就可以了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: