环境准备

创建 Maven 项目创建服务器远程连接
Tools------Delployment-----Browse Remote Host

在这里插入图片描述

设置如下内容:

在这里插入图片描述

在这里输入服务器的账号和密码

在这里插入图片描述

点击Test Connection,提示Successfully的话,就说明配置成功。

在这里插入图片描述

复制Hadoop的 core-site.xml、hdfs-site.xml 以及 log4j.properties 三个文件复制到resources文件夹下。

在这里插入图片描述

设置 log4j.properties 为打印警告异常信息:

log4j.rootCategory=WARN, console

4.添加 pom.xml 文件

<repositories>
        <repository>
            <id>aliyun</id>
            <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
        </repository>
        <repository>
            <id>cloudera</id>
            <url>https://repository.cloudera.com/artifactory/cloudera-repos/</url>
        </repository>
        <repository>
            <id>jboss</id>
            <url>http://repository.jboss.com/nexus/content/groups/public</url>
        </repository>
    </repositories>

    <properties>
        <scala.version>2.12.10</scala.version>
        <scala.binary.version>2.12</scala.binary.version>
        <spark.version>3.0.0</spark.version>
        <hadoop.version>2.7.3</hadoop.version>
        <hudi.version>0.9.0</hudi.version>
    </properties>

    <dependencies>
        <!-- 依赖Scala语言 -->
        <dependency>
            <groupId>org.scala-lang</groupId>
            <artifactId>scala-library</artifactId>
            <version>${scala.version}</version>
        </dependency>
        <!-- Spark Core 依赖 -->
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-core_${scala.binary.version}</artifactId>
            <version>${spark.version}</version>
        </dependency>
        <!-- Spark SQL 依赖 -->
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-sql_${scala.binary.version}</artifactId>
            <version>${spark.version}</version>
        </dependency>

        <!-- Hadoop Client 依赖 -->
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-client</artifactId>
            <version>${hadoop.version}</version>
        </dependency>

        <!-- hudi-spark3 -->
        <dependency>
            <groupId>org.apache.hudi</groupId>
            <artifactId>hudi-spark3-bundle_2.12</artifactId>
            <version>${hudi.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-avro_2.12</artifactId>
            <version>${spark.version}</version>
        </dependency>

    </dependencies>

    <build>
        <outputDirectory>target/classes</outputDirectory>
        <testOutputDirectory>target/test-classes</testOutputDirectory>
        <resources>
            <resource>
                <directory>${project.basedir}/src/main/resources</directory>
            </resource>
        </resources>
        <!-- Maven 编译的插件 -->
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>net.alchim31.maven</groupId>
                <artifactId>scala-maven-plugin</artifactId>
                <version>3.2.0</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>testCompile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

要注释掉创建项目时的生成的下面的代码,不然依赖一直报错:

<!--    <properties>-->
<!--        <maven.compiler.source>8</maven.compiler.source>-->
<!--        <maven.compiler.target>8</maven.compiler.target>-->
<!--    </properties>-->

代码结构:

在这里插入图片描述

核心代码

import org.apache.hudi.QuickstartUtils.DataGenerator
import org.apache.spark.sql.{DataFrame, SaveMode, SparkSession}
/**
 * Hudi 数据湖的框架,基于Spark计算引擎,对数据进行CURD操作,使用官方模拟赛生成的出租车出行数据
 *
 * 任务一:模拟数据,插入Hudi表,采用COW模式
 * 任务二:快照方式查询(Snapshot Query)数据,采用DSL方式
 * 任务三:更新(Update)数据
 * 任务四:增量查询(Incremental Query)数据,采用SQL方式
 * 任务五:删除(Delete)数据
 */
object HudiSparkDemo {
  /**
   * 官方案例:模拟产生数据,插入Hudi表,表的类型为COW
   */
  def insertData(spark: SparkSession, table: String, path: String): Unit = {
    import spark.implicits._
    // 第1步、模拟乘车数据
    import org.apache.hudi.QuickstartUtils._
    val dataGen: DataGenerator = new DataGenerator()
    val inserts = convertToStringList(dataGen.generateInserts(100))
    import scala.collection.JavaConverters._
    val insertDF: DataFrame = spark.read.json(
      spark.sparkContext.parallelize(inserts.asScala, 2).toDS()
    )
//    		insertDF.printSchema()
//    		insertDF.show(10, truncate = false)
    //第二步: 插入数据到Hudi表
    import org.apache.hudi.DataSourceWriteOptions._
    import org.apache.hudi.config.HoodieWriteConfig._
    insertDF.write
      .mode(SaveMode.Append)
      .format("hudi")
      .option("hoodie.insert.shuffle.parallelism", 2)
      .option("hoodie.insert.shuffle.parallelism", 2)
      //Hudi表的属性设置
      .option(PRECOMBINE_FIELD.key(), "ts")
      .option(RECORDKEY_FIELD.key(), "uuid")
      .option(PARTITIONPATH_FIELD.key(), "partitionpath")
      .option(TBL_NAME.key(), table)
      .save(path)
  }
  /**
   *  采用Snapshot Query快照方式查询表的数据
   */
  def queryData(spark: SparkSession, path: String): Unit = {
    import spark.implicits._
    val tripsDF: DataFrame = spark.read.format("hudi").load(path)
//    tripsDF.printSchema()
//    tripsDF.show(10, truncate = false)
    //查询费用大于10,小于50的乘车数据
    tripsDF
      .filter($"fare" >= 20 && $"fare" <=50)
      .select($"driver", $"rider", $"fare", $"begin_lat", $"begin_lon", $"partitionpath", $"_hoodie_commit_time")
      .orderBy($"fare".desc, $"_hoodie_commit_time".desc)
      .show(20, truncate = false)
  }
  def queryDataByTime(spark: SparkSession, path: String):Unit = {
    import org.apache.spark.sql.functions._
    //方式一:指定字符串,按照日期时间过滤获取数据
    val df1 = spark.read
      .format("hudi")
      .option("as.of.instant", "20220610160908")
      .load(path)
      .sort(col("_hoodie_commit_time").desc)
    df1.printSchema()
    df1.show(numRows = 5, truncate = false)
    //方式二:指定字符串,按照日期时间过滤获取数据
    val df2 = spark.read
      .format("hudi")
      .option("as.of.instant", "2022-06-10 16:09:08")
      .load(path)
      .sort(col("_hoodie_commit_time").desc)
    df2.printSchema()
    df2.show(numRows = 5, truncate = false)
  }
  
  /**
   * 将DataGenerator作为参数传入生成数据
   */
  def insertData(spark: SparkSession, table: String, path: String, dataGen: DataGenerator): Unit = {
    import spark.implicits._
    // 第1步、模拟乘车数据
    import org.apache.hudi.QuickstartUtils._
    val inserts = convertToStringList(dataGen.generateInserts(100))
    import scala.collection.JavaConverters._
    val insertDF: DataFrame = spark.read.json(
      spark.sparkContext.parallelize(inserts.asScala, 2).toDS()
    )
    //    		insertDF.printSchema()
    //    		insertDF.show(10, truncate = false)
    //第二步: 插入数据到Hudi表
    import org.apache.hudi.DataSourceWriteOptions._
    import org.apache.hudi.config.HoodieWriteConfig._
    insertDF.write
      //更换为Overwrite模式
      .mode(SaveMode.Overwrite)
      .format("hudi")
      .option("hoodie.insert.shuffle.parallelism", 2)
      .option("hoodie.insert.shuffle.parallelism", 2)
      //Hudi表的属性设置
      .option(PRECOMBINE_FIELD.key(), "ts")
      .option(RECORDKEY_FIELD.key(), "uuid")
      .option(PARTITIONPATH_FIELD.key(), "partitionpath")
      .option(TBL_NAME.key(), table)
      .save(path)
  }
  /**
   * 模拟产生Hudi表中更新数据,将其更新到Hudi表中
   */
  def updateData(spark: SparkSession, table: String, path: String, dataGen: DataGenerator):Unit = {
    import spark.implicits._
    // 第1步、模拟乘车数据
    import org.apache.hudi.QuickstartUtils._
    //产生更新的数据
    val updates = convertToStringList(dataGen.generateUpdates(100))
    import scala.collection.JavaConverters._
    val updateDF: DataFrame = spark.read.json(
      spark.sparkContext.parallelize(updates.asScala, 2).toDS()
    )
    // TOOD: 第2步、插入数据到Hudi表
    import org.apache.hudi.DataSourceWriteOptions._
    import org.apache.hudi.config.HoodieWriteConfig._
    updateDF.write
      //追加模式
      .mode(SaveMode.Append)
      .format("hudi")
      .option("hoodie.insert.shuffle.parallelism", "2")
      .option("hoodie.upsert.shuffle.parallelism", "2")
      // Hudi 表的属性值设置
      .option(PRECOMBINE_FIELD.key(), "ts")
      .option(RECORDKEY_FIELD.key(), "uuid")
      .option(PARTITIONPATH_FIELD.key(), "partitionpath")
      .option(TBL_NAME.key(), table)
      .save(path)
  }
  /**
   *  采用Incremental Query增量方式查询数据,需要指定时间戳
   */
  def incrementalQueryData(spark: SparkSession, path: String): Unit = {
    import spark.implicits._
    // 第1步、加载Hudi表数据,获取commit time时间,作为增量查询数据阈值
    import org.apache.hudi.DataSourceReadOptions._
    spark.read
      .format("hudi")
      .load(path)
      .createOrReplaceTempView("view_temp_hudi_trips")
    val commits: Array[String] = spark
      .sql(
        """
				  |select
				  |  distinct(_hoodie_commit_time) as commitTime
				  |from
				  |  view_temp_hudi_trips
				  |order by
				  |  commitTime DESC
				  |""".stripMargin
      )
      .map(row => row.getString(0))
      .take(50)
    val beginTime = commits(commits.length - 1) // commit time we are interested in
    println(s"beginTime = ${beginTime}")
    // 第2步、设置Hudi数据CommitTime时间阈值,进行增量数据查询
    val tripsIncrementalDF = spark.read
      .format("hudi")
      // 设置查询数据模式为:incremental,增量读取
      .option(QUERY_TYPE.key(), QUERY_TYPE_INCREMENTAL_OPT_VAL)
      // 设置增量读取数据时开始时间
      .option(BEGIN_INSTANTTIME.key(), beginTime)
      .load(path)
    // 第3步、将增量查询数据注册为临时视图,查询费用大于20数据
    tripsIncrementalDF.createOrReplaceTempView("hudi_trips_incremental")
    spark
      .sql(
        """
				  |select
				  |  `_hoodie_commit_time`, fare, begin_lon, begin_lat, ts
				  |from
				  |  hudi_trips_incremental
				  |where
				  |  fare > 20.0
				  |""".stripMargin
      )
      .show(10, truncate = false)
  }
  /**
   * 删除Hudi表数据,依据主键uuid进行删除,如果是分区表,指定分区路径
   */
  def deleteData(spark: SparkSession, table: String, path: String): Unit = {
    import spark.implicits._
    // 第1步、加载Hudi表数据,获取条目数
    val tripsDF: DataFrame = spark.read.format("hudi").load(path)
    println(s"Raw Count = ${tripsDF.count()}")
    // 第2步、模拟要删除的数据,从Hudi中加载数据,获取几条数据,转换为要删除数据集合
    val dataframe = tripsDF.limit(2).select($"uuid", $"partitionpath")
    import org.apache.hudi.QuickstartUtils._
    val dataGenerator = new DataGenerator()
    val deletes = dataGenerator.generateDeletes(dataframe.collectAsList())
    import scala.collection.JavaConverters._
    val deleteDF = spark.read.json(spark.sparkContext.parallelize(deletes.asScala, 2))
    // 第3步、保存数据到Hudi表中,设置操作类型:DELETE
    import org.apache.hudi.DataSourceWriteOptions._
    import org.apache.hudi.config.HoodieWriteConfig._
    deleteDF.write
      .mode(SaveMode.Append)
      .format("hudi")
      .option("hoodie.insert.shuffle.parallelism", "2")
      .option("hoodie.upsert.shuffle.parallelism", "2")
      // 设置数据操作类型为delete,默认值为upsert
      .option(OPERATION.key(), "delete")
      .option(PRECOMBINE_FIELD.key(), "ts")
      .option(RECORDKEY_FIELD.key(), "uuid")
      .option(PARTITIONPATH_FIELD.key(), "partitionpath")
      .option(TBL_NAME.key(), table)
      .save(path)
    // 第4步、再次加载Hudi表数据,统计条目数,查看是否减少2条数据
    val hudiDF: DataFrame = spark.read.format("hudi").load(path)
    println(s"Delete After Count = ${hudiDF.count()}")
  }
  def main(args: Array[String]): Unit = {
    System.setProperty("HADOOP_USER_NAME","hty")
    //创建SparkSession示例对象,设置属性
    val spark: SparkSession = {
      SparkSession.builder()
        .appName(this.getClass.getSimpleName.stripSuffix("$"))
        .master("local[2]")
        // 设置序列化方式:Kryo
        .config("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
        .getOrCreate()
    }
    //定义变量:表名称、保存路径
    val tableName: String = "tbl_trips_cow"
    val tablePath: String = "/hudi_warehouse/tbl_trips_cow"
    //构建数据生成器,模拟产生业务数据
    import org.apache.hudi.QuickstartUtils._
    //任务一:模拟数据,插入Hudi表,采用COW模式
    //insertData(spark, tableName, tablePath)
     //任务二:快照方式查询(Snapshot Query)数据,采用DSL方式
      //queryData(spark, tablePath)
    //queryDataByTime(spark, tablePath)
    // 任务三:更新(Update)数据,第1步、模拟产生数据,第2步、模拟产生数据,针对第1步数据字段值更新,
    // 第3步、将数据更新到Hudi表中
    val dataGen: DataGenerator = new DataGenerator()
    //insertData(spark, tableName, tablePath, dataGen)
    //updateData(spark, tableName, tablePath, dataGen)
    //任务四:增量查询(Incremental Query)数据,采用SQL方式
    //incrementalQueryData(spark, tablePath)
    //任务五:删除(Delete)数据
    deleteData(spark, tableName,tablePath)
    //应用结束,关闭资源
    spark.stop()
  }
}

测试

执行 insertData(spark, tableName, tablePath) 方法后对其用快照查询的方式进行查询:

queryData(spark, tablePath)

在这里插入图片描述

增量查询(Incremental Query)数据:

incrementalQueryData(spark, tablePath)

在这里插入图片描述

参考资料

https://www.bilibili.com/video/BV1sb4y1n7hK?p=21&vd_source=e21134e00867aeadc3c6b37bb38b9eee

到此这篇关于IDEA 中使用 Hudi的文章就介绍到这了,更多相关IDEA 使用 Hudi内容请搜索Devmax以前的文章或继续浏览下面的相关文章希望大家以后多多支持Devmax!

IDEA 中使用 Hudi的示例代码的更多相关文章

  1. 适用于Xcode,IntelliJ Idea和Phonegap(又名Cordova)的gitignore模板

    有没有人有一个很好的预先推出的gitignore文件用于使用Xcode和PhoneGap的iPhone开发?

  2. 第四章 :构建你的应用程序原型

    在应用程序开发的环境下,原型可以是一个app的早期样品,这个样品没有什么功能只有一些用户界面甚至只有草图。原型可以允许你在不构建应用程序的情况下测试你的idea。下图展示原型的好处将应用程序的草图画在纸上现在你有一个idea,怎么构建原型呢?使用POP构建你的应用程序prototype你可以把你的app话在纸上。如前所述,应用程序原型有很多形式。

  3. android-studio – IDEA中Gradle自动完成的位置在哪里?

    解决方法对于Groovy插件,它可能是Cucumber.我知道Gradle使用Groovy的一些技术和语法,所以我尝试在第一次尝试时安装一些Groovy插件并取得成功.安装此插件的步骤:>在MacOS上:首选项…

  4. android-studio – 在Android Studio中放置gitIgnore文件的位置?

    我将此文件复制到AndroidStudio中的gitIgnore文件中,但是当我在gitHub上推送该项目时,我的gitnigore文件如下所示:所以,我复制到AndroidStudio的文件不在这里.问题是什么?解决方法通常在创建新项目时会为您生成gitignore文件.这是正确的.gitignore文件.这是你必须把它.

  5. Tools-&gt; Android-&gt;启用ADB服务的目的是什么?

    为了将IDEA和DDMS连接到同一个仿真器,我不得不禁用此功能.它有什么作用?这个行动有不利之处吗?

  6. android – IntelliJ IDEA认为我的项目的一部分是subversion而不是git,如何解决这个问题?

    解决方法在“设置”中检查项目配置>版本控制.这是配置目录/vcs映射的位置.删除可能存在的任何SVN映射,并确保整个项目映射到Git.顺便说一句,我不知道这怎么可能发生.

  7. Android Studio在启动时修改./idea/vcs.xml

    因为不建议忽略AndroidStudio中的整个.idea文件夹,所以大多数文件都由git跟踪.然而奇怪的是,每次启动后,即使已经存在数十个,也会向vcs.xml添加相同的行.这很快变老了.这种行为是有目的还是仅仅是一个错误?AndroidStudio还可以在启动时阻止它进行此类修改吗?

  8. android – 强制Idea生成R.Java文件的最简单的方法是什么?

    我试图使用intellij想法运行Android示例应用程序,而R.Java文件缺少表单记事本样本源目录.解决方法确保您的项目根目录中有gen文件夹.如果没有,请自己做一个.

  9. 使用IntelliJ IDEA调式Stream流的方法步骤

    本文主要介绍了使用IntelliJ IDEA调式Stream流的方法步骤,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  10. 使用idea创建vue项目的图文教程

    Vue.js是一套构建用户界面的框架,只关注视图层,它不仅易于上手,还便于与第三方库或既有项目整合,下面这篇文章主要给大家介绍了关于使用idea创建vue项目的相关资料,需要的朋友可以参考下

随机推荐

  1. 基于EJB技术的商务预订系统的开发

    用EJB结构开发的应用程序是可伸缩的、事务型的、多用户安全的。总的来说,EJB是一个组件事务监控的标准服务器端的组件模型。基于EJB技术的系统结构模型EJB结构是一个服务端组件结构,是一个层次性结构,其结构模型如图1所示。图2:商务预订系统的构架EntityBean是为了现实世界的对象建造的模型,这些对象通常是数据库的一些持久记录。

  2. Java利用POI实现导入导出Excel表格

    这篇文章主要为大家详细介绍了Java利用POI实现导入导出Excel表格,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  3. Mybatis分页插件PageHelper手写实现示例

    这篇文章主要为大家介绍了Mybatis分页插件PageHelper手写实现示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  4. (jsp/html)网页上嵌入播放器(常用播放器代码整理)

    网页上嵌入播放器,只要在HTML上添加以上代码就OK了,下面整理了一些常用的播放器代码,总有一款适合你,感兴趣的朋友可以参考下哈,希望对你有所帮助

  5. Java 阻塞队列BlockingQueue详解

    本文详细介绍了BlockingQueue家庭中的所有成员,包括他们各自的功能以及常见使用场景,通过实例代码介绍了Java 阻塞队列BlockingQueue的相关知识,需要的朋友可以参考下

  6. Java异常Exception详细讲解

    异常就是不正常,比如当我们身体出现了异常我们会根据身体情况选择喝开水、吃药、看病、等 异常处理方法。 java异常处理机制是我们java语言使用异常处理机制为程序提供了错误处理的能力,程序出现的错误,程序可以安全的退出,以保证程序正常的运行等

  7. Java Bean 作用域及它的几种类型介绍

    这篇文章主要介绍了Java Bean作用域及它的几种类型介绍,Spring框架作为一个管理Bean的IoC容器,那么Bean自然是Spring中的重要资源了,那Bean的作用域又是什么,接下来我们一起进入文章详细学习吧

  8. 面试突击之跨域问题的解决方案详解

    跨域问题本质是浏览器的一种保护机制,它的初衷是为了保证用户的安全,防止恶意网站窃取数据。那怎么解决这个问题呢?接下来我们一起来看

  9. Mybatis-Plus接口BaseMapper与Services使用详解

    这篇文章主要为大家介绍了Mybatis-Plus接口BaseMapper与Services使用详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  10. mybatis-plus雪花算法增强idworker的实现

    今天聊聊在mybatis-plus中引入分布式ID生成框架idworker,进一步增强实现生成分布式唯一ID,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

返回
顶部