vinishjail97 commented on code in PR #935: URL: https://github.com/apache/incubator-xtable/pull/935#discussion_r4226522649
########## xtable-core/src/main/java/org/apache/xtable/index/Index.java: ########## @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xtable.index; + +import org.apache.spark.sql.Dataset; +import org.apache.spark.sql.Row; + +/** + * A secondary index over a table in another format, backed by XTable's Hudi conversion. It maps the + * values of an indexed column to the data file and row position that holds each value, so an engine + * can locate the rows to merge or delete without a full table join. + * + * @param <T> The table type of the source format (for example an Iceberg {@code Table}) + */ +public interface Index<T> { + /** Result column with the full path of the data file that holds the row. */ + String FILE_COLUMN = "_file"; Review Comment: Is the interface specific to iceberg? _delta can have the same index structure? So let's make it really format agnostic? ########## xtable-core/src/main/java/org/apache/xtable/hudi/engine/HudiExecutionEngineProvider.java: ########## @@ -0,0 +1,59 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xtable.hudi.engine; + +import java.util.List; +import java.util.Map; + +import org.apache.hudi.client.BaseHoodieWriteClient; +import org.apache.hudi.client.WriteStatus; +import org.apache.hudi.common.engine.HoodieEngineContext; +import org.apache.hudi.common.table.HoodieTableMetaClient; +import org.apache.hudi.common.util.Option; +import org.apache.hudi.config.HoodieWriteConfig; +import org.apache.hudi.table.HoodieTable; + +/** + * Abstracts the Hudi engine (Java or Spark) used by the Hudi conversion target to commit the + * registered files and to maintain the table and its metadata table indexes. + */ +public interface HudiExecutionEngineProvider { + + /** Returns the engine context used for file listing, index generation and table services. */ + HoodieEngineContext getEngineContext(); + + /** Creates the engine specific {@link HoodieTable} for cleaning and archival. */ + HoodieTable<?, ?, ?, ?> createTable( Review Comment: Do we need `HoodieTable<?, ?, ?, ?>` or just returning `HoodieTable` is enough? ########## xtable-core/src/main/java/org/apache/xtable/index/HudiBackedIcebergSecondaryIndex.java: ########## @@ -0,0 +1,299 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xtable.index; + +import static org.apache.hudi.metadata.HoodieTableMetadataUtil.PARTITION_NAME_SECONDARY_INDEX_PREFIX; +import static org.apache.spark.sql.functions.col; + +import java.util.Collections; +import java.util.List; +import java.util.Properties; +import java.util.Set; +import java.util.stream.Collectors; + +import lombok.extern.log4j.Log4j2; + +import org.apache.hadoop.conf.Configuration; +import org.apache.spark.api.java.JavaPairRDD; +import org.apache.spark.api.java.JavaRDD; +import org.apache.spark.api.java.JavaSparkContext; +import org.apache.spark.sql.Dataset; +import org.apache.spark.sql.Encoders; +import org.apache.spark.sql.Row; +import org.apache.spark.sql.RowFactory; +import org.apache.spark.sql.SparkSession; +import org.apache.spark.sql.types.DataTypes; +import org.apache.spark.sql.types.StructType; + +import org.apache.hudi.client.common.HoodieSparkEngineContext; +import org.apache.hudi.common.config.HoodieMetadataConfig; +import org.apache.hudi.common.data.HoodiePairData; +import org.apache.hudi.common.table.HoodieTableMetaClient; +import org.apache.hudi.common.table.HoodieTableVersion; +import org.apache.hudi.data.HoodieJavaPairRDD; +import org.apache.hudi.data.HoodieJavaRDD; +import org.apache.hudi.exception.TableNotFoundException; +import org.apache.hudi.metadata.HoodieBackedTableMetadata; +import org.apache.hudi.storage.HoodieStorage; +import org.apache.hudi.storage.hadoop.HoodieHadoopStorage; + +import org.apache.iceberg.Table; + +import scala.Tuple2; + +import com.google.common.base.Preconditions; + +import org.apache.xtable.catalog.TableFormatUtils; +import org.apache.xtable.conversion.ConversionConfig; +import org.apache.xtable.conversion.ConversionController; +import org.apache.xtable.conversion.SourceTable; +import org.apache.xtable.conversion.TargetTable; +import org.apache.xtable.hudi.HudiTargetConfig; +import org.apache.xtable.iceberg.IcebergConversionSourceProvider; +import org.apache.xtable.model.storage.TableFormat; +import org.apache.xtable.model.sync.SyncResult; +import org.apache.xtable.model.sync.SyncStatusCode; + +/** + * Secondary index for an Iceberg table backed by the Hudi metadata table. The index is built by + * syncing the Iceberg table to Hudi with the record index and a secondary index enabled; the Hudi + * metadata lives under {@code <data location>/.hoodie/metadata}. Because the Iceberg data files + * carry no Hudi record keys, the record key of a row is {@code <file path relative to the data + * location>_<row position>}, which a lookup resolves back to a file path and row position. + */ +@Log4j2 +public class HudiBackedIcebergSecondaryIndex implements Index<Table> { + private final String tableLocation; + private final String dataPath; + private final SourceTable sourceTable; + private final Properties targetTableProperties; + private final List<String> indexedColumns; + private final SparkSession sparkSession; + private final JavaSparkContext javaSparkContext; + private final HoodieSparkEngineContext engineContext; + + /** + * @param icebergTable the table to index + * @param sourceTable how XTable loads the table for a sync, because a loaded table does not + * expose the catalog it came from. A table of a catalog sets its catalog config, name and + * namespace, and a table without a catalog config is loaded from its location + * @param sparkSession the Spark session used to build and query the index + * @param targetTableProperties {@link HudiTargetConfig} properties for the sync. {@link + * HudiTargetConfig#SECONDARY_INDEX_COLUMNS} lists the columns to index, and other properties + * such as the record index file group counts are optional + */ + public HudiBackedIcebergSecondaryIndex( + Table icebergTable, + SourceTable sourceTable, + SparkSession sparkSession, + Properties targetTableProperties) { + Preconditions.checkArgument( + TableFormat.ICEBERG.equals(sourceTable.getFormatName()), + "Expected an Iceberg source table but got format %s", + sourceTable.getFormatName()); + this.tableLocation = icebergTable.location(); + this.dataPath = + TableFormatUtils.getTableDataLocation( + TableFormat.ICEBERG, tableLocation, icebergTable.properties()); + // the Hudi table lives under the data location, which Iceberg resolves from the table + // properties + this.sourceTable = sourceTable.toBuilder().dataPath(dataPath).build(); + this.targetTableProperties = new Properties(); + this.targetTableProperties.putAll(targetTableProperties); + this.targetTableProperties.setProperty( + HudiTargetConfig.EXECUTION_ENGINE, HudiTargetConfig.EXECUTION_ENGINE_SPARK); + // the secondary index is only available from Hudi table version 8 onwards + this.targetTableProperties.setProperty( + HudiTargetConfig.HUDI_TABLE_VERSION, String.valueOf(HoodieTableVersion.NINE.versionCode())); + this.indexedColumns = + HudiTargetConfig.fromProperties(this.targetTableProperties).getSecondaryIndexColumns(); + Preconditions.checkArgument( + !indexedColumns.isEmpty(), + "Set %s to the columns to index", + HudiTargetConfig.SECONDARY_INDEX_COLUMNS); + this.sparkSession = sparkSession; + this.javaSparkContext = JavaSparkContext.fromSparkContext(sparkSession.sparkContext()); + this.engineContext = new HoodieSparkEngineContext(javaSparkContext); + } + + @Override + public boolean doesIndexExist(String columnName) { + return getCompletedIndexPartitions() + .contains(PARTITION_NAME_SECONDARY_INDEX_PREFIX + columnName); + } + + @Override + public void syncIndex(Table icebergTable) { + Configuration configuration = javaSparkContext.hadoopConfiguration(); + IcebergConversionSourceProvider sourceProvider = new IcebergConversionSourceProvider(); + sourceProvider.init(configuration); + // The sync reports a failed target in its result instead of throwing. It returns no result + // for the target when the table has no new commits. + SyncResult syncResult = + new ConversionController(configuration) + .sync(getConversionConfig(icebergTable), sourceProvider) + .get(TableFormat.HUDI); + if (syncResult != null + && (syncResult.getTableFormatSyncStatus() == null + || syncResult.getTableFormatSyncStatus().getStatusCode() != SyncStatusCode.SUCCESS)) { + throw new IllegalStateException( + "Failed to sync the secondary indexes of columns " + + indexedColumns + + " of table " + + tableLocation + + ": " + + syncResult.getTableFormatSyncStatus()); + } + Set<String> completedPartitions = getCompletedIndexPartitions(); + List<String> notIndexed = + indexedColumns.stream() + .filter( + column -> + !completedPartitions.contains(PARTITION_NAME_SECONDARY_INDEX_PREFIX + column)) + .collect(Collectors.toList()); + if (!notIndexed.isEmpty()) { + throw new IllegalStateException( + "The secondary indexes of columns " + + notIndexed + + " of table " + + tableLocation + + " do not exist. The indexes are built when the index is created, and adding a" + + " column to an existing index is not supported yet."); + } + log.info( + "Synced the secondary indexes of columns {} of table {}", indexedColumns, tableLocation); + } + + /** + * Returns the metadata table partitions whose build has completed. A partition directory can + * exist while the build is in flight or after it failed, so the directory alone does not show + * that the index is usable. + */ + private Set<String> getCompletedIndexPartitions() { + try { + return getMetaClient().getTableConfig().getMetadataPartitions(); + } catch (TableNotFoundException e) { + return Collections.emptySet(); + } + } + + private HoodieTableMetaClient getMetaClient() { + HoodieStorage storage = + new HoodieHadoopStorage(dataPath, javaSparkContext.hadoopConfiguration()); + return HoodieTableMetaClient.builder().setStorage(storage).setBasePath(dataPath).build(); + } + + private ConversionConfig getConversionConfig(Table icebergTable) { + TargetTable targetTable = + TargetTable.builder() + .name(icebergTable.name()) + .basePath(dataPath) + .formatName(TableFormat.HUDI) + .additionalProperties(targetTableProperties) + .build(); + return ConversionConfig.builder() + .sourceTable(sourceTable) + .targetTables(Collections.singletonList(targetTable)) + .build(); + } + + @Override + public Dataset<Row> lookup(Table icebergTable, Dataset<Row> keys, String columnName) { + Preconditions.checkArgument( + indexedColumns.contains(columnName), + "Column %s is not one of the indexed columns %s", + columnName, + indexedColumns); + StructType resultSchema = + new StructType() + .add(columnName, DataTypes.StringType, false) + .add(FILE_COLUMN, DataTypes.StringType, false) + .add(POSITION_COLUMN, DataTypes.LongType, false); + // the secondary index stores the values of the indexed column as strings + JavaRDD<String> secondaryKeys = + keys.where(col(columnName).isNotNull()) + .select(col(columnName).cast(DataTypes.StringType)) + .as(Encoders.STRING()) + .toJavaRDD(); + HoodieTableMetaClient metaClient = getMetaClient(); + HoodieStorage storage = metaClient.getStorage(); + if (!metaClient + .getTableConfig() + .getMetadataPartitions() + .contains(PARTITION_NAME_SECONDARY_INDEX_PREFIX + columnName)) { + throw new IllegalStateException( + "The secondary index of column " + + columnName + + " of table " + + tableLocation + + " is not built"); + } + HoodieMetadataConfig metadataConfig = + HoodieMetadataConfig.newBuilder().enable(true).withSecondaryIndexEnabled(true).build(); + try (HoodieBackedTableMetadata tableMetadata = + (HoodieBackedTableMetadata) + metaClient + .getTableFormat() + .getMetadataFactory() + .create(engineContext, storage, metadataConfig, dataPath)) { + HoodiePairData<String, String> recordKeysBySecondaryKey = + tableMetadata.readSecondaryIndexDataTableRecordKeysWithKeys( + HoodieJavaRDD.of(secondaryKeys), PARTITION_NAME_SECONDARY_INDEX_PREFIX + columnName); + // capture the field so the closure does not serialize the index instance + String dataPath = this.dataPath; + JavaRDD<Row> lookupResults = + toJavaPairRDD(recordKeysBySecondaryKey) + .map( + recordKeyBySecondaryKey -> + toLookupResult( + dataPath, recordKeyBySecondaryKey._1(), recordKeyBySecondaryKey._2())); + return sparkSession.createDataFrame(lookupResults, resultSchema); + } + } + + /** + * Hudi returns an RDD backed result for keys in an RDD, but a list backed result when there are + * no keys to look up, for example when every key is null. + */ + private JavaPairRDD<String, String> toJavaPairRDD(HoodiePairData<String, String> pairData) { + if (pairData instanceof HoodieJavaPairRDD) { + return HoodieJavaPairRDD.getJavaPairRDD(pairData); + } + List<Tuple2<String, String>> pairs = + pairData.collectAsList().stream() + .map(pair -> new Tuple2<>(pair.getKey(), pair.getValue())) + .collect(Collectors.toList()); + return javaSparkContext.parallelizePairs(pairs); + } + + private static Row toLookupResult(String dataPath, String secondaryKey, String recordKey) { + // record keys generated by Hudi for files without record keys are "<relative path>_<row + // position>" + int positionSeparator = recordKey.lastIndexOf('_'); + if (positionSeparator == -1) { + throw new IllegalArgumentException( + "Expected a record key of the form <file path>_<row position> but got " + recordKey); + } + String relativeFilePath = recordKey.substring(0, positionSeparator); + return RowFactory.create( + secondaryKey, + dataPath.endsWith("/") ? dataPath + relativeFilePath : dataPath + "/" + relativeFilePath, Review Comment: `dataPath.endsWith("/") ? dataPath + relativeFilePath : dataPath + "/" + relativeFilePath` Isn't there an existing util function for this? ########## xtable-core/src/main/java/org/apache/xtable/index/Index.java: ########## @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xtable.index; + +import org.apache.spark.sql.Dataset; +import org.apache.spark.sql.Row; + +/** + * A secondary index over a table in another format, backed by XTable's Hudi conversion. It maps the + * values of an indexed column to the data file and row position that holds each value, so an engine + * can locate the rows to merge or delete without a full table join. + * + * @param <T> The table type of the source format (for example an Iceberg {@code Table}) + */ +public interface Index<T> { + /** Result column with the full path of the data file that holds the row. */ + String FILE_COLUMN = "_file"; + + /** Result column with the zero based position of the row within the file. */ + String POSITION_COLUMN = "_pos"; + + /** + * Checks whether a secondary index exists for the given column. + * + * @param columnName The indexed column + * @return true when a build of the index has completed + */ + boolean doesIndexExist(String columnName); + + /** + * Brings the secondary indexes of the configured columns up to date with the current state of the + * table. The indexed columns are part of the index configuration, not of the sync. + * + * @param table The table to index + */ + void syncIndex(T table); + + /** + * Looks up the given keys in the secondary index of a column. + * + * @param table The table the index belongs to + * @param keys The values to look up, in the column named {@code columnName} + * @param columnName The indexed column + * @return one row for every row of the table that holds a key, with the key in the column named Review Comment: Make the java doc not coupled to implementation. ########## xtable-core/src/main/java/org/apache/xtable/index/HudiBackedIcebergSecondaryIndex.java: ########## @@ -0,0 +1,299 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xtable.index; + +import static org.apache.hudi.metadata.HoodieTableMetadataUtil.PARTITION_NAME_SECONDARY_INDEX_PREFIX; +import static org.apache.spark.sql.functions.col; + +import java.util.Collections; +import java.util.List; +import java.util.Properties; +import java.util.Set; +import java.util.stream.Collectors; + +import lombok.extern.log4j.Log4j2; + +import org.apache.hadoop.conf.Configuration; +import org.apache.spark.api.java.JavaPairRDD; +import org.apache.spark.api.java.JavaRDD; +import org.apache.spark.api.java.JavaSparkContext; +import org.apache.spark.sql.Dataset; +import org.apache.spark.sql.Encoders; +import org.apache.spark.sql.Row; +import org.apache.spark.sql.RowFactory; +import org.apache.spark.sql.SparkSession; +import org.apache.spark.sql.types.DataTypes; +import org.apache.spark.sql.types.StructType; + +import org.apache.hudi.client.common.HoodieSparkEngineContext; +import org.apache.hudi.common.config.HoodieMetadataConfig; +import org.apache.hudi.common.data.HoodiePairData; +import org.apache.hudi.common.table.HoodieTableMetaClient; +import org.apache.hudi.common.table.HoodieTableVersion; +import org.apache.hudi.data.HoodieJavaPairRDD; +import org.apache.hudi.data.HoodieJavaRDD; +import org.apache.hudi.exception.TableNotFoundException; +import org.apache.hudi.metadata.HoodieBackedTableMetadata; +import org.apache.hudi.storage.HoodieStorage; +import org.apache.hudi.storage.hadoop.HoodieHadoopStorage; + +import org.apache.iceberg.Table; + +import scala.Tuple2; + +import com.google.common.base.Preconditions; + +import org.apache.xtable.catalog.TableFormatUtils; +import org.apache.xtable.conversion.ConversionConfig; +import org.apache.xtable.conversion.ConversionController; +import org.apache.xtable.conversion.SourceTable; +import org.apache.xtable.conversion.TargetTable; +import org.apache.xtable.hudi.HudiTargetConfig; +import org.apache.xtable.iceberg.IcebergConversionSourceProvider; +import org.apache.xtable.model.storage.TableFormat; +import org.apache.xtable.model.sync.SyncResult; +import org.apache.xtable.model.sync.SyncStatusCode; + +/** + * Secondary index for an Iceberg table backed by the Hudi metadata table. The index is built by + * syncing the Iceberg table to Hudi with the record index and a secondary index enabled; the Hudi + * metadata lives under {@code <data location>/.hoodie/metadata}. Because the Iceberg data files + * carry no Hudi record keys, the record key of a row is {@code <file path relative to the data + * location>_<row position>}, which a lookup resolves back to a file path and row position. + */ +@Log4j2 +public class HudiBackedIcebergSecondaryIndex implements Index<Table> { + private final String tableLocation; + private final String dataPath; + private final SourceTable sourceTable; + private final Properties targetTableProperties; + private final List<String> indexedColumns; + private final SparkSession sparkSession; + private final JavaSparkContext javaSparkContext; + private final HoodieSparkEngineContext engineContext; + + /** + * @param icebergTable the table to index + * @param sourceTable how XTable loads the table for a sync, because a loaded table does not + * expose the catalog it came from. A table of a catalog sets its catalog config, name and + * namespace, and a table without a catalog config is loaded from its location + * @param sparkSession the Spark session used to build and query the index + * @param targetTableProperties {@link HudiTargetConfig} properties for the sync. {@link + * HudiTargetConfig#SECONDARY_INDEX_COLUMNS} lists the columns to index, and other properties + * such as the record index file group counts are optional + */ + public HudiBackedIcebergSecondaryIndex( + Table icebergTable, + SourceTable sourceTable, + SparkSession sparkSession, + Properties targetTableProperties) { + Preconditions.checkArgument( + TableFormat.ICEBERG.equals(sourceTable.getFormatName()), + "Expected an Iceberg source table but got format %s", + sourceTable.getFormatName()); + this.tableLocation = icebergTable.location(); + this.dataPath = + TableFormatUtils.getTableDataLocation( + TableFormat.ICEBERG, tableLocation, icebergTable.properties()); + // the Hudi table lives under the data location, which Iceberg resolves from the table + // properties + this.sourceTable = sourceTable.toBuilder().dataPath(dataPath).build(); + this.targetTableProperties = new Properties(); + this.targetTableProperties.putAll(targetTableProperties); + this.targetTableProperties.setProperty( + HudiTargetConfig.EXECUTION_ENGINE, HudiTargetConfig.EXECUTION_ENGINE_SPARK); + // the secondary index is only available from Hudi table version 8 onwards + this.targetTableProperties.setProperty( + HudiTargetConfig.HUDI_TABLE_VERSION, String.valueOf(HoodieTableVersion.NINE.versionCode())); Review Comment: This should be a function of it's own instead of writing consecutive statements like this? ########## xtable-core/src/main/java/org/apache/xtable/hudi/HudiTargetConfig.java: ########## @@ -35,22 +39,130 @@ public class HudiTargetConfig { */ public static final String HUDI_TABLE_VERSION = "xtable.hudi.target.table_version"; + /** + * Engine that writes the Hudi commit and the metadata table indexes. Supported values are {@code + * java} (default) and {@code spark}. The Spark engine reuses the active Spark session and + * distributes the index generation, which is recommended when the record index or a secondary + * index is enabled because those indexes read every registered data file. + */ + public static final String EXECUTION_ENGINE = "xtable.hudi.target.execution.engine"; + + public static final String EXECUTION_ENGINE_JAVA = "java"; + public static final String EXECUTION_ENGINE_SPARK = "spark"; + + /** + * Comma separated columns to build a Hudi secondary index on, one index per column. Setting it + * also enables the global record index, which the secondary index depends on. The indexes are + * stored in the Hudi metadata table under the target table path and require table version 9. The + * indexes are built when the Hudi table is created; a column added to the list of an existing + * table is not indexed yet. + */ + public static final String SECONDARY_INDEX_COLUMNS = "xtable.hudi.target.secondary.index.columns"; + + /** + * Lower and upper bound on the number of file groups of the record index. Both must be set + * together; when unset the Hudi defaults apply. + */ + public static final String RECORD_INDEX_MIN_FILEGROUP_COUNT = + "xtable.hudi.target.metadata.record.index.min.filegroup.count"; + + public static final String RECORD_INDEX_MAX_FILEGROUP_COUNT = + "xtable.hudi.target.metadata.record.index.max.filegroup.count"; + + /** Parallelism used when generating the secondary index records. */ + public static final String SECONDARY_INDEX_PARALLELISM = + "xtable.hudi.target.metadata.index.secondary.parallelism"; + static final HoodieTableVersion DEFAULT_TABLE_VERSION = HoodieTableVersion.SIX; HoodieTableVersion tableVersion; + boolean sparkEngine; + List<String> secondaryIndexColumns; + Optional<Integer> recordIndexMinFileGroupCount; + Optional<Integer> recordIndexMaxFileGroupCount; + Optional<Integer> secondaryIndexParallelism; public static HudiTargetConfig fromProperties(Properties properties) { + Properties targetProperties = properties == null ? new Properties() : properties; + HoodieTableVersion tableVersion = parseTableVersion(targetProperties); + boolean sparkEngine = parseSparkEngine(targetProperties); + List<String> secondaryIndexColumns = + Arrays.stream(targetProperties.getProperty(SECONDARY_INDEX_COLUMNS, "").split(",")) + .map(String::trim) + .filter(column -> !column.isEmpty()) + .distinct() + .collect(Collectors.toList()); + if (!secondaryIndexColumns.isEmpty() && tableVersion != HoodieTableVersion.NINE) { + throw new IllegalArgumentException( + String.format( + "%s requires Hudi target table version 9, set %s=9.", + SECONDARY_INDEX_COLUMNS, HUDI_TABLE_VERSION)); + } + if (secondaryIndexColumns.size() > 1 && !sparkEngine) { + // Hudi builds the index of the first column in the commit and the others with its indexer. + // In Hudi 1.2.1 the Java engine's JavaHoodieMetadataBulkInsertPartitioner writes an index + // built from existing files into a single file group, so lookups miss most keys. + throw new IllegalArgumentException( + String.format( + "More than one column in %s requires %s=%s.", + SECONDARY_INDEX_COLUMNS, EXECUTION_ENGINE, EXECUTION_ENGINE_SPARK)); + } + Optional<Integer> recordIndexMinFileGroupCount = + parsePositiveInt(targetProperties, RECORD_INDEX_MIN_FILEGROUP_COUNT); + Optional<Integer> recordIndexMaxFileGroupCount = + parsePositiveInt(targetProperties, RECORD_INDEX_MAX_FILEGROUP_COUNT); + if (recordIndexMinFileGroupCount.isPresent() != recordIndexMaxFileGroupCount.isPresent()) { + throw new IllegalArgumentException( + String.format( + "%s and %s must be set together.", + RECORD_INDEX_MIN_FILEGROUP_COUNT, RECORD_INDEX_MAX_FILEGROUP_COUNT)); + } + return new HudiTargetConfig( + tableVersion, + sparkEngine, + secondaryIndexColumns, + recordIndexMinFileGroupCount, + recordIndexMaxFileGroupCount, + parsePositiveInt(targetProperties, SECONDARY_INDEX_PARALLELISM)); + } + + private static HoodieTableVersion parseTableVersion(Properties properties) { HoodieTableVersion tableVersion = DEFAULT_TABLE_VERSION; - if (properties != null) { - String configured = properties.getProperty(HUDI_TABLE_VERSION); - if (configured != null && !configured.trim().isEmpty()) { - tableVersion = parseTableVersion(configured.trim()); - } + String configured = properties.getProperty(HUDI_TABLE_VERSION); + if (configured != null && !configured.trim().isEmpty()) { + tableVersion = parseTableVersion(configured.trim()); } if (tableVersion != HoodieTableVersion.SIX && tableVersion != HoodieTableVersion.NINE) { throw unsupportedTableVersion(String.valueOf(tableVersion.versionCode()), null); } - return new HudiTargetConfig(tableVersion); + return tableVersion; + } + + private static boolean parseSparkEngine(Properties properties) { + String engine = properties.getProperty(EXECUTION_ENGINE, EXECUTION_ENGINE_JAVA).trim(); Review Comment: Would defining an enum simplify this function here? ########## xtable-core/src/main/java/org/apache/xtable/index/Index.java: ########## @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xtable.index; + +import org.apache.spark.sql.Dataset; +import org.apache.spark.sql.Row; + +/** + * A secondary index over a table in another format, backed by XTable's Hudi conversion. It maps the Review Comment: Remove secondary from the java docs...it's an implementation detail of the index backed by hudi not something that needs to be leaked into the interface. ########## xtable-core/src/main/java/org/apache/xtable/index/HudiBackedIcebergSecondaryIndex.java: ########## @@ -0,0 +1,299 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xtable.index; + +import static org.apache.hudi.metadata.HoodieTableMetadataUtil.PARTITION_NAME_SECONDARY_INDEX_PREFIX; +import static org.apache.spark.sql.functions.col; + +import java.util.Collections; +import java.util.List; +import java.util.Properties; +import java.util.Set; +import java.util.stream.Collectors; + +import lombok.extern.log4j.Log4j2; + +import org.apache.hadoop.conf.Configuration; +import org.apache.spark.api.java.JavaPairRDD; +import org.apache.spark.api.java.JavaRDD; +import org.apache.spark.api.java.JavaSparkContext; +import org.apache.spark.sql.Dataset; +import org.apache.spark.sql.Encoders; +import org.apache.spark.sql.Row; +import org.apache.spark.sql.RowFactory; +import org.apache.spark.sql.SparkSession; +import org.apache.spark.sql.types.DataTypes; +import org.apache.spark.sql.types.StructType; + +import org.apache.hudi.client.common.HoodieSparkEngineContext; +import org.apache.hudi.common.config.HoodieMetadataConfig; +import org.apache.hudi.common.data.HoodiePairData; +import org.apache.hudi.common.table.HoodieTableMetaClient; +import org.apache.hudi.common.table.HoodieTableVersion; +import org.apache.hudi.data.HoodieJavaPairRDD; +import org.apache.hudi.data.HoodieJavaRDD; +import org.apache.hudi.exception.TableNotFoundException; +import org.apache.hudi.metadata.HoodieBackedTableMetadata; +import org.apache.hudi.storage.HoodieStorage; +import org.apache.hudi.storage.hadoop.HoodieHadoopStorage; + +import org.apache.iceberg.Table; + +import scala.Tuple2; + +import com.google.common.base.Preconditions; + +import org.apache.xtable.catalog.TableFormatUtils; +import org.apache.xtable.conversion.ConversionConfig; +import org.apache.xtable.conversion.ConversionController; +import org.apache.xtable.conversion.SourceTable; +import org.apache.xtable.conversion.TargetTable; +import org.apache.xtable.hudi.HudiTargetConfig; +import org.apache.xtable.iceberg.IcebergConversionSourceProvider; +import org.apache.xtable.model.storage.TableFormat; +import org.apache.xtable.model.sync.SyncResult; +import org.apache.xtable.model.sync.SyncStatusCode; + +/** + * Secondary index for an Iceberg table backed by the Hudi metadata table. The index is built by + * syncing the Iceberg table to Hudi with the record index and a secondary index enabled; the Hudi + * metadata lives under {@code <data location>/.hoodie/metadata}. Because the Iceberg data files + * carry no Hudi record keys, the record key of a row is {@code <file path relative to the data + * location>_<row position>}, which a lookup resolves back to a file path and row position. + */ +@Log4j2 +public class HudiBackedIcebergSecondaryIndex implements Index<Table> { + private final String tableLocation; + private final String dataPath; + private final SourceTable sourceTable; + private final Properties targetTableProperties; + private final List<String> indexedColumns; + private final SparkSession sparkSession; + private final JavaSparkContext javaSparkContext; + private final HoodieSparkEngineContext engineContext; + + /** + * @param icebergTable the table to index + * @param sourceTable how XTable loads the table for a sync, because a loaded table does not + * expose the catalog it came from. A table of a catalog sets its catalog config, name and + * namespace, and a table without a catalog config is loaded from its location + * @param sparkSession the Spark session used to build and query the index + * @param targetTableProperties {@link HudiTargetConfig} properties for the sync. {@link + * HudiTargetConfig#SECONDARY_INDEX_COLUMNS} lists the columns to index, and other properties + * such as the record index file group counts are optional + */ + public HudiBackedIcebergSecondaryIndex( + Table icebergTable, + SourceTable sourceTable, + SparkSession sparkSession, + Properties targetTableProperties) { + Preconditions.checkArgument( + TableFormat.ICEBERG.equals(sourceTable.getFormatName()), + "Expected an Iceberg source table but got format %s", + sourceTable.getFormatName()); + this.tableLocation = icebergTable.location(); + this.dataPath = + TableFormatUtils.getTableDataLocation( + TableFormat.ICEBERG, tableLocation, icebergTable.properties()); + // the Hudi table lives under the data location, which Iceberg resolves from the table + // properties + this.sourceTable = sourceTable.toBuilder().dataPath(dataPath).build(); + this.targetTableProperties = new Properties(); + this.targetTableProperties.putAll(targetTableProperties); + this.targetTableProperties.setProperty( + HudiTargetConfig.EXECUTION_ENGINE, HudiTargetConfig.EXECUTION_ENGINE_SPARK); + // the secondary index is only available from Hudi table version 8 onwards + this.targetTableProperties.setProperty( + HudiTargetConfig.HUDI_TABLE_VERSION, String.valueOf(HoodieTableVersion.NINE.versionCode())); + this.indexedColumns = + HudiTargetConfig.fromProperties(this.targetTableProperties).getSecondaryIndexColumns(); + Preconditions.checkArgument( + !indexedColumns.isEmpty(), + "Set %s to the columns to index", + HudiTargetConfig.SECONDARY_INDEX_COLUMNS); + this.sparkSession = sparkSession; + this.javaSparkContext = JavaSparkContext.fromSparkContext(sparkSession.sparkContext()); + this.engineContext = new HoodieSparkEngineContext(javaSparkContext); + } + + @Override + public boolean doesIndexExist(String columnName) { + return getCompletedIndexPartitions() + .contains(PARTITION_NAME_SECONDARY_INDEX_PREFIX + columnName); + } + + @Override + public void syncIndex(Table icebergTable) { + Configuration configuration = javaSparkContext.hadoopConfiguration(); + IcebergConversionSourceProvider sourceProvider = new IcebergConversionSourceProvider(); + sourceProvider.init(configuration); + // The sync reports a failed target in its result instead of throwing. It returns no result + // for the target when the table has no new commits. + SyncResult syncResult = + new ConversionController(configuration) + .sync(getConversionConfig(icebergTable), sourceProvider) + .get(TableFormat.HUDI); + if (syncResult != null + && (syncResult.getTableFormatSyncStatus() == null + || syncResult.getTableFormatSyncStatus().getStatusCode() != SyncStatusCode.SUCCESS)) { + throw new IllegalStateException( Review Comment: There should be utility function to get formatted error message from `SyncResult`? ########## xtable-core/src/main/java/org/apache/xtable/index/HudiBackedIcebergSecondaryIndex.java: ########## @@ -0,0 +1,299 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xtable.index; + +import static org.apache.hudi.metadata.HoodieTableMetadataUtil.PARTITION_NAME_SECONDARY_INDEX_PREFIX; +import static org.apache.spark.sql.functions.col; + +import java.util.Collections; +import java.util.List; +import java.util.Properties; +import java.util.Set; +import java.util.stream.Collectors; + +import lombok.extern.log4j.Log4j2; + +import org.apache.hadoop.conf.Configuration; +import org.apache.spark.api.java.JavaPairRDD; +import org.apache.spark.api.java.JavaRDD; +import org.apache.spark.api.java.JavaSparkContext; +import org.apache.spark.sql.Dataset; +import org.apache.spark.sql.Encoders; +import org.apache.spark.sql.Row; +import org.apache.spark.sql.RowFactory; +import org.apache.spark.sql.SparkSession; +import org.apache.spark.sql.types.DataTypes; +import org.apache.spark.sql.types.StructType; + +import org.apache.hudi.client.common.HoodieSparkEngineContext; +import org.apache.hudi.common.config.HoodieMetadataConfig; +import org.apache.hudi.common.data.HoodiePairData; +import org.apache.hudi.common.table.HoodieTableMetaClient; +import org.apache.hudi.common.table.HoodieTableVersion; +import org.apache.hudi.data.HoodieJavaPairRDD; +import org.apache.hudi.data.HoodieJavaRDD; +import org.apache.hudi.exception.TableNotFoundException; +import org.apache.hudi.metadata.HoodieBackedTableMetadata; +import org.apache.hudi.storage.HoodieStorage; +import org.apache.hudi.storage.hadoop.HoodieHadoopStorage; + +import org.apache.iceberg.Table; + +import scala.Tuple2; + +import com.google.common.base.Preconditions; + +import org.apache.xtable.catalog.TableFormatUtils; +import org.apache.xtable.conversion.ConversionConfig; +import org.apache.xtable.conversion.ConversionController; +import org.apache.xtable.conversion.SourceTable; +import org.apache.xtable.conversion.TargetTable; +import org.apache.xtable.hudi.HudiTargetConfig; +import org.apache.xtable.iceberg.IcebergConversionSourceProvider; +import org.apache.xtable.model.storage.TableFormat; +import org.apache.xtable.model.sync.SyncResult; +import org.apache.xtable.model.sync.SyncStatusCode; + +/** + * Secondary index for an Iceberg table backed by the Hudi metadata table. The index is built by + * syncing the Iceberg table to Hudi with the record index and a secondary index enabled; the Hudi + * metadata lives under {@code <data location>/.hoodie/metadata}. Because the Iceberg data files + * carry no Hudi record keys, the record key of a row is {@code <file path relative to the data + * location>_<row position>}, which a lookup resolves back to a file path and row position. + */ +@Log4j2 +public class HudiBackedIcebergSecondaryIndex implements Index<Table> { + private final String tableLocation; + private final String dataPath; + private final SourceTable sourceTable; + private final Properties targetTableProperties; + private final List<String> indexedColumns; + private final SparkSession sparkSession; + private final JavaSparkContext javaSparkContext; + private final HoodieSparkEngineContext engineContext; + + /** + * @param icebergTable the table to index + * @param sourceTable how XTable loads the table for a sync, because a loaded table does not + * expose the catalog it came from. A table of a catalog sets its catalog config, name and + * namespace, and a table without a catalog config is loaded from its location + * @param sparkSession the Spark session used to build and query the index + * @param targetTableProperties {@link HudiTargetConfig} properties for the sync. {@link + * HudiTargetConfig#SECONDARY_INDEX_COLUMNS} lists the columns to index, and other properties + * such as the record index file group counts are optional + */ + public HudiBackedIcebergSecondaryIndex( + Table icebergTable, + SourceTable sourceTable, + SparkSession sparkSession, + Properties targetTableProperties) { + Preconditions.checkArgument( + TableFormat.ICEBERG.equals(sourceTable.getFormatName()), + "Expected an Iceberg source table but got format %s", + sourceTable.getFormatName()); + this.tableLocation = icebergTable.location(); + this.dataPath = Review Comment: The iceberg data path can be a completely different location hope that's handled and we are not simply appending _data? ########## xtable-core/src/main/java/org/apache/xtable/hudi/HudiConversionTarget.java: ########## @@ -482,6 +501,36 @@ private Optional<TableSyncMetadata> getMetadata( } } + /** + * Registers a definition for every secondary index partition that has none. Hudi updates every + * secondary index on each commit through its definition, but the commit that creates the metadata + * table rewrites the column-stats index definition from a stale view of the definitions, which + * drops the secondary index definition registered in the same commit. + */ + static void restoreSecondaryIndexDefinitions(HoodieTableMetaClient metaClient) { Review Comment: All these new private methods for writing and building secondary index have bloated HudiConversionTarget, any way we can refactor this to define better abstractions? ########## xtable-core/src/main/java/org/apache/xtable/index/HudiBackedIcebergSecondaryIndex.java: ########## @@ -0,0 +1,299 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xtable.index; + +import static org.apache.hudi.metadata.HoodieTableMetadataUtil.PARTITION_NAME_SECONDARY_INDEX_PREFIX; +import static org.apache.spark.sql.functions.col; + +import java.util.Collections; +import java.util.List; +import java.util.Properties; +import java.util.Set; +import java.util.stream.Collectors; + +import lombok.extern.log4j.Log4j2; + +import org.apache.hadoop.conf.Configuration; +import org.apache.spark.api.java.JavaPairRDD; +import org.apache.spark.api.java.JavaRDD; +import org.apache.spark.api.java.JavaSparkContext; +import org.apache.spark.sql.Dataset; +import org.apache.spark.sql.Encoders; +import org.apache.spark.sql.Row; +import org.apache.spark.sql.RowFactory; +import org.apache.spark.sql.SparkSession; +import org.apache.spark.sql.types.DataTypes; +import org.apache.spark.sql.types.StructType; + +import org.apache.hudi.client.common.HoodieSparkEngineContext; +import org.apache.hudi.common.config.HoodieMetadataConfig; +import org.apache.hudi.common.data.HoodiePairData; +import org.apache.hudi.common.table.HoodieTableMetaClient; +import org.apache.hudi.common.table.HoodieTableVersion; +import org.apache.hudi.data.HoodieJavaPairRDD; +import org.apache.hudi.data.HoodieJavaRDD; +import org.apache.hudi.exception.TableNotFoundException; +import org.apache.hudi.metadata.HoodieBackedTableMetadata; +import org.apache.hudi.storage.HoodieStorage; +import org.apache.hudi.storage.hadoop.HoodieHadoopStorage; + +import org.apache.iceberg.Table; + +import scala.Tuple2; + +import com.google.common.base.Preconditions; + +import org.apache.xtable.catalog.TableFormatUtils; +import org.apache.xtable.conversion.ConversionConfig; +import org.apache.xtable.conversion.ConversionController; +import org.apache.xtable.conversion.SourceTable; +import org.apache.xtable.conversion.TargetTable; +import org.apache.xtable.hudi.HudiTargetConfig; +import org.apache.xtable.iceberg.IcebergConversionSourceProvider; +import org.apache.xtable.model.storage.TableFormat; +import org.apache.xtable.model.sync.SyncResult; +import org.apache.xtable.model.sync.SyncStatusCode; + +/** + * Secondary index for an Iceberg table backed by the Hudi metadata table. The index is built by + * syncing the Iceberg table to Hudi with the record index and a secondary index enabled; the Hudi + * metadata lives under {@code <data location>/.hoodie/metadata}. Because the Iceberg data files + * carry no Hudi record keys, the record key of a row is {@code <file path relative to the data + * location>_<row position>}, which a lookup resolves back to a file path and row position. + */ +@Log4j2 +public class HudiBackedIcebergSecondaryIndex implements Index<Table> { + private final String tableLocation; + private final String dataPath; + private final SourceTable sourceTable; + private final Properties targetTableProperties; + private final List<String> indexedColumns; + private final SparkSession sparkSession; + private final JavaSparkContext javaSparkContext; + private final HoodieSparkEngineContext engineContext; + + /** + * @param icebergTable the table to index + * @param sourceTable how XTable loads the table for a sync, because a loaded table does not + * expose the catalog it came from. A table of a catalog sets its catalog config, name and + * namespace, and a table without a catalog config is loaded from its location + * @param sparkSession the Spark session used to build and query the index + * @param targetTableProperties {@link HudiTargetConfig} properties for the sync. {@link + * HudiTargetConfig#SECONDARY_INDEX_COLUMNS} lists the columns to index, and other properties + * such as the record index file group counts are optional + */ + public HudiBackedIcebergSecondaryIndex( + Table icebergTable, + SourceTable sourceTable, + SparkSession sparkSession, + Properties targetTableProperties) { + Preconditions.checkArgument( + TableFormat.ICEBERG.equals(sourceTable.getFormatName()), + "Expected an Iceberg source table but got format %s", + sourceTable.getFormatName()); + this.tableLocation = icebergTable.location(); + this.dataPath = + TableFormatUtils.getTableDataLocation( + TableFormat.ICEBERG, tableLocation, icebergTable.properties()); + // the Hudi table lives under the data location, which Iceberg resolves from the table + // properties + this.sourceTable = sourceTable.toBuilder().dataPath(dataPath).build(); + this.targetTableProperties = new Properties(); + this.targetTableProperties.putAll(targetTableProperties); + this.targetTableProperties.setProperty( + HudiTargetConfig.EXECUTION_ENGINE, HudiTargetConfig.EXECUTION_ENGINE_SPARK); + // the secondary index is only available from Hudi table version 8 onwards + this.targetTableProperties.setProperty( + HudiTargetConfig.HUDI_TABLE_VERSION, String.valueOf(HoodieTableVersion.NINE.versionCode())); + this.indexedColumns = + HudiTargetConfig.fromProperties(this.targetTableProperties).getSecondaryIndexColumns(); + Preconditions.checkArgument( + !indexedColumns.isEmpty(), + "Set %s to the columns to index", + HudiTargetConfig.SECONDARY_INDEX_COLUMNS); + this.sparkSession = sparkSession; + this.javaSparkContext = JavaSparkContext.fromSparkContext(sparkSession.sparkContext()); + this.engineContext = new HoodieSparkEngineContext(javaSparkContext); + } + + @Override + public boolean doesIndexExist(String columnName) { + return getCompletedIndexPartitions() + .contains(PARTITION_NAME_SECONDARY_INDEX_PREFIX + columnName); + } + + @Override + public void syncIndex(Table icebergTable) { + Configuration configuration = javaSparkContext.hadoopConfiguration(); + IcebergConversionSourceProvider sourceProvider = new IcebergConversionSourceProvider(); + sourceProvider.init(configuration); + // The sync reports a failed target in its result instead of throwing. It returns no result + // for the target when the table has no new commits. + SyncResult syncResult = + new ConversionController(configuration) + .sync(getConversionConfig(icebergTable), sourceProvider) + .get(TableFormat.HUDI); + if (syncResult != null + && (syncResult.getTableFormatSyncStatus() == null + || syncResult.getTableFormatSyncStatus().getStatusCode() != SyncStatusCode.SUCCESS)) { + throw new IllegalStateException( + "Failed to sync the secondary indexes of columns " + + indexedColumns + + " of table " + + tableLocation + + ": " + + syncResult.getTableFormatSyncStatus()); + } + Set<String> completedPartitions = getCompletedIndexPartitions(); + List<String> notIndexed = + indexedColumns.stream() + .filter( + column -> + !completedPartitions.contains(PARTITION_NAME_SECONDARY_INDEX_PREFIX + column)) + .collect(Collectors.toList()); + if (!notIndexed.isEmpty()) { + throw new IllegalStateException( + "The secondary indexes of columns " + + notIndexed + + " of table " + + tableLocation + + " do not exist. The indexes are built when the index is created, and adding a" + + " column to an existing index is not supported yet."); + } + log.info( + "Synced the secondary indexes of columns {} of table {}", indexedColumns, tableLocation); + } + + /** + * Returns the metadata table partitions whose build has completed. A partition directory can + * exist while the build is in flight or after it failed, so the directory alone does not show + * that the index is usable. + */ + private Set<String> getCompletedIndexPartitions() { Review Comment: Rename to `getIndexedColumns()`? The name of the function shouldn't necessarily reveal internal implementation details? ########## xtable-core/src/main/java/org/apache/xtable/index/HudiBackedIcebergSecondaryIndex.java: ########## @@ -0,0 +1,299 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xtable.index; + +import static org.apache.hudi.metadata.HoodieTableMetadataUtil.PARTITION_NAME_SECONDARY_INDEX_PREFIX; +import static org.apache.spark.sql.functions.col; + +import java.util.Collections; +import java.util.List; +import java.util.Properties; +import java.util.Set; +import java.util.stream.Collectors; + +import lombok.extern.log4j.Log4j2; + +import org.apache.hadoop.conf.Configuration; +import org.apache.spark.api.java.JavaPairRDD; +import org.apache.spark.api.java.JavaRDD; +import org.apache.spark.api.java.JavaSparkContext; +import org.apache.spark.sql.Dataset; +import org.apache.spark.sql.Encoders; +import org.apache.spark.sql.Row; +import org.apache.spark.sql.RowFactory; +import org.apache.spark.sql.SparkSession; +import org.apache.spark.sql.types.DataTypes; +import org.apache.spark.sql.types.StructType; + +import org.apache.hudi.client.common.HoodieSparkEngineContext; +import org.apache.hudi.common.config.HoodieMetadataConfig; +import org.apache.hudi.common.data.HoodiePairData; +import org.apache.hudi.common.table.HoodieTableMetaClient; +import org.apache.hudi.common.table.HoodieTableVersion; +import org.apache.hudi.data.HoodieJavaPairRDD; +import org.apache.hudi.data.HoodieJavaRDD; +import org.apache.hudi.exception.TableNotFoundException; +import org.apache.hudi.metadata.HoodieBackedTableMetadata; +import org.apache.hudi.storage.HoodieStorage; +import org.apache.hudi.storage.hadoop.HoodieHadoopStorage; + +import org.apache.iceberg.Table; + +import scala.Tuple2; + +import com.google.common.base.Preconditions; + +import org.apache.xtable.catalog.TableFormatUtils; +import org.apache.xtable.conversion.ConversionConfig; +import org.apache.xtable.conversion.ConversionController; +import org.apache.xtable.conversion.SourceTable; +import org.apache.xtable.conversion.TargetTable; +import org.apache.xtable.hudi.HudiTargetConfig; +import org.apache.xtable.iceberg.IcebergConversionSourceProvider; +import org.apache.xtable.model.storage.TableFormat; +import org.apache.xtable.model.sync.SyncResult; +import org.apache.xtable.model.sync.SyncStatusCode; + +/** + * Secondary index for an Iceberg table backed by the Hudi metadata table. The index is built by + * syncing the Iceberg table to Hudi with the record index and a secondary index enabled; the Hudi + * metadata lives under {@code <data location>/.hoodie/metadata}. Because the Iceberg data files + * carry no Hudi record keys, the record key of a row is {@code <file path relative to the data + * location>_<row position>}, which a lookup resolves back to a file path and row position. + */ +@Log4j2 +public class HudiBackedIcebergSecondaryIndex implements Index<Table> { + private final String tableLocation; + private final String dataPath; + private final SourceTable sourceTable; + private final Properties targetTableProperties; + private final List<String> indexedColumns; + private final SparkSession sparkSession; + private final JavaSparkContext javaSparkContext; + private final HoodieSparkEngineContext engineContext; + + /** + * @param icebergTable the table to index + * @param sourceTable how XTable loads the table for a sync, because a loaded table does not + * expose the catalog it came from. A table of a catalog sets its catalog config, name and + * namespace, and a table without a catalog config is loaded from its location + * @param sparkSession the Spark session used to build and query the index + * @param targetTableProperties {@link HudiTargetConfig} properties for the sync. {@link + * HudiTargetConfig#SECONDARY_INDEX_COLUMNS} lists the columns to index, and other properties + * such as the record index file group counts are optional + */ + public HudiBackedIcebergSecondaryIndex( + Table icebergTable, + SourceTable sourceTable, + SparkSession sparkSession, + Properties targetTableProperties) { + Preconditions.checkArgument( + TableFormat.ICEBERG.equals(sourceTable.getFormatName()), + "Expected an Iceberg source table but got format %s", + sourceTable.getFormatName()); + this.tableLocation = icebergTable.location(); + this.dataPath = + TableFormatUtils.getTableDataLocation( + TableFormat.ICEBERG, tableLocation, icebergTable.properties()); + // the Hudi table lives under the data location, which Iceberg resolves from the table + // properties + this.sourceTable = sourceTable.toBuilder().dataPath(dataPath).build(); + this.targetTableProperties = new Properties(); + this.targetTableProperties.putAll(targetTableProperties); + this.targetTableProperties.setProperty( + HudiTargetConfig.EXECUTION_ENGINE, HudiTargetConfig.EXECUTION_ENGINE_SPARK); + // the secondary index is only available from Hudi table version 8 onwards + this.targetTableProperties.setProperty( + HudiTargetConfig.HUDI_TABLE_VERSION, String.valueOf(HoodieTableVersion.NINE.versionCode())); + this.indexedColumns = + HudiTargetConfig.fromProperties(this.targetTableProperties).getSecondaryIndexColumns(); + Preconditions.checkArgument( + !indexedColumns.isEmpty(), + "Set %s to the columns to index", + HudiTargetConfig.SECONDARY_INDEX_COLUMNS); + this.sparkSession = sparkSession; + this.javaSparkContext = JavaSparkContext.fromSparkContext(sparkSession.sparkContext()); + this.engineContext = new HoodieSparkEngineContext(javaSparkContext); + } + + @Override + public boolean doesIndexExist(String columnName) { + return getCompletedIndexPartitions() + .contains(PARTITION_NAME_SECONDARY_INDEX_PREFIX + columnName); + } + + @Override + public void syncIndex(Table icebergTable) { + Configuration configuration = javaSparkContext.hadoopConfiguration(); + IcebergConversionSourceProvider sourceProvider = new IcebergConversionSourceProvider(); + sourceProvider.init(configuration); + // The sync reports a failed target in its result instead of throwing. It returns no result + // for the target when the table has no new commits. + SyncResult syncResult = + new ConversionController(configuration) + .sync(getConversionConfig(icebergTable), sourceProvider) + .get(TableFormat.HUDI); + if (syncResult != null + && (syncResult.getTableFormatSyncStatus() == null + || syncResult.getTableFormatSyncStatus().getStatusCode() != SyncStatusCode.SUCCESS)) { + throw new IllegalStateException( + "Failed to sync the secondary indexes of columns " + + indexedColumns + + " of table " + + tableLocation + + ": " + + syncResult.getTableFormatSyncStatus()); + } + Set<String> completedPartitions = getCompletedIndexPartitions(); + List<String> notIndexed = + indexedColumns.stream() + .filter( + column -> + !completedPartitions.contains(PARTITION_NAME_SECONDARY_INDEX_PREFIX + column)) + .collect(Collectors.toList()); + if (!notIndexed.isEmpty()) { + throw new IllegalStateException( + "The secondary indexes of columns " + + notIndexed + + " of table " + + tableLocation + + " do not exist. The indexes are built when the index is created, and adding a" + + " column to an existing index is not supported yet."); + } + log.info( + "Synced the secondary indexes of columns {} of table {}", indexedColumns, tableLocation); + } + + /** + * Returns the metadata table partitions whose build has completed. A partition directory can + * exist while the build is in flight or after it failed, so the directory alone does not show + * that the index is usable. + */ + private Set<String> getCompletedIndexPartitions() { + try { + return getMetaClient().getTableConfig().getMetadataPartitions(); + } catch (TableNotFoundException e) { + return Collections.emptySet(); + } + } + + private HoodieTableMetaClient getMetaClient() { + HoodieStorage storage = + new HoodieHadoopStorage(dataPath, javaSparkContext.hadoopConfiguration()); + return HoodieTableMetaClient.builder().setStorage(storage).setBasePath(dataPath).build(); + } + + private ConversionConfig getConversionConfig(Table icebergTable) { + TargetTable targetTable = + TargetTable.builder() + .name(icebergTable.name()) + .basePath(dataPath) + .formatName(TableFormat.HUDI) + .additionalProperties(targetTableProperties) + .build(); + return ConversionConfig.builder() + .sourceTable(sourceTable) + .targetTables(Collections.singletonList(targetTable)) + .build(); + } + + @Override + public Dataset<Row> lookup(Table icebergTable, Dataset<Row> keys, String columnName) { + Preconditions.checkArgument( + indexedColumns.contains(columnName), + "Column %s is not one of the indexed columns %s", + columnName, + indexedColumns); + StructType resultSchema = + new StructType() + .add(columnName, DataTypes.StringType, false) + .add(FILE_COLUMN, DataTypes.StringType, false) + .add(POSITION_COLUMN, DataTypes.LongType, false); + // the secondary index stores the values of the indexed column as strings + JavaRDD<String> secondaryKeys = + keys.where(col(columnName).isNotNull()) + .select(col(columnName).cast(DataTypes.StringType)) + .as(Encoders.STRING()) + .toJavaRDD(); + HoodieTableMetaClient metaClient = getMetaClient(); + HoodieStorage storage = metaClient.getStorage(); + if (!metaClient + .getTableConfig() + .getMetadataPartitions() + .contains(PARTITION_NAME_SECONDARY_INDEX_PREFIX + columnName)) { + throw new IllegalStateException( + "The secondary index of column " + + columnName + + " of table " + + tableLocation + + " is not built"); + } + HoodieMetadataConfig metadataConfig = + HoodieMetadataConfig.newBuilder().enable(true).withSecondaryIndexEnabled(true).build(); + try (HoodieBackedTableMetadata tableMetadata = + (HoodieBackedTableMetadata) + metaClient + .getTableFormat() + .getMetadataFactory() + .create(engineContext, storage, metadataConfig, dataPath)) { + HoodiePairData<String, String> recordKeysBySecondaryKey = + tableMetadata.readSecondaryIndexDataTableRecordKeysWithKeys( + HoodieJavaRDD.of(secondaryKeys), PARTITION_NAME_SECONDARY_INDEX_PREFIX + columnName); + // capture the field so the closure does not serialize the index instance + String dataPath = this.dataPath; + JavaRDD<Row> lookupResults = + toJavaPairRDD(recordKeysBySecondaryKey) + .map( + recordKeyBySecondaryKey -> + toLookupResult( + dataPath, recordKeyBySecondaryKey._1(), recordKeyBySecondaryKey._2())); + return sparkSession.createDataFrame(lookupResults, resultSchema); + } + } + + /** + * Hudi returns an RDD backed result for keys in an RDD, but a list backed result when there are + * no keys to look up, for example when every key is null. + */ + private JavaPairRDD<String, String> toJavaPairRDD(HoodiePairData<String, String> pairData) { + if (pairData instanceof HoodieJavaPairRDD) { + return HoodieJavaPairRDD.getJavaPairRDD(pairData); + } + List<Tuple2<String, String>> pairs = + pairData.collectAsList().stream() + .map(pair -> new Tuple2<>(pair.getKey(), pair.getValue())) + .collect(Collectors.toList()); Review Comment: Doesn't this collect everything to the driver and cause OOM? Why do we handle this special method of toJavaPairRDD? ########## xtable-core/src/main/java/org/apache/xtable/hudi/HudiTargetConfig.java: ########## @@ -35,22 +39,130 @@ public class HudiTargetConfig { */ public static final String HUDI_TABLE_VERSION = "xtable.hudi.target.table_version"; + /** + * Engine that writes the Hudi commit and the metadata table indexes. Supported values are {@code + * java} (default) and {@code spark}. The Spark engine reuses the active Spark session and + * distributes the index generation, which is recommended when the record index or a secondary + * index is enabled because those indexes read every registered data file. + */ + public static final String EXECUTION_ENGINE = "xtable.hudi.target.execution.engine"; + + public static final String EXECUTION_ENGINE_JAVA = "java"; + public static final String EXECUTION_ENGINE_SPARK = "spark"; Review Comment: An enum would be helpful here? ########## xtable-core/src/main/java/org/apache/xtable/index/HudiBackedIcebergSecondaryIndex.java: ########## @@ -0,0 +1,299 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xtable.index; + +import static org.apache.hudi.metadata.HoodieTableMetadataUtil.PARTITION_NAME_SECONDARY_INDEX_PREFIX; +import static org.apache.spark.sql.functions.col; + +import java.util.Collections; +import java.util.List; +import java.util.Properties; +import java.util.Set; +import java.util.stream.Collectors; + +import lombok.extern.log4j.Log4j2; + +import org.apache.hadoop.conf.Configuration; +import org.apache.spark.api.java.JavaPairRDD; +import org.apache.spark.api.java.JavaRDD; +import org.apache.spark.api.java.JavaSparkContext; +import org.apache.spark.sql.Dataset; +import org.apache.spark.sql.Encoders; +import org.apache.spark.sql.Row; +import org.apache.spark.sql.RowFactory; +import org.apache.spark.sql.SparkSession; +import org.apache.spark.sql.types.DataTypes; +import org.apache.spark.sql.types.StructType; + +import org.apache.hudi.client.common.HoodieSparkEngineContext; +import org.apache.hudi.common.config.HoodieMetadataConfig; +import org.apache.hudi.common.data.HoodiePairData; +import org.apache.hudi.common.table.HoodieTableMetaClient; +import org.apache.hudi.common.table.HoodieTableVersion; +import org.apache.hudi.data.HoodieJavaPairRDD; +import org.apache.hudi.data.HoodieJavaRDD; +import org.apache.hudi.exception.TableNotFoundException; +import org.apache.hudi.metadata.HoodieBackedTableMetadata; +import org.apache.hudi.storage.HoodieStorage; +import org.apache.hudi.storage.hadoop.HoodieHadoopStorage; + +import org.apache.iceberg.Table; + +import scala.Tuple2; + +import com.google.common.base.Preconditions; + +import org.apache.xtable.catalog.TableFormatUtils; +import org.apache.xtable.conversion.ConversionConfig; +import org.apache.xtable.conversion.ConversionController; +import org.apache.xtable.conversion.SourceTable; +import org.apache.xtable.conversion.TargetTable; +import org.apache.xtable.hudi.HudiTargetConfig; +import org.apache.xtable.iceberg.IcebergConversionSourceProvider; +import org.apache.xtable.model.storage.TableFormat; +import org.apache.xtable.model.sync.SyncResult; +import org.apache.xtable.model.sync.SyncStatusCode; + +/** + * Secondary index for an Iceberg table backed by the Hudi metadata table. The index is built by + * syncing the Iceberg table to Hudi with the record index and a secondary index enabled; the Hudi + * metadata lives under {@code <data location>/.hoodie/metadata}. Because the Iceberg data files + * carry no Hudi record keys, the record key of a row is {@code <file path relative to the data + * location>_<row position>}, which a lookup resolves back to a file path and row position. + */ +@Log4j2 +public class HudiBackedIcebergSecondaryIndex implements Index<Table> { + private final String tableLocation; + private final String dataPath; + private final SourceTable sourceTable; + private final Properties targetTableProperties; + private final List<String> indexedColumns; + private final SparkSession sparkSession; + private final JavaSparkContext javaSparkContext; + private final HoodieSparkEngineContext engineContext; + + /** + * @param icebergTable the table to index + * @param sourceTable how XTable loads the table for a sync, because a loaded table does not + * expose the catalog it came from. A table of a catalog sets its catalog config, name and + * namespace, and a table without a catalog config is loaded from its location + * @param sparkSession the Spark session used to build and query the index + * @param targetTableProperties {@link HudiTargetConfig} properties for the sync. {@link + * HudiTargetConfig#SECONDARY_INDEX_COLUMNS} lists the columns to index, and other properties + * such as the record index file group counts are optional + */ + public HudiBackedIcebergSecondaryIndex( + Table icebergTable, + SourceTable sourceTable, + SparkSession sparkSession, + Properties targetTableProperties) { + Preconditions.checkArgument( + TableFormat.ICEBERG.equals(sourceTable.getFormatName()), + "Expected an Iceberg source table but got format %s", + sourceTable.getFormatName()); + this.tableLocation = icebergTable.location(); + this.dataPath = + TableFormatUtils.getTableDataLocation( + TableFormat.ICEBERG, tableLocation, icebergTable.properties()); + // the Hudi table lives under the data location, which Iceberg resolves from the table + // properties + this.sourceTable = sourceTable.toBuilder().dataPath(dataPath).build(); + this.targetTableProperties = new Properties(); + this.targetTableProperties.putAll(targetTableProperties); + this.targetTableProperties.setProperty( + HudiTargetConfig.EXECUTION_ENGINE, HudiTargetConfig.EXECUTION_ENGINE_SPARK); + // the secondary index is only available from Hudi table version 8 onwards + this.targetTableProperties.setProperty( + HudiTargetConfig.HUDI_TABLE_VERSION, String.valueOf(HoodieTableVersion.NINE.versionCode())); + this.indexedColumns = + HudiTargetConfig.fromProperties(this.targetTableProperties).getSecondaryIndexColumns(); + Preconditions.checkArgument( + !indexedColumns.isEmpty(), + "Set %s to the columns to index", + HudiTargetConfig.SECONDARY_INDEX_COLUMNS); + this.sparkSession = sparkSession; + this.javaSparkContext = JavaSparkContext.fromSparkContext(sparkSession.sparkContext()); + this.engineContext = new HoodieSparkEngineContext(javaSparkContext); + } + + @Override + public boolean doesIndexExist(String columnName) { + return getCompletedIndexPartitions() + .contains(PARTITION_NAME_SECONDARY_INDEX_PREFIX + columnName); + } + + @Override + public void syncIndex(Table icebergTable) { + Configuration configuration = javaSparkContext.hadoopConfiguration(); + IcebergConversionSourceProvider sourceProvider = new IcebergConversionSourceProvider(); + sourceProvider.init(configuration); + // The sync reports a failed target in its result instead of throwing. It returns no result + // for the target when the table has no new commits. + SyncResult syncResult = + new ConversionController(configuration) + .sync(getConversionConfig(icebergTable), sourceProvider) + .get(TableFormat.HUDI); + if (syncResult != null + && (syncResult.getTableFormatSyncStatus() == null + || syncResult.getTableFormatSyncStatus().getStatusCode() != SyncStatusCode.SUCCESS)) { + throw new IllegalStateException( + "Failed to sync the secondary indexes of columns " + + indexedColumns + + " of table " + + tableLocation + + ": " + + syncResult.getTableFormatSyncStatus()); + } + Set<String> completedPartitions = getCompletedIndexPartitions(); + List<String> notIndexed = + indexedColumns.stream() + .filter( + column -> + !completedPartitions.contains(PARTITION_NAME_SECONDARY_INDEX_PREFIX + column)) + .collect(Collectors.toList()); + if (!notIndexed.isEmpty()) { + throw new IllegalStateException( + "The secondary indexes of columns " + + notIndexed + + " of table " + + tableLocation + + " do not exist. The indexes are built when the index is created, and adding a" + + " column to an existing index is not supported yet."); + } + log.info( + "Synced the secondary indexes of columns {} of table {}", indexedColumns, tableLocation); + } + + /** + * Returns the metadata table partitions whose build has completed. A partition directory can + * exist while the build is in flight or after it failed, so the directory alone does not show + * that the index is usable. + */ + private Set<String> getCompletedIndexPartitions() { + try { + return getMetaClient().getTableConfig().getMetadataPartitions(); + } catch (TableNotFoundException e) { + return Collections.emptySet(); + } + } + + private HoodieTableMetaClient getMetaClient() { + HoodieStorage storage = + new HoodieHadoopStorage(dataPath, javaSparkContext.hadoopConfiguration()); + return HoodieTableMetaClient.builder().setStorage(storage).setBasePath(dataPath).build(); + } + + private ConversionConfig getConversionConfig(Table icebergTable) { + TargetTable targetTable = + TargetTable.builder() + .name(icebergTable.name()) + .basePath(dataPath) + .formatName(TableFormat.HUDI) + .additionalProperties(targetTableProperties) + .build(); + return ConversionConfig.builder() + .sourceTable(sourceTable) + .targetTables(Collections.singletonList(targetTable)) + .build(); + } + + @Override + public Dataset<Row> lookup(Table icebergTable, Dataset<Row> keys, String columnName) { + Preconditions.checkArgument( + indexedColumns.contains(columnName), + "Column %s is not one of the indexed columns %s", + columnName, + indexedColumns); + StructType resultSchema = Review Comment: Can resultSchema be defined in the end? ########## xtable-core/src/main/java/org/apache/xtable/hudi/HudiConversionTarget.java: ########## @@ -482,6 +501,36 @@ private Optional<TableSyncMetadata> getMetadata( } } + /** + * Registers a definition for every secondary index partition that has none. Hudi updates every + * secondary index on each commit through its definition, but the commit that creates the metadata + * table rewrites the column-stats index definition from a stale view of the definitions, which + * drops the secondary index definition registered in the same commit. + */ + static void restoreSecondaryIndexDefinitions(HoodieTableMetaClient metaClient) { Review Comment: Is this required to bootstrap indexes for tables where new secondary index columns have been added? ########## xtable-core/src/main/java/org/apache/xtable/index/HudiBackedIcebergSecondaryIndex.java: ########## @@ -0,0 +1,299 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xtable.index; + +import static org.apache.hudi.metadata.HoodieTableMetadataUtil.PARTITION_NAME_SECONDARY_INDEX_PREFIX; +import static org.apache.spark.sql.functions.col; + +import java.util.Collections; +import java.util.List; +import java.util.Properties; +import java.util.Set; +import java.util.stream.Collectors; + +import lombok.extern.log4j.Log4j2; + +import org.apache.hadoop.conf.Configuration; +import org.apache.spark.api.java.JavaPairRDD; +import org.apache.spark.api.java.JavaRDD; +import org.apache.spark.api.java.JavaSparkContext; +import org.apache.spark.sql.Dataset; +import org.apache.spark.sql.Encoders; +import org.apache.spark.sql.Row; +import org.apache.spark.sql.RowFactory; +import org.apache.spark.sql.SparkSession; +import org.apache.spark.sql.types.DataTypes; +import org.apache.spark.sql.types.StructType; + +import org.apache.hudi.client.common.HoodieSparkEngineContext; +import org.apache.hudi.common.config.HoodieMetadataConfig; +import org.apache.hudi.common.data.HoodiePairData; +import org.apache.hudi.common.table.HoodieTableMetaClient; +import org.apache.hudi.common.table.HoodieTableVersion; +import org.apache.hudi.data.HoodieJavaPairRDD; +import org.apache.hudi.data.HoodieJavaRDD; +import org.apache.hudi.exception.TableNotFoundException; +import org.apache.hudi.metadata.HoodieBackedTableMetadata; +import org.apache.hudi.storage.HoodieStorage; +import org.apache.hudi.storage.hadoop.HoodieHadoopStorage; + +import org.apache.iceberg.Table; + +import scala.Tuple2; + +import com.google.common.base.Preconditions; + +import org.apache.xtable.catalog.TableFormatUtils; +import org.apache.xtable.conversion.ConversionConfig; +import org.apache.xtable.conversion.ConversionController; +import org.apache.xtable.conversion.SourceTable; +import org.apache.xtable.conversion.TargetTable; +import org.apache.xtable.hudi.HudiTargetConfig; +import org.apache.xtable.iceberg.IcebergConversionSourceProvider; +import org.apache.xtable.model.storage.TableFormat; +import org.apache.xtable.model.sync.SyncResult; +import org.apache.xtable.model.sync.SyncStatusCode; + +/** + * Secondary index for an Iceberg table backed by the Hudi metadata table. The index is built by + * syncing the Iceberg table to Hudi with the record index and a secondary index enabled; the Hudi + * metadata lives under {@code <data location>/.hoodie/metadata}. Because the Iceberg data files + * carry no Hudi record keys, the record key of a row is {@code <file path relative to the data + * location>_<row position>}, which a lookup resolves back to a file path and row position. + */ +@Log4j2 +public class HudiBackedIcebergSecondaryIndex implements Index<Table> { + private final String tableLocation; + private final String dataPath; + private final SourceTable sourceTable; + private final Properties targetTableProperties; + private final List<String> indexedColumns; + private final SparkSession sparkSession; + private final JavaSparkContext javaSparkContext; + private final HoodieSparkEngineContext engineContext; + + /** + * @param icebergTable the table to index + * @param sourceTable how XTable loads the table for a sync, because a loaded table does not + * expose the catalog it came from. A table of a catalog sets its catalog config, name and + * namespace, and a table without a catalog config is loaded from its location + * @param sparkSession the Spark session used to build and query the index + * @param targetTableProperties {@link HudiTargetConfig} properties for the sync. {@link + * HudiTargetConfig#SECONDARY_INDEX_COLUMNS} lists the columns to index, and other properties + * such as the record index file group counts are optional + */ + public HudiBackedIcebergSecondaryIndex( + Table icebergTable, + SourceTable sourceTable, + SparkSession sparkSession, + Properties targetTableProperties) { + Preconditions.checkArgument( + TableFormat.ICEBERG.equals(sourceTable.getFormatName()), + "Expected an Iceberg source table but got format %s", + sourceTable.getFormatName()); + this.tableLocation = icebergTable.location(); + this.dataPath = + TableFormatUtils.getTableDataLocation( + TableFormat.ICEBERG, tableLocation, icebergTable.properties()); + // the Hudi table lives under the data location, which Iceberg resolves from the table + // properties + this.sourceTable = sourceTable.toBuilder().dataPath(dataPath).build(); + this.targetTableProperties = new Properties(); + this.targetTableProperties.putAll(targetTableProperties); + this.targetTableProperties.setProperty( + HudiTargetConfig.EXECUTION_ENGINE, HudiTargetConfig.EXECUTION_ENGINE_SPARK); + // the secondary index is only available from Hudi table version 8 onwards + this.targetTableProperties.setProperty( + HudiTargetConfig.HUDI_TABLE_VERSION, String.valueOf(HoodieTableVersion.NINE.versionCode())); + this.indexedColumns = + HudiTargetConfig.fromProperties(this.targetTableProperties).getSecondaryIndexColumns(); + Preconditions.checkArgument( + !indexedColumns.isEmpty(), + "Set %s to the columns to index", + HudiTargetConfig.SECONDARY_INDEX_COLUMNS); + this.sparkSession = sparkSession; + this.javaSparkContext = JavaSparkContext.fromSparkContext(sparkSession.sparkContext()); + this.engineContext = new HoodieSparkEngineContext(javaSparkContext); + } + + @Override + public boolean doesIndexExist(String columnName) { + return getCompletedIndexPartitions() + .contains(PARTITION_NAME_SECONDARY_INDEX_PREFIX + columnName); + } + + @Override + public void syncIndex(Table icebergTable) { + Configuration configuration = javaSparkContext.hadoopConfiguration(); + IcebergConversionSourceProvider sourceProvider = new IcebergConversionSourceProvider(); + sourceProvider.init(configuration); + // The sync reports a failed target in its result instead of throwing. It returns no result + // for the target when the table has no new commits. + SyncResult syncResult = + new ConversionController(configuration) + .sync(getConversionConfig(icebergTable), sourceProvider) + .get(TableFormat.HUDI); + if (syncResult != null + && (syncResult.getTableFormatSyncStatus() == null + || syncResult.getTableFormatSyncStatus().getStatusCode() != SyncStatusCode.SUCCESS)) { + throw new IllegalStateException( + "Failed to sync the secondary indexes of columns " + + indexedColumns + + " of table " + + tableLocation + + ": " + + syncResult.getTableFormatSyncStatus()); + } + Set<String> completedPartitions = getCompletedIndexPartitions(); + List<String> notIndexed = + indexedColumns.stream() + .filter( + column -> + !completedPartitions.contains(PARTITION_NAME_SECONDARY_INDEX_PREFIX + column)) + .collect(Collectors.toList()); + if (!notIndexed.isEmpty()) { + throw new IllegalStateException( + "The secondary indexes of columns " + + notIndexed + + " of table " + + tableLocation + + " do not exist. The indexes are built when the index is created, and adding a" + + " column to an existing index is not supported yet."); + } + log.info( + "Synced the secondary indexes of columns {} of table {}", indexedColumns, tableLocation); + } + + /** + * Returns the metadata table partitions whose build has completed. A partition directory can + * exist while the build is in flight or after it failed, so the directory alone does not show + * that the index is usable. + */ + private Set<String> getCompletedIndexPartitions() { + try { + return getMetaClient().getTableConfig().getMetadataPartitions(); + } catch (TableNotFoundException e) { + return Collections.emptySet(); + } + } + + private HoodieTableMetaClient getMetaClient() { + HoodieStorage storage = + new HoodieHadoopStorage(dataPath, javaSparkContext.hadoopConfiguration()); + return HoodieTableMetaClient.builder().setStorage(storage).setBasePath(dataPath).build(); + } + + private ConversionConfig getConversionConfig(Table icebergTable) { + TargetTable targetTable = + TargetTable.builder() + .name(icebergTable.name()) + .basePath(dataPath) + .formatName(TableFormat.HUDI) + .additionalProperties(targetTableProperties) + .build(); + return ConversionConfig.builder() + .sourceTable(sourceTable) + .targetTables(Collections.singletonList(targetTable)) + .build(); + } + + @Override + public Dataset<Row> lookup(Table icebergTable, Dataset<Row> keys, String columnName) { + Preconditions.checkArgument( + indexedColumns.contains(columnName), + "Column %s is not one of the indexed columns %s", + columnName, + indexedColumns); + StructType resultSchema = + new StructType() + .add(columnName, DataTypes.StringType, false) + .add(FILE_COLUMN, DataTypes.StringType, false) + .add(POSITION_COLUMN, DataTypes.LongType, false); + // the secondary index stores the values of the indexed column as strings + JavaRDD<String> secondaryKeys = + keys.where(col(columnName).isNotNull()) + .select(col(columnName).cast(DataTypes.StringType)) + .as(Encoders.STRING()) + .toJavaRDD(); + HoodieTableMetaClient metaClient = getMetaClient(); + HoodieStorage storage = metaClient.getStorage(); + if (!metaClient + .getTableConfig() + .getMetadataPartitions() + .contains(PARTITION_NAME_SECONDARY_INDEX_PREFIX + columnName)) { + throw new IllegalStateException( + "The secondary index of column " + + columnName + + " of table " + + tableLocation + + " is not built"); + } + HoodieMetadataConfig metadataConfig = Review Comment: Is there any way we can get this from metaClient itself instead of assuming and initializing like this? ########## xtable-core/src/main/java/org/apache/xtable/iceberg/IcebergPartitionValueConverter.java: ########## @@ -181,6 +182,28 @@ private InternalPartitionField getFromInternalPartitionFieldMap( Collectors.toMap(InternalPartitionField::getTransformType, Function.identity()))); } + /** + * Resolves the position of a partition field in the partition struct by name. The struct is Review Comment: Can this be simplified to iceberg' spark reader returns PartitionData instead of IndexedRecord? Is there an existing iceberg function that can be used here instead? ########## xtable-core/src/main/java/org/apache/xtable/index/HudiBackedIcebergSecondaryIndex.java: ########## @@ -0,0 +1,299 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.xtable.index; + +import static org.apache.hudi.metadata.HoodieTableMetadataUtil.PARTITION_NAME_SECONDARY_INDEX_PREFIX; +import static org.apache.spark.sql.functions.col; + +import java.util.Collections; +import java.util.List; +import java.util.Properties; +import java.util.Set; +import java.util.stream.Collectors; + +import lombok.extern.log4j.Log4j2; + +import org.apache.hadoop.conf.Configuration; +import org.apache.spark.api.java.JavaPairRDD; +import org.apache.spark.api.java.JavaRDD; +import org.apache.spark.api.java.JavaSparkContext; +import org.apache.spark.sql.Dataset; +import org.apache.spark.sql.Encoders; +import org.apache.spark.sql.Row; +import org.apache.spark.sql.RowFactory; +import org.apache.spark.sql.SparkSession; +import org.apache.spark.sql.types.DataTypes; +import org.apache.spark.sql.types.StructType; + +import org.apache.hudi.client.common.HoodieSparkEngineContext; +import org.apache.hudi.common.config.HoodieMetadataConfig; +import org.apache.hudi.common.data.HoodiePairData; +import org.apache.hudi.common.table.HoodieTableMetaClient; +import org.apache.hudi.common.table.HoodieTableVersion; +import org.apache.hudi.data.HoodieJavaPairRDD; +import org.apache.hudi.data.HoodieJavaRDD; +import org.apache.hudi.exception.TableNotFoundException; +import org.apache.hudi.metadata.HoodieBackedTableMetadata; +import org.apache.hudi.storage.HoodieStorage; +import org.apache.hudi.storage.hadoop.HoodieHadoopStorage; + +import org.apache.iceberg.Table; + +import scala.Tuple2; + +import com.google.common.base.Preconditions; + +import org.apache.xtable.catalog.TableFormatUtils; +import org.apache.xtable.conversion.ConversionConfig; +import org.apache.xtable.conversion.ConversionController; +import org.apache.xtable.conversion.SourceTable; +import org.apache.xtable.conversion.TargetTable; +import org.apache.xtable.hudi.HudiTargetConfig; +import org.apache.xtable.iceberg.IcebergConversionSourceProvider; +import org.apache.xtable.model.storage.TableFormat; +import org.apache.xtable.model.sync.SyncResult; +import org.apache.xtable.model.sync.SyncStatusCode; + +/** + * Secondary index for an Iceberg table backed by the Hudi metadata table. The index is built by + * syncing the Iceberg table to Hudi with the record index and a secondary index enabled; the Hudi + * metadata lives under {@code <data location>/.hoodie/metadata}. Because the Iceberg data files + * carry no Hudi record keys, the record key of a row is {@code <file path relative to the data + * location>_<row position>}, which a lookup resolves back to a file path and row position. + */ +@Log4j2 +public class HudiBackedIcebergSecondaryIndex implements Index<Table> { + private final String tableLocation; + private final String dataPath; + private final SourceTable sourceTable; + private final Properties targetTableProperties; + private final List<String> indexedColumns; + private final SparkSession sparkSession; + private final JavaSparkContext javaSparkContext; + private final HoodieSparkEngineContext engineContext; + + /** + * @param icebergTable the table to index + * @param sourceTable how XTable loads the table for a sync, because a loaded table does not + * expose the catalog it came from. A table of a catalog sets its catalog config, name and + * namespace, and a table without a catalog config is loaded from its location + * @param sparkSession the Spark session used to build and query the index + * @param targetTableProperties {@link HudiTargetConfig} properties for the sync. {@link + * HudiTargetConfig#SECONDARY_INDEX_COLUMNS} lists the columns to index, and other properties + * such as the record index file group counts are optional + */ + public HudiBackedIcebergSecondaryIndex( + Table icebergTable, + SourceTable sourceTable, + SparkSession sparkSession, + Properties targetTableProperties) { + Preconditions.checkArgument( + TableFormat.ICEBERG.equals(sourceTable.getFormatName()), + "Expected an Iceberg source table but got format %s", + sourceTable.getFormatName()); + this.tableLocation = icebergTable.location(); + this.dataPath = + TableFormatUtils.getTableDataLocation( + TableFormat.ICEBERG, tableLocation, icebergTable.properties()); + // the Hudi table lives under the data location, which Iceberg resolves from the table + // properties + this.sourceTable = sourceTable.toBuilder().dataPath(dataPath).build(); + this.targetTableProperties = new Properties(); + this.targetTableProperties.putAll(targetTableProperties); + this.targetTableProperties.setProperty( + HudiTargetConfig.EXECUTION_ENGINE, HudiTargetConfig.EXECUTION_ENGINE_SPARK); + // the secondary index is only available from Hudi table version 8 onwards + this.targetTableProperties.setProperty( + HudiTargetConfig.HUDI_TABLE_VERSION, String.valueOf(HoodieTableVersion.NINE.versionCode())); + this.indexedColumns = + HudiTargetConfig.fromProperties(this.targetTableProperties).getSecondaryIndexColumns(); + Preconditions.checkArgument( + !indexedColumns.isEmpty(), + "Set %s to the columns to index", + HudiTargetConfig.SECONDARY_INDEX_COLUMNS); + this.sparkSession = sparkSession; + this.javaSparkContext = JavaSparkContext.fromSparkContext(sparkSession.sparkContext()); + this.engineContext = new HoodieSparkEngineContext(javaSparkContext); + } + + @Override + public boolean doesIndexExist(String columnName) { + return getCompletedIndexPartitions() + .contains(PARTITION_NAME_SECONDARY_INDEX_PREFIX + columnName); + } + + @Override + public void syncIndex(Table icebergTable) { + Configuration configuration = javaSparkContext.hadoopConfiguration(); + IcebergConversionSourceProvider sourceProvider = new IcebergConversionSourceProvider(); + sourceProvider.init(configuration); + // The sync reports a failed target in its result instead of throwing. It returns no result + // for the target when the table has no new commits. + SyncResult syncResult = + new ConversionController(configuration) + .sync(getConversionConfig(icebergTable), sourceProvider) + .get(TableFormat.HUDI); + if (syncResult != null + && (syncResult.getTableFormatSyncStatus() == null + || syncResult.getTableFormatSyncStatus().getStatusCode() != SyncStatusCode.SUCCESS)) { + throw new IllegalStateException( + "Failed to sync the secondary indexes of columns " + + indexedColumns + + " of table " + + tableLocation + + ": " + + syncResult.getTableFormatSyncStatus()); + } + Set<String> completedPartitions = getCompletedIndexPartitions(); + List<String> notIndexed = + indexedColumns.stream() + .filter( + column -> + !completedPartitions.contains(PARTITION_NAME_SECONDARY_INDEX_PREFIX + column)) + .collect(Collectors.toList()); + if (!notIndexed.isEmpty()) { + throw new IllegalStateException( + "The secondary indexes of columns " + + notIndexed + + " of table " + + tableLocation + + " do not exist. The indexes are built when the index is created, and adding a" + + " column to an existing index is not supported yet."); + } Review Comment: Isn't secondary index commit part of the hudi transaction and this kind of check is not required? -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
