

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 存取 Spark Shell
<a name="emr-spark-shell"></a>

Spark Shell 以 Scala REPL (Read-Eval-Print-Loop) 為基礎。這可讓您以互動的方式建立 Spark 程式，並將工作提交至架構。您可以透過使用 SSH 連接到主節點並調用 `spark-shell` 來存取 Spark Shell。有關如何連線到主節點的詳細資訊，請參閱《Amazon EMR 管理指南》**中的[使用 SSH 連線至主節點](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-connect-master-node-ssh.html)。以下範例使用在 Amazon S3 中存放的 Apache HTTP 伺服器存取日誌。

**注意**  
可存取美國東部 (維吉尼亞北部) 的用戶端可使用這些範例中的儲存貯體。

 在預設情況下，Spark shell 會建立名為 `sc` 的自己的 [SparkContext](https://spark.apache.org/docs/1.3.1/api/scala/index.html#org.apache.spark.SparkContext) 物件。如果此內容在 REPL 中為必要，則您可以使用此內容。sqlContext 在 shell 中也有提供，且其為 [HiveContext](https://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.hive.HiveContext)。

**Example 使用 Spark Shell 來計算在 Amazon S3 中存放之檔案中某字串的出現次數**  
此範例使用 `sc` 讀取 Amazon S3 中存放的文字檔案。  

```
scala> sc
res0: org.apache.spark.SparkContext = org.apache.spark.SparkContext@404721db

scala> val textFile = sc.textFile("s3://elasticmapreduce/samples/hive-ads/tables/impressions/dt=2009-04-13-08-05/ec2-0-51-75-39.amazon.com.rproxy.govskope.ca-2009-04-13-08-05.log")
```
Spark 會建立 textFile 且與[資料結構](https://spark.apache.org/docs/latest/programming-guide.html#resilient-distributed-datasets-rdds)建立關聯。接著，範例會計算日誌檔中含字串「cartoonnetwork.com」的行數量：  

```
scala> val linesWithCartoonNetwork = textFile.filter(line => line.contains("cartoonnetwork.com")).count()
linesWithCartoonNetwork: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[2] at filter at <console>:23
<snip>
<Spark program runs>
scala> linesWithCartoonNetwork
res2: Long = 9
```

**Example 使用 Python 型 Spark shell 來計算在 Amazon S3 中存放之檔案中某字串的出現次數**  
Spark 還包含以 Python 為基礎的 shell、`pyspark`，您可以使用該 shell 來開發以 Python 撰寫之 Spark 程式的原型。如同使用 `spark-shell`，在主節點上調用 `pyspark`；它也有相同的 [SparkContext](https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.SparkContext.html#pyspark.SparkContext) 物件。  

```
>>> sc
<pyspark.context.SparkContext object at 0x7fe7e659fa50>
>>> textfile = sc.textFile("s3://elasticmapreduce/samples/hive-ads/tables/impressions/dt=2009-04-13-08-05/ec2-0-51-75-39.amazon.com.rproxy.govskope.ca-2009-04-13-08-05.log")
```
Spark 會建立 textFile 且與[資料結構](https://spark.apache.org/docs/latest/programming-guide.html#resilient-distributed-datasets-rdds)建立關聯。接著，範例會計算日誌檔中含字串「cartoonnetwork.com」的行數量。  

```
>>> linesWithCartoonNetwork = textfile.filter(lambda line: "cartoonnetwork.com" in line).count()
15/06/04 17:12:22 INFO lzo.GPLNativeCodeLoader: Loaded native gpl library from the embedded binaries
15/06/04 17:12:22 INFO lzo.LzoCodec: Successfully loaded & initialized native-lzo library [hadoop-lzo rev EXAMPLE]
15/06/04 17:12:23 INFO fs.EmrFileSystem: Consistency disabled, using com.amazon.ws.emr.hadoop.fs.s3n.S3NativeFileSystem as filesystem implementation
<snip>
<Spark program continues>
>>> linesWithCartoonNetwork
9
```