当前位置: 首页 > 编程日记 > 正文

spark编程基础--5.4综合实例

操作指令如下:

cd /usr/local/hadoop./sbin/start-dfs.sh./bin/hdfs dfs -mkdir -p spark/mycode/rdd/TopN./bin/hdfs dfs -put /usr/local/spark/mycode/TopN_file1.txt spark/mycode/rdd/TopN
./bin/hdfs dfs -put /usr/local/spark/mycode/TopN_file2.txt spark/mycode/rdd/TopN./bin/hdfs dfs -ls ./spark/mycode/rdd/TopN./bin/hdfs dfs -cat spark/mycode/rdd/TopN/TopN_file1.txt
./bin/hdfs dfs -cat spark/mycode/rdd/TopN/TopN_file2.txtcd ~/sparkapp/usr/local/sbt/sbt package/usr/local/spark/bin/spark-submit --class "TopN" ~/sparkapp/target/scala-2.11/simple-project_2.11-1.0.jar

案例1:求TOP1 案

//TopN.scala
import org.apache.spark.{SparkConf, SparkContext}
object TopN {def main(args: Array[String]): Unit = {val conf = new SparkConf().setAppName("TopN").setMaster("local")val sc = new SparkContext(conf)sc.setLogLevel("ERROR")val lines = sc.textFile("hdfs://localhost:9000/user/hadoop/spark/mycode/rdd/examples",2)var num = 0;val result = lines.filter(line => (line.trim().length > 0) && (line.split(",").length == 4)).map(_.split(",")(2)).map(x => (x.toInt,"")).sortByKey(false).map(x => x._1).take(5).foreach(x => {num = num + 1println(num + "\t" + x)})}
}

案例2:求最大最小值

1:求TOP值5.4.15.4.1案例1OP值55.4.1 案例1:求TOP值5.4.1 案例1:求TOP值.4.1 案例1:求TOP值 案例1:求?/TOP

案例3:文件排序

这是怎么了?

用了朋友的代码 又可以了……

import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.SparkConf
import org.apache.spark.HashPartitioner
object FileSort {def main(args: Array[String]) {val conf = new SparkConf().setAppName("FileSort")val sc = new SparkContext(conf)val dataFile = "file:///usr/local/spark/mycode/rdd/data"val lines = sc.textFile(dataFile,3)var index = 0val result = lines.filter(_.trim().length>0).map(n=>(n.trim.toInt,"")).partitionBy(new HashPartitioner(1)).sortByKey().map(t => {index += 1(index,t._1)})result.saveAsTextFile("file:///usr/local/spark/mycode/rdd/examples/result")}
}

案例4:二次排序

二次排序,具体的实现步骤:

 * 第一步:按照OrderedSerializable接口实现自定义排序的key

 * 第二步:将要进行二次排序的文件加载进来生成<key,value>类型的RDD

 * 第三步:使用sortByKey基于自定义的Key进行二次排序

 * 第四步:去除掉排序的Key,只保留排序的结果

SecondarySortKey.scala代码如下:

class SecondarySortKey(val first:Int,val second:Int) extends Ordered [SecondarySortKey] with Serializable {
def compare(other:SecondarySortKey):Int = {if (this.first - other.first !=0) {this.first - other.first } else {this.second - other.second}}
}

SecondarySortApp.scala代码如下:

import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
object SecondarySortApp {def main(args:Array[String]){val conf = new SparkConf().setAppName("SecondarySortApp").setMaster("local")val sc = new SparkContext(conf)val lines = sc.textFile("file:///usr/local/spark/mycode/rdd/examples/SecondarySortApp_file1.txt", 1)val pairWithSortKey = lines.map(line=>(new SecondarySortKey(line.split(" ")(0).toInt, line.split(" ")(1).toInt),line))val sorted = pairWithSortKey.sortByKey(false)val sortedResult = sorted.map(sortedLine =>sortedLine._2)sortedResult.collect().foreach (println)}
}

案例5:连接操作

任务描述:在推荐领域有一个著名的开放测试集,下载链接是:http://grouplens.org/datasets/movielens/,该测试集包含三个文件,分别是ratings.datsers.datmovies.dat,具体介绍可阅读:README.txt。请编程实现:通过连接ratings.datmovies.dat两个文件得到平均得分超过4.0的电影列表,采用的数据集是:ml-1m

/*movies.dat
MovieID::Title::Genres
1::Toy Story (1995)::Animation|Children's|Comedy
2::Jumanji (1995)::Adventure|Children's|Fantasy
3::Grumpier Old Men (1995)::Comedy|Romance
4::Waiting to Exhale (1995)::Comedy|Drama
5::Father of the Bride Part II (1995)::Comedy
6::Heat (1995)::Action|Crime|Thriller
7::Sabrina (1995)::Comedy|Romance
8::Tom and Huck (1995)::Adventure|Children's
9::Sudden Death (1995)::Action
10::GoldenEye (1995)::Action|Adventure|Thriller*/

/*ratings.dat
UserID::MovieID::Rating::Timestamp
1::1193::5::978300760
1::661::3::978302109
1::914::3::978301968
1::3408::4::978300275
1::2355::5::978824291
1::1197::3::978302268
1::1287::5::978302039
1::2804::5::978300719
1::594::4::978302268
1::919::4::978301368
1::595::5::978824268
1::938::4::978301752
1::2398::4::978302281
1::2918::4::978302124
1::1035::5::978301753
1::2791::4::978302188
1::2687::3::978824268*/

import org.apache.spark._
import SparkContext._
object SparkJoin {def main(args: Array[String]) {if(args.length != 3 ){println("usage is SparkJoin <rating> <movie> <output>")return}val conf = new SparkConf().setAppName("SparkJoin").setMaster("local")val sc = new SparkContext(conf)
// Read rating from HDFS file val textFile = sc.textFile(args(0))
//extract (movieid, rating) val rating = textFile.map(line => {val fileds = line.split("::")(fileds(1).toInt, fileds(2).toDouble)})
//get (movieid,ave_rating)val movieScores = rating.groupByKey().map(data => {val avg = data._2.sum / data._2.size(data._1, avg)})
// Read movie from HDFS file val movies = sc.textFile(args(1))val movieskey = movies.map(line => {val fileds = line.split("::")(fileds(0).toInt, fileds(1))    //(MovieID,MovieName)}).keyBy(tup => tup._1)// by join, we get <movie, averageRating, movieName> val result = movieScores.keyBy(tup => tup._1).join(movieskey).filter(f => f._2._1._2 > 4.0).map(f => (f._1, f._2._1._2, f._2._2._2))result.saveAsTextFile(args(2))}
}

//连接操作
使用网址http://files.grouplens.org/datasets/movielens/ml-1m.zip下载所需文件,解压后存在"~/下载/ml-1m"目录里

相关文章:

关于C#中的DLLImport (引)

MSDN中对DllImportAttribute的解释是这样的&#xff1a;可将该属性应用于方法。DllImportAttribute 属性提供对从非托管 DLL 导出的函数进行调用所必需的信息。作为最低要求&#xff0c;必须提供包含入口点的 DLL 的名称。 并给了一个示例&#xff1a; [DllImport("KERNEL…

Bootstrap框架和inconfont、font-awesome使用

Bootstrap框架和inconfont、font-awesome使用 iconfont的使用&#xff1a;https://www.cnblogs.com/clschao/articles/10387580.html Bootstrap介绍 Bootstrap是Twitter开源的基于HTML、CSS、JavaScript的前端框架。 它是为实现快速开发Web应用程序而设计的一套前端工具包。 它…

spark编程基础--6.DataFrame

使用spark安装时自带的样例数据people.json文件&#xff0c;生成DataFrame&#xff1a; 下面从示例文件people.json中创建一个DataFrame&#xff0c;然后保存成csv格式文件&#xff0c;代码如下&#xff1a; scala> val peopleDF spark.read.format("json").loa…

firebug 的使用

[Firebug - Console控制台视图] console API文档, http://www.getfirebug.com/console.html console.info显示(i)图标 在输出时&#xff0c;需要注意第一个参数被自动识别为格式字符串 需要在页面加载前启动firebug&#xff0c;当页面加载后启动firebug时&#xff0c;就没有…

cisco PIX防火墙的配置及注解完全手册

PIX Version 6.3(1)interface ethernet0 auto 设定端口0 速率为自动interface ethernet1 100full 设定端口1 速率为100兆全双工interface ethernet2 auto 设定端口2 速率为自动nameif ethernet0 outside security0 设 定端口0 名称为 outside 安全级别为0nameif ethernet1 insi…

C/C++:*(p++)慎用!!!!!

各位代码界的大佬大家好&#xff0c;今天跟大家分享一个在C/C中常用&#xff0c;但是很危险的一串代码——*(p) 为什么说这一行代码比较危险呢&#xff0c;因为对于C/C来说&#xff0c;成也指针&#xff0c;败也指针。C/C中指针便于我们操作一块连续的内存空间中内容&#xff0…

Kindeditor学习中的那些坑

Kindeditor富文本编辑器还算比较好上手的一款插件吧&#xff0c;下面记录一下我在学习和实践中遇到的那些坑。 编辑器初始化方法和参数网上一搜一大把&#xff0c;不想搜的点这里&#xff0c;文档上各个参数已经写得很清楚了&#xff0c;直接拿过来用就OK 开始说一些实际用到时…

java2实用教程--第二章基本数据类型与数组

基本数据类型--浮点类型 public class Example2_1 {public static void main (String args[]) {char chinaWord 好,japenWord あ;char you \u4F60;int position 20320;System.out.println("汉字&#xff1a;"chinaWord"的位置&#xff1a;"(int)china…

EntityCURD操作的参数和返回值

以下是netbeans根据实体自动生成的CURD模板&#xff1a;/** To change this template, choose Tools | Templates* and open the template in the editor.*/package com.medea.order.session;import com.medea.order.entity.Storeorder;import java.util.List; import javax.ej…

[ZT]SQL Server 的事务日志意外增大或充满的处理方法

http://support.microsoft.com/kb/317375 事务日志文件Transaction Log File是用来记录数据库更新情况的文件&#xff0c;扩展名为ldf。在 SQL Server 7.0 和 SQL Server 2000 中&#xff0c;如果设置了自动增长功能&#xff0c;事务日志文件将会自动扩展。一般情况下&#xff…

powershell真香

写毕设开题报告&#xff0c;从PDF复制后会有多余空格&#xff0c;一个一个手动删除略显麻烦。 delete.cpp#include<iostream> #include<cstdio> #include<string> #include<vector> using namespace std; int main() {//freopen("UAS.txt",&…

背包的硬币问题

在一个国家仅有1分&#xff0c;2分&#xff0c;3分硬币&#xff0c;将钱N兑换成硬币有很多种兑法。请你编程序计算出共有多少种兑法。 HDU 1284 #include <iostream> using namespace std;const int M 32768 10;int dp[M];int main() {int n;while (~scanf("%d&q…

【转帖】OnPreRender Render的区别

转自&#xff1a;http://hi.baidu.com/trip008/blog/item/d6139ab77b5414f130add1e9.html protected override void OnPreRender(EventArgs e) protected override void Render(HtmlTextWriter writer) 这两个的区别。可否告知 asp.net页面在触发各个子控件的事件之后&#…

微信小程序如何进行登录授权和获取用户信息

微信小程序如何进行登录授权和获取用户信息

禁止windows系统的自动运行功能

禁用Windows 系统的自动播放功能的方法&#xff1a;在运行中输入 gpedit.msc 后回车&#xff0c;打开组策略编辑器&#xff0c;依次点击&#xff1a;计算机配置&#xff0d;&#xff1e;管理模板&#xff0d;&#xff1e;系统&#xff0d;&#xff1e;关闭自动播放&#xff0d;…

WCF配置文件全攻略

Code<?xml version"1.0" encoding"utf-8" ?><configuration> <system.ServiceModel> <!-- services 元素包含应用中驻留的所有service的配置要求 --> <services> <!-- 每个服务的…

图的算法专题——最小生成树

概要&#xff1a; Prim算法Kruskal算法1、Prim算法 算法流程&#xff1a; &#xff08;1&#xff09;对图G&#xff08;V,E&#xff09;设置集合S来存放已被并入的顶点&#xff0c;然后执行n次&#xff08;2&#xff09;&#xff08;3&#xff09; &#xff08;2&#xff09;每…

GridControl摘录

gvCabTotalInfo.Columns["出线平均<br>电压"].SummaryItem.SummaryType DevExpress.Data.SummaryItemType.Average; gvCabTotalInfo.Columns["出线平均<br>电压"].SummaryItem.DisplayFormat "平均:{0:N2}"; gvCabTotalInfo.Refre…

小程序将form表单数据写入云数据库

小程序将form表单数据写入云数据库 <!--pages/MyIncome/MyIncome.wxml--> <view classforms><form bindsubmitgetForm><view classgetform><view>用戶名:<input typetext nameusername placeholder請輸入用戶名/></view><view&g…

ASP.NET自定义控件组件开发 第四章 组合控件开发CompositeControl

第四章 组合控件开发CompositeControl 大家好&#xff0c;今天我们来实现一个自定义的控件&#xff0c;之前我们已经知道了&#xff0c;要开发自定义的控件一般继承三个基 类:Control,WebControl&#xff0c;还有一个就是今天要说的CompositeControl。系列文章链接:ASP.NET自…

[C++对象模型][6]sizeof与对象内存布局

有了前面几节的铺垫&#xff0c;本节开始摸索C的对象的内存布局&#xff0c;平台为windows32位VS2008。 一 内置类型的size 内置类型&#xff0c;直接上代码&#xff0c;帮助大家加深记忆&#xff1a; Codevoid TestBasicSizeOf() { cout << __FUNCTION__ << e…

Linux负载均衡实现

配置之前清空所有服务器防火墙规则iptables -F关闭selinux&#xff1a;1、/usr/sbin/sestatus -v ##如果SELinux status参数为enabled即为开启状态SELinux status: enabled2、getenforce ##也可以用这个命令检查关闭SELinux&#xff1a;1…

【bzoj2770】YY的Treap 权值线段树

题目描述 志向远大的YY小朋友在学完快速排序之后决定学习平衡树&#xff0c;左思右想再加上SY的教唆&#xff0c;YY决定学习Treap。友爱教教父SY如砍瓜切菜般教会了YY小朋友Treap&#xff08;一种平衡树&#xff0c;通过对每个节点随机分配一个priority&#xff0c;同时保证这棵…

第二章 数据类型、运算符与表达式

#include <stdio.h> #include <stdlib.h>int Add(int a,int b) {return ab; }int main() {int x,y,sum 0;printf("Input two integers:\n");scanf("%d%d",&x,&y);sum Add(x,y);printf("sum %d\n",sum);return 0; }计算圆…

从设计原则谈软件开发(二)

最近一直在一个培训公司做着极为无聊的培训&#xff0c;所以一直都没有时间上网。今天突然发现这里可以上无线&#xff0c;嘿嘿&#xff0c;就上来继续把这个文章完成。 上次说到了设计原则中的单一职责原则&#xff0c;今天时间比较紧&#xff0c;我就继续往下写&#xff0c;也…

Npm环境依赖重置

需要彻底删除node_modules 然后npm install 如果无法删除node_modules文件&#xff0c;可以试试这个&#xff1a; 安装RimRaf&#xff1a; npm install rimraf -g 并在项目文件夹中删除node_modules文件夹&#xff1a; rimraf node_modules 然后你可以去npm install转载于:http…

MySQL的information_schema

在一次清空一张比较大的表时&#xff08;在清空前占用400多兆&#xff09;&#xff0c;发现该表中记录为0条但是空间并没有被释放&#xff0c;采用下面方式可查看占用情况 -- 查询各个数据库占用磁盘的情况 select TABLE_SCHEMA, concat(truncate(sum(data_length)/1024/1024,2…

编写spring应用

测试类自动注入失败&#xff1a;RunWith(SpringRunner.class)详解 CtrlAltDelete键&#xff0c;打开任务管理器&#xff0c;结束占据8080端口的Tomcat进程。 HomeController.java <!DOCTYPE html> <html xmlns"http://www.w3.org/1999/xhtml"xmlns:th&quo…

[导入]Learning.ASP.NET 2.0.with.AJAX.pdf(14.14 MB)

ASP.NET 2.0的AJAX无疑是最快&#xff0c;最有效&#xff0c;最可靠和最佳的方式支持创建交互式Web应用程序上市。结合开发工具&#xff0c;可以从Microsoft &#xff0c;免费和商业&#xff0c;这是难以置信轻松地创建网站&#xff0c;看看伟大的表现良好。最重要的是&#xf…

c# IO线程 打造 定时打开指定程序

用IO以及线程轻松实现 定时器 &#xff0c;在指定的时间打开指定的程序&#xff1a;&#xff09; 首先是如何实现定时&#xff1f;这可以单独的用个线程&#xff0c;在时间到的时候打开程序 然后是如何打开程序 &#xff0c;用Process.Start就可以了 最后就是如何把程序列表保存…