美文网首页我爱编程Spark
使用Spark写WordCount

使用Spark写WordCount

作者: Taoyongpan | 来源:发表于2018-05-24 19:11 被阅读0次

框架搭建

使用IDEA搭建同时可以写Scala语言和Java语言的Maven项目,步骤:
new--->project
选择Maven项目,不要勾选任何选项,一直next到finish;
pom.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.tao</groupId>
        <artifactId>spark</artifactId>
        <version>1.0-SNAPSHOT</version>

        <properties>
            <spark.version>2.1.0</spark.version>
            <scala.version>2.11.8</scala.version>
        </properties>
        <dependencies>
            <dependency>
                <groupId>org.scala-lang</groupId>
                <artifactId>scala-library</artifactId>
                <version>${scala.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.spark</groupId>
                <artifactId>spark-core_2.11</artifactId>
                <version>${spark.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.hadoop</groupId>
                <artifactId>hadoop-client</artifactId>
                <version>2.6.5</version>
            </dependency>
        </dependencies>

        <!--打包插件-->
        <build>
            <sourceDirectory>src/main/scala</sourceDirectory>
            <testSourceDirectory>src/test/scala</testSourceDirectory>
            <pluginManagement>
                <plugins>
                    <plugin>
                        <groupId>net.alchim31.maven</groupId>
                        <artifactId>scala-maven-plugin</artifactId>
                        <version>3.2.2</version>
                    </plugin>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-compiler-plugin</artifactId>
                        <version>3.7.0</version>
                    </plugin>
                </plugins>
            </pluginManagement>
            <plugins>
                <plugin>
                    <groupId>net.alchim31.maven</groupId>
                    <artifactId>scala-maven-plugin</artifactId>
                    <executions>
                        <execution>
                            <id>scala-compile-first</id>
                            <phase>process-resources</phase>
                            <goals>
                                <goal>add-source</goal>
                                <goal>compile</goal>
                            </goals>
                        </execution>
                        <execution>
                            <id>scala-test-compile</id>
                            <phase>process-test-resources</phase>
                            <goals>
                                <goal>testCompile</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-shade-plugin</artifactId>
                    <version>2.4.3</version>
                    <executions>
                        <execution>
                            <phase>package</phase>
                            <goals>
                                <goal>shade</goal>
                            </goals>
                            <configuration>
                                <filters>
                                    <filter>
                                        <artifact>*:*</artifact>
                                        <excludes>
                                            <exclude>META-INF/*.SF</exclude>
                                            <exclude>META-INF/*.DSA</exclude>
                                            <exclude>META-INF/*.RSA</exclude>
                                        </excludes>
                                    </filter>
                                </filters>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </project>

使用该pom文件,直接下载即可;

Scala写WordCount

代码如下:

/**
  *  Taoyongpan
  *  Created in 12:47 2018/5/24
  */
object WordCount {
  def main(args: Array[String]): Unit = {

    val conf = new SparkConf().setAppName("ScalaWorkContext").setMaster("local")
    //sc是Spark Context,是Spark程序的入口
    val sc = new SparkContext(conf)
    //编写Spark程序
    //sc.textFile(args(0)).flatMap(_.split(" ")).map((_,1)).reduceByKey(_+_).saveAsTextFile(args(1))
    //指定从哪里读取数据,并生成RDD
    val lines : RDD[String] = sc.textFile(args(0))
    //将一行内容进行切分压平
    val words : RDD[String] = lines.flatMap(_.split(" "))
    //将单词和1放到一个元组中
    val  wordAndOne : RDD[(String,Int)] = words.map((_,1))
    //继续聚合
    val reduced : RDD[(String,Int)] = wordAndOne.reduceByKey(_+_)
    //从小到大排序
    val sorted : RDD[(String,Int)] = reduced.sortBy(_._2)
    //逆序排序
//    val sorted : RDD[(String,Int)] = reduced.sortBy(_._2,false)
    //存储到指定位置
    sorted.saveAsTextFile(args(1))
    sc.stop()
  }
}

Java写 WordCount

代码如下:

/**
 * Author: Taoyongpan
 * Date: Created in 13:16 2018/5/24
 */
public class WordCount {
    public static void main(String[] args) {

        //
        SparkConf conf = new SparkConf();
        conf.setAppName("WordCount").setMaster("local");
        //创建程序执行的入口
        JavaSparkContext jsc = new JavaSparkContext(conf);
        //Spark程序
        //指定从哪里读取数据
        final JavaRDD<String> lines = jsc.textFile(args[0]);
        //切分压平
        JavaRDD<String> words = lines.flatMap(new FlatMapFunction<String, String>() {
            public Iterator<String> call(String line) throws Exception {
                String[] words = line.split(" ");
                return Arrays.asList(words).iterator();
            }
        });
        //将单词和1放在一起
        JavaPairRDD<String, Integer> wordAndOne = words.mapToPair(new PairFunction<String, String, Integer>() {
            public Tuple2<String, Integer> call(String word) throws Exception {
                return new Tuple2<String, Integer>(word, 1);
            }
        });
        //聚合
        JavaPairRDD<String, Integer> reduced = wordAndOne.reduceByKey(new Function2<Integer, Integer, Integer>() {
            public Integer call(Integer v1, Integer v2) throws Exception {
                return v1 + v2;
            }
        });
        //排序,Java的RDD只支持SortByKey,调换单词和次数的顺序
        JavaPairRDD<Integer, String> swaped = reduced.mapToPair(new PairFunction<Tuple2<String, Integer>, Integer, String>() {
            public Tuple2<Integer, String> call(Tuple2<String, Integer> tp) throws Exception {
                return tp.swap();
            }
        });
        //排序
        JavaPairRDD<Integer, String> sorted = swaped.sortByKey();
        //再调换顺序
        JavaPairRDD<String, Integer> res = sorted.mapToPair(new PairFunction<Tuple2<Integer, String>, String, Integer>() {
            public Tuple2<String, Integer> call(Tuple2<Integer, String> tp) throws Exception {
                return tp.swap();
            }
        });
        //保存
        res.saveAsTextFile(args[1]);
        //释放资源
        jsc.stop();
    }
}

未完待续。。。

相关文章

网友评论

    本文标题:使用Spark写WordCount

    本文链接:https://www.haomeiwen.com/subject/yytejftx.html