spark 入门教程

一、安装scala环境

官网下载地址 Download | The Scala Programming Language,本次使用版本为sacla2.11.12,将压缩包解压至指定目录,配置好环境变量,控制台验证是否安环境是否可用:

二、添加pom依赖

创建一个maven项目

1、添加scala的sdk依赖

复制代码
  <properties>
    <scala.version>2.11.12</scala.version>
  </properties>
 
   <dependency>
      <groupId>org.scala-lang</groupId>
      <artifactId>scala-library</artifactId>
      <version>${scala.version}</version>
    </dependency>
 
    <dependency>
      <groupId>org.scala-lang</groupId>
      <artifactId>scala-compiler</artifactId>
      <version>${scala.version}</version>
    </dependency>
 
    <dependency>
      <groupId>org.scala-lang</groupId>
      <artifactId>scala-reflect</artifactId>
      <version>${scala.version}</version>
    </dependency>

2、添加spark依赖

复制代码
  <dependency>
      <groupId>org.apache.spark</groupId>
      <artifactId>spark-core_2.11</artifactId>
      <version>2.4.8</version>
    </dependency>
 
    <dependency>
      <groupId>org.apache.spark</groupId>
      <artifactId>spark-streaming_2.11</artifactId>
      <version>2.4.8</version>
      <scope>provided</scope>
    </dependency>

三、入门应用

1、数据源

test_spark.txt

复制代码
中国 河南
中国 浙江
河南 郑州
浙江 杭州
河南 洛阳
浙江 宁波
美国 纽约
纽约 华尔街
美国 吉利福尼亚
加利福尼亚 落砂机

2、编码实现

复制代码
import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}
 
object SparkWordCount {
  def main(args: Array[String]): Unit = {
    ///使用本地模式连接spark
    val conf = new SparkConf().setAppName("WordCount").setMaster("local")
    val sc = new SparkContext(conf)
    ///读取文件中每一行字符 存入到是数据集合RDD中
    val lines: RDD[String] = sc.textFile("D:/workplace/java-item/res/file/test_spark.txt")
    /// 将数据集合进行扁平化操作  以字符空格分割
    val tuples = lines.flatMap(_.split(" ")).groupBy(word => word).map({ case (w, l) => (w, l.size) }).collect()
    tuples.foreach(println)
  }
}
相关推荐
Databend3 小时前
2KB histogram 背后:Databend 如何低成本追踪长尾延迟
大数据·数据分析·agent
Databend5 小时前
从湖仓升级为 Agent 时代的数据控制面,Snowflake 和 Databricks 有哪些布局
大数据·数据库·agent
阿里云大数据AI技术1 天前
StarRocks x Fluss x Paimon湖流一体方案:构建秒级响应、湖流一体的实时数据引擎
大数据·人工智能
Databend1 天前
Agent 轨迹分析与归因的数据工程实践
大数据·数据库·agent
喵个咪1 天前
Go Wind UBA 拆解系列 - 架构总览:三服务、数据流与契约优先
大数据·后端·go
喵个咪1 天前
Go Wind UBA 拆解系列 - 多租户与安全:两套隔离机制的边界
大数据·后端·go
喵个咪1 天前
Go Wind UBA 拆解系列 - OLAP 与 SQL 硬核:25 个分析模型怎么落地
大数据·后端·go
喵个咪1 天前
Go Wind UBA 拆解系列 - SDK 与采集层:从浏览器到 Kafka
大数据·后端·go
QCC产品中心1 天前
MiniMax Agent 接入实测:企业查询、股权穿透与 UBO 识别(附 Prompt 模板)
大数据·mcp·金融/非金融
SelectDB2 天前
Apache Doris Python UDF:让 SQL 直接调用 Python 生态,支撑 Agent 时代复杂业务逻辑
大数据·数据库·python