您的位置:首页 > 编程语言 > Java开发

sparksql分组后topN(JAVA)

2017-03-21 10:56 711 查看
<!-- spark -->
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.10</artifactId>
<version>1.6.0</version>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-sql_2.10</artifactId>
<version>1.6.0</version>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-hive_2.10</artifactId>
<version>1.6.0</version>
</dependency>

public class RowNumberTopN {
public static void main(String[] args) {
SparkConf conf = new SparkConf().setAppName("RowNumberTopN").setMaster("local");

JavaSparkContext sc = new JavaSparkContext(conf);
HiveContext hiveContext = new HiveContext(sc.sc());
hiveContext.sql("drop table if exists sales");
//创建销售表
hiveContext.sql("create table if not exists sales(product STRING,category STRING,revenue BIGINT)");
hiveContext.sql("LOAD DATA LOCAL INPATH '/user/local/spark/resources/sales.txt' INTO TABLE sales");
4000
//进行row_number分组
DataFrame topnDF = hiveContext.sql("SELECT product,category,revenue FROM (\n" +
"SELECT product,category,revenue,row_number() OVER (PARTITION BY category ORDER BY revenue DESC) rank\n" +
"FROM sales\n" +
") topn_sales where rank<=3");
hiveContext.sql("drop table if exists top3_sales");
topnDF.saveAsTable("top3_sales");
sc.close();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: