upsert部分hudi表字段

发布时间 2023-04-27 21:42:50作者: -见

当 insert into 一个 hudi 表时,如果只指定了部分字段,则运行时报错:

java.sql.SQLException: java.util.concurrent.ExecutionException: java.lang.RuntimeException: org.apache.hudi.exception.HoodieException: Expected table's schema:

测试 SQL:

set `hoodie.datasource.write.payload.class`=`org.apache.hudi.common.model.OverwriteNonDefaultsWithLatestAvroPayload`;
INSERT INTO t_test_001 (ds,ts,pk,a0,a1,a2) SELECT ds,CAST(current_timestamp AS BIGINT) AS ts,pk,f0,f1,f2 FROM t_test_002;

CREATE TABLE t_test_001 (
    ds BIGINT COMMENT	'date stamp',
    ts BIGINT COMMENT 'ts',
    pk BIGINT COMMENT 'pk',
    a0 BIGINT COMMENT 'a0',
    a1 BIGINT COMMENT 'a1',
    a2 string COMMENT 'a2',
    a3 BIGINT COMMENT 'a3',
    a4 BIGINT COMMENT 'a4',
    a5 string COMMENT 'a5',
    a6 BIGINT COMMENT 'a6',
    a7 BIGINT COMMENT 'a7',
    a8 BIGINT COMMENT 'a8',
    a9 string COMMENT 'a9'
) using hudi
tblproperties (
  type = 'mor', -- cow/mor
  primaryKey='pk',
  preCombineField = 'ts',
  hoodie.clean.automatic = 'true',
  hoodie.cleaner.policy = 'KEEP_LATEST_BY_HOURS', -- KEEP_LATEST_FILE_VERSIONS/KEEP_LATEST_COMMITS
  hoodie.cleaner.hours.retained = '48',
  hoodie.clean.trigger.strategy = 'NUM_COMMITS',
  hoodie.clean.max.commits = '9',
  hoodie.archive.automatic = 'true',
  hoodie.keep.max.commits = '30',
  hoodie.keep.min.commits = '20'
);

相关代码(https://github.com/apache/hudi/blob/master/hudi-spark-datasource/hudi-spark/src/main/scala/org/apache/spark/sql/hudi/command/InsertIntoHoodieTableCommand.scala):

  private def validate(queryOutputSchema: StructType, partitionsSpec: Map[String, Option[String]], catalogTable: HoodieCatalogTable): Unit = {
    // Validate that partition-spec has proper format (it could be empty if all of the partition values are dynamic,
    // ie there are no static partition-values specified)
    if (partitionsSpec.nonEmpty && partitionsSpec.size != catalogTable.partitionSchema.size) {
      throw new HoodieException(s"Required partition schema is: ${catalogTable.partitionSchema.fieldNames.mkString("[", ", ", "]")}, " +
        s"partition spec is: ${partitionsSpec.mkString("[", ", ", "]")}")
    }

    val staticPartitionValues = filterStaticPartitionValues(partitionsSpec)
    val fullQueryOutputSchema = StructType(queryOutputSchema.fields ++ staticPartitionValues.keys.map(StructField(_, StringType)))

    // Assert that query provides all the required columns
    if (!conforms(fullQueryOutputSchema, catalogTable.tableSchemaWithoutMetaFields)) {
      throw new HoodieException(s"Expected table's schema: ${catalogTable.tableSchemaWithoutMetaFields.fields.mkString("[", ", ", "]")}, " +
        s"query's output (including static partition values): ${fullQueryOutputSchema.fields.mkString("[", ", ", "]")}")
    }
  }