hudi-agent commented on code in PR #19006:
URL: https://github.com/apache/hudi/pull/19006#discussion_r3432625488


##########
hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/source/stats/RecordLevelIndex.java:
##########
@@ -22,262 +22,152 @@
 import org.apache.hudi.common.data.HoodieListData;
 import org.apache.hudi.common.data.HoodiePairData;
 import org.apache.hudi.common.model.FileSlice;
+import org.apache.hudi.common.model.HoodieFileGroupId;
 import org.apache.hudi.common.model.HoodieRecordGlobalLocation;
 import org.apache.hudi.common.table.HoodieTableMetaClient;
-import org.apache.hudi.common.util.HoodieDataUtils;
 import org.apache.hudi.common.util.Option;
-import org.apache.hudi.common.util.VisibleForTesting;
-import org.apache.hudi.common.util.collection.Pair;
-import org.apache.hudi.configuration.FlinkOptions;
-import org.apache.hudi.configuration.OptionsResolver;
-import org.apache.hudi.exception.HoodieException;
-import org.apache.hudi.keygen.KeyGenUtils;
-import org.apache.hudi.keygen.KeyGenerator;
+import org.apache.hudi.common.util.ValidationUtils;
 import org.apache.hudi.metadata.HoodieTableMetadata;
 import org.apache.hudi.metadata.HoodieTableMetadataUtil;
-import org.apache.hudi.sink.bulk.RowDataKeyGen;
-import org.apache.hudi.source.ExpressionEvaluators;
-import org.apache.hudi.util.StreamerUtil;
+import org.apache.hudi.metadata.MetadataPartitionType;
 
 import lombok.extern.slf4j.Slf4j;
 import org.apache.flink.configuration.Configuration;
-import org.apache.flink.table.data.TimestampData;
-import org.apache.flink.table.types.logical.DecimalType;
-import org.apache.flink.table.types.logical.LogicalType;
-import org.apache.flink.table.types.logical.RowType;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 
-import java.math.BigDecimal;
 import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
+import java.util.HashSet;
 import java.util.List;
-import java.util.Objects;
+import java.util.Map;
 import java.util.Set;
 import java.util.stream.Collectors;
 
 /**
- * An index support implementation that leverages Record Level Index to prune 
file slices.
+ * An index support implementation that leverages partitioned Record Level 
Index to prune file slices.
+ *
+ * <p>Unlike the global RLI, record keys in partitioned RLI are only unique 
within a data-table partition.
+ * This implementation therefore scopes metadata-table lookups by candidate 
data partition. To avoid reading
+ * every RLI shard for each candidate partition, it first groups 
filter-derived record keys by the shard they
+ * hash to within each partition, then performs one metadata lookup per {@code 
(partition, shard)} group.
+ *
+ * <p>The grouped lookups use bounded local parallelism through {@link 
HoodieFlinkEngineContext#map(List,
+ * org.apache.hudi.common.function.SerializableFunction, int)}. This is 
intentionally not implemented with
+ * {@code HoodieFlinkEngineContext#parallelize}, because the Flink context 
backs {@code parallelize} with
+ * in-memory {@code HoodieListData}, not distributed Flink tasks.
  */
 @Slf4j
-public class RecordLevelIndex implements FlinkMetadataIndex {
+public class RecordLevelIndex extends BaseRecordLevelIndex {

Review Comment:
   🤖 nit: with `BaseRecordLevelIndex` as the abstract parent and 
`GlobalRecordLevelIndex` as the sibling, leaving the partitioned variant named 
just `RecordLevelIndex` is asymmetric — a reader scanning `create()` would 
reasonably assume it's the default/global form. Could you rename this to 
`PartitionedRecordLevelIndex` to match `GlobalRecordLevelIndex`?
   
   <sub><i>- AI-generated; verify before applying. React 👍/👎 to flag 
quality.</i></sub>



##########
hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/source/stats/BaseRecordLevelIndex.java:
##########
@@ -0,0 +1,297 @@
+/*
+ * 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.hudi.source.stats;
+
+import org.apache.hudi.client.common.HoodieFlinkEngineContext;
+import org.apache.hudi.common.data.HoodiePairData;
+import org.apache.hudi.common.model.FileSlice;
+import org.apache.hudi.common.model.HoodieFileGroupId;
+import org.apache.hudi.common.model.HoodieIndexDefinition;
+import org.apache.hudi.common.model.HoodieRecordGlobalLocation;
+import org.apache.hudi.common.table.HoodieTableMetaClient;
+import org.apache.hudi.common.util.HoodieDataUtils;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.common.util.VisibleForTesting;
+import org.apache.hudi.common.util.collection.Pair;
+import org.apache.hudi.configuration.FlinkOptions;
+import org.apache.hudi.configuration.OptionsResolver;
+import org.apache.hudi.exception.HoodieException;
+import org.apache.hudi.index.record.HoodieRecordIndex;
+import org.apache.hudi.keygen.KeyGenUtils;
+import org.apache.hudi.keygen.KeyGenerator;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+import org.apache.hudi.metadata.HoodieTableMetadataUtil;
+import org.apache.hudi.sink.bulk.RowDataKeyGen;
+import org.apache.hudi.source.ExpressionEvaluators;
+import org.apache.hudi.util.StreamerUtil;
+
+import lombok.extern.slf4j.Slf4j;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.table.data.TimestampData;
+import org.apache.flink.table.types.logical.DecimalType;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.RowType;
+
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * Base index support that leverages Record Level Index to prune file slices.
+ */
+@Slf4j
+public abstract class BaseRecordLevelIndex implements FlinkMetadataIndex {
+  private static final long serialVersionUID = 1L;
+
+  private final String basePath;
+  protected final Configuration conf;
+  protected final List<String> hoodieKeysFromFilter;
+  private final HoodieTableMetaClient metaClient;
+  private HoodieTableMetadata metadataTable;
+
+  @VisibleForTesting
+  BaseRecordLevelIndex(
+      String basePath,
+      Configuration conf,
+      HoodieTableMetaClient metaClient,
+      List<String> hoodieKeysFromFilter) {
+    this.basePath = basePath;
+    this.conf = conf;
+    this.metaClient = metaClient;
+    this.hoodieKeysFromFilter = hoodieKeysFromFilter;
+  }
+
+  @Override
+  public String getIndexPartitionName() {
+    return HoodieTableMetadataUtil.PARTITION_NAME_RECORD_INDEX;
+  }
+
+  @Override
+  public boolean isIndexAvailable() {
+    return metaClient.getTableConfig().isMetadataTableAvailable()
+        && 
metaClient.getTableConfig().getMetadataPartitions().contains(HoodieTableMetadataUtil.PARTITION_NAME_RECORD_INDEX);
+  }
+
+  public HoodieTableMetadata getMetadataTable() {
+    // initialize the metadata table lazily
+    if (this.metadataTable == null) {
+      this.metadataTable = 
metaClient.getTableFormat().getMetadataFactory().create(
+          HoodieFlinkEngineContext.DEFAULT,
+          metaClient.getStorage(),
+          StreamerUtil.metadataConfig(conf),
+          basePath);
+    }
+    return this.metadataTable;
+  }
+
+  public List<FileSlice> computeCandidateFileSlices(List<FileSlice> 
fileSlices) {
+    if (!isIndexAvailable()) {
+      return fileSlices;
+    }
+
+    try {
+      Option<Set<HoodieFileGroupId>> candidateFileGroupIds =
+          lookupCandidateFileGroupIds(fileSlices);
+      return candidateFileGroupIds.map(candidates -> fileSlices.stream()
+          .filter(fileSlice -> candidates.contains(fileSlice.getFileGroupId()))
+          .collect(Collectors.toList()))
+          .orElse(fileSlices);
+    } catch (Throwable e) {
+      log.error("Failed to read metadata index: {} for data skipping", 
getIndexPartitionName(), e);
+      return fileSlices;
+    }
+  }
+
+  protected abstract Option<Set<HoodieFileGroupId>> 
lookupCandidateFileGroupIds(List<FileSlice> fileSlices);
+
+  protected static Set<HoodieFileGroupId> getFileGroupIds(
+      HoodiePairData<String, HoodieRecordGlobalLocation> recordIndexData) {
+    List<Pair<String, HoodieRecordGlobalLocation>> recordIndexLocations =
+        HoodieDataUtils.dedupeAndCollectAsList(recordIndexData);
+    return recordIndexLocations.stream()
+        .map(pair -> new HoodieFileGroupId(pair.getValue().getPartitionPath(), 
pair.getValue().getFileId()))
+        .collect(Collectors.toSet());
+  }
+
+  public static Option<BaseRecordLevelIndex> create(
+      String basePath,
+      Configuration conf,
+      HoodieTableMetaClient metaClient,
+      List<ExpressionEvaluators.Evaluator> evaluators,
+      RowType rowType) {
+    if (evaluators.isEmpty() || 
!FlinkOptions.QUERY_TYPE_SNAPSHOT.equalsIgnoreCase(conf.get(FlinkOptions.QUERY_TYPE)))
 {
+      return Option.empty();
+    }
+    if (metaClient == null) {
+      metaClient = StreamerUtil.createMetaClient(conf);
+    }
+    // disallow RLI for new encoding with complex key gen when the table 
version is lower than NINE.
+    if 
(KeyGenUtils.mayUseNewEncodingForComplexKeyGen(metaClient.getTableConfig())) {
+      return Option.empty();
+    }
+
+    String[] recordKeyFields = 
metaClient.getTableConfig().getRecordKeyFields().orElse(new String[0]);
+    if (recordKeyFields.length == 0) {
+      log.warn("The table do not have record keys, skipping the rli pruning.");
+      return Option.empty();
+    }
+    boolean consistentLogicalTimestampEnabled = 
OptionsResolver.isConsistentLogicalTimestampEnabled(conf);
+    List<String> hoodieKeysFromFilter = computeHoodieKeyFromFilters(conf, 
metaClient, evaluators, recordKeyFields, rowType, 
consistentLogicalTimestampEnabled);
+    if (hoodieKeysFromFilter.isEmpty()) {
+      log.warn("The number of keys from query predicate is empty, skipping the 
rli pruning.");
+      return Option.empty();
+    }
+    int maxKeyNum = conf.get(FlinkOptions.READ_DATA_SKIPPING_RLI_KEYS_MAX_NUM);
+    if (hoodieKeysFromFilter.size() > maxKeyNum) {
+      log.warn("The number of keys from query predicate: {} exceeds the upper 
threshold: {}, skipping the rli pruning, the keys: {}",
+          hoodieKeysFromFilter.size(), maxKeyNum, hoodieKeysFromFilter);
+      return Option.empty();
+    }
+    HoodieIndexDefinition indexDefinition = 
metaClient.getIndexForMetadataPartition(HoodieTableMetadataUtil.PARTITION_NAME_RECORD_INDEX).orElse(null);
+    if (indexDefinition == null) {
+      return Option.empty();
+    }
+    return Option.of(HoodieRecordIndex.isPartitioned(indexDefinition)
+        ? new RecordLevelIndex(basePath, conf, metaClient, 
hoodieKeysFromFilter)
+        : new GlobalRecordLevelIndex(basePath, conf, metaClient, 
hoodieKeysFromFilter));
+  }
+
+  /**
+   * Given query filters, it filters the EqualTo, IN and OR queries on record 
key columns and
+   * returns the list of record key literals present in the query, for example:
+   * <p>
+   * filter1: `key1` = 'val1', returns {"val1"}
+   * filter2: `key1` in ('val1', 'val2', 'val3'), returns {"val1", "vale", 
"val3"}

Review Comment:
   🤖 nit: typo carried over from the original — `"vale"` should be `"val2"` 
(appears on this line and the next).
   
   <sub><i>- AI-generated; verify before applying. React 👍/👎 to flag 
quality.</i></sub>



-- 
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]

Reply via email to