vinothchandar commented on a change in pull request #1402: [WIP][HUDI-407] 
Adding Simple Index
URL: https://github.com/apache/incubator-hudi/pull/1402#discussion_r405076523
 
 

 ##########
 File path: 
hudi-client/src/main/java/org/apache/hudi/index/bloom/HoodieSimpleIndex.java
 ##########
 @@ -0,0 +1,263 @@
+/*
+ * 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.index.bloom;
+
+import org.apache.hudi.WriteStatus;
+import org.apache.hudi.common.model.HoodieDataFile;
+import org.apache.hudi.common.model.HoodieKey;
+import org.apache.hudi.common.model.HoodieRecord;
+import org.apache.hudi.common.model.HoodieRecordLocation;
+import org.apache.hudi.common.model.HoodieRecordPayload;
+import org.apache.hudi.common.table.timeline.HoodieInstant;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.common.util.ParquetUtils;
+import org.apache.hudi.common.util.collection.Pair;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.table.HoodieTable;
+
+import com.google.common.annotations.VisibleForTesting;
+import org.apache.hadoop.fs.Path;
+import org.apache.log4j.LogManager;
+import org.apache.log4j.Logger;
+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.api.java.Optional;
+import org.apache.spark.api.java.function.PairFunction;
+import org.apache.spark.storage.StorageLevel;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import scala.Tuple2;
+
+import static java.util.stream.Collectors.toList;
+
+/**
+ * A simple index which reads interested fields from parquet and joins with 
incoming records to find the tagged location
+ *
+ * @param <T>
+ */
+public class HoodieSimpleIndex<T extends HoodieRecordPayload> extends 
HoodieBloomIndex<T> {
+
+  private static final Logger LOG = 
LogManager.getLogger(HoodieSimpleIndex.class);
+
+  public HoodieSimpleIndex(HoodieWriteConfig config) {
+    super(config);
+  }
+
+  /**
+   * Returns an RDD mapping each HoodieKey with a partitionPath/fileID which 
contains it. Option.Empty if the key is not
+   * found.
+   *
+   * @param hoodieKeys  keys to lookup
+   * @param jsc         spark context
+   * @param hoodieTable hoodie table object
+   */
+  @Override
+  public JavaPairRDD<HoodieKey, Option<Pair<String, String>>> 
fetchRecordLocation(JavaRDD<HoodieKey> hoodieKeys,
+                                                                               
   JavaSparkContext jsc, HoodieTable<T> hoodieTable) {
+    JavaPairRDD<String, String> partitionRecordKeyPairRDD =
+        hoodieKeys.mapToPair(key -> new Tuple2<>(key.getPartitionPath(), 
key.getRecordKey()));
+
+    // Lookup indexes for all the partition/recordkey pair
+    JavaPairRDD<HoodieKey, HoodieRecordLocation> recordKeyLocationRDD =
+        lookupIndex(partitionRecordKeyPairRDD, jsc, hoodieTable);
+
+    JavaPairRDD<HoodieKey, String> keyHoodieKeyPairRDD = 
hoodieKeys.mapToPair(key -> new Tuple2<>(key, null));
+
+    return 
keyHoodieKeyPairRDD.leftOuterJoin(recordKeyLocationRDD).mapToPair(keyLoc -> {
+      Option<Pair<String, String>> partitionPathFileidPair;
+      if (keyLoc._2._2.isPresent()) {
+        partitionPathFileidPair = 
Option.of(Pair.of(keyLoc._1().getPartitionPath(), 
keyLoc._2._2.get().getFileId()));
+      } else {
+        partitionPathFileidPair = Option.empty();
+      }
+      return new Tuple2<>(keyLoc._1, partitionPathFileidPair);
+    });
+  }
+
+  @Override
+  public JavaRDD<HoodieRecord<T>> tagLocation(JavaRDD<HoodieRecord<T>> 
recordRDD, JavaSparkContext jsc,
+                                              HoodieTable<T> hoodieTable) {
+
+    // Step 0: cache the input record RDD
+    if (config.getBloomIndexUseCaching()) {
+      recordRDD.persist(config.getBloomIndexInputStorageLevel());
+    }
+
+    // Step 1: Extract out thinner JavaPairRDD of (partitionPath, recordKey)
+    JavaPairRDD<String, String> partitionRecordKeyPairRDD =
+        recordRDD.mapToPair(record -> new Tuple2<>(record.getPartitionPath(), 
record.getRecordKey()));
+
+    // Lookup indexes for all the partition/recordkey pair
+    JavaPairRDD<HoodieKey, HoodieRecordLocation> keyFilenamePairRDD =
+        lookupIndex(partitionRecordKeyPairRDD, jsc, hoodieTable);
+
+    // Cache the result, for subsequent stages.
+    if (config.getBloomIndexUseCaching()) {
+      keyFilenamePairRDD.persist(StorageLevel.MEMORY_AND_DISK_SER());
+    }
+    if (LOG.isDebugEnabled()) {
+      long totalTaggedRecords = keyFilenamePairRDD.count();
+      LOG.debug("Number of update records (ones tagged with a fileID): " + 
totalTaggedRecords);
+    }
+
+    // Step 4: Tag the incoming records, as inserts or updates, by joining 
with existing record keys
+    JavaRDD<HoodieRecord<T>> taggedRecordRDD = 
tagLocationBacktoRecords(keyFilenamePairRDD, recordRDD);
+
+    if (config.getBloomIndexUseCaching()) {
+      recordRDD.unpersist(); // unpersist the input Record RDD
+      keyFilenamePairRDD.unpersist();
+    }
+    return taggedRecordRDD;
+  }
+
+  @Override
+  public JavaRDD<WriteStatus> updateLocation(JavaRDD<WriteStatus> 
writeStatusRDD, JavaSparkContext jsc,
+                                             HoodieTable<T> hoodieTable) {
+    return writeStatusRDD;
+  }
+
+  @Override
+  public boolean rollbackCommit(String commitTime) {
+    // Nope, don't need to do anything.
+    return true;
+  }
+
+  /**
+   * This is not global, since we depend on the partitionPath to do the lookup.
+   */
+  @Override
+  public boolean isGlobal() {
+    return false;
+  }
+
+  /**
+   * No indexes into log files yet.
+   */
+  @Override
+  public boolean canIndexLogFiles() {
+    return false;
+  }
+
+  /**
+   * Bloom filters are stored, into the same data files.
+   */
+  @Override
+  public boolean isImplicitWithStorage() {
+    return true;
+  }
+
+  /**
+   * Lookup the location for each record key and return the 
pair<record_key,location> for all record keys already
+   * present and drop the record keys if not present.
+   */
+  private JavaPairRDD<HoodieKey, HoodieRecordLocation> lookupIndex(
+      JavaPairRDD<String, String> partitionRecordKeyPairRDD, final 
JavaSparkContext jsc,
+      final HoodieTable hoodieTable) {
+    // Obtain records per partition, in the incoming records
+    Map<String, Long> recordsPerPartition = 
partitionRecordKeyPairRDD.countByKey();
+    List<String> affectedPartitionPathList = new 
ArrayList<>(recordsPerPartition.keySet());
+
+    // Step 2: Load all involved files as <Partition, filename> pairs
+    List<Tuple2<String, String>> fileInfoList =
+        loadInvolvedFileIds(affectedPartitionPathList, jsc, hoodieTable);
+
+    return findMatchingFilesForRecordKeys(jsc, fileInfoList, 
partitionRecordKeyPairRDD, hoodieTable);
+  }
+
+  /**
+   * Load all involved files as <Partition, filename> pair RDD.
+   */
+  @VisibleForTesting
+  List<Tuple2<String, String>> loadInvolvedFileIds(List<String> partitions, 
final JavaSparkContext jsc,
+                                                   final HoodieTable 
hoodieTable) {
+
+    // Obtain the latest data files from all the partitions.
+    List<Pair<String, String>> partitionPathFileIDList =
+        jsc.parallelize(partitions, Math.max(partitions.size(), 
1)).flatMap(partitionPath -> {
+          Option<HoodieInstant> latestCommitTime =
+              
hoodieTable.getMetaClient().getCommitsTimeline().filterCompletedInstants().lastInstant();
+          List<Pair<String, String>> filteredFiles = new ArrayList<>();
+          if (latestCommitTime.isPresent()) {
+            filteredFiles = hoodieTable.getROFileSystemView()
+                .getLatestDataFilesBeforeOrOn(partitionPath, 
latestCommitTime.get().getTimestamp())
+                .map(f -> Pair.of(partitionPath, 
f.getFileId())).collect(toList());
+          }
+          return filteredFiles.iterator();
+        }).collect();
+    return partitionPathFileIDList.stream()
+        .map(pf -> new Tuple2<>(pf.getKey(), pf.getValue())).collect(toList());
+  }
+
+  /**
+   * Find <HoodieKey, HoodieRecordLocation> for all incoming HoodieKeys
+   */
+  private JavaPairRDD<HoodieKey, HoodieRecordLocation> 
findMatchingFilesForRecordKeys(JavaSparkContext jsc,
+                                                                               
       List<Tuple2<String, String>> partitionToFileIndexInfo,
+                                                                               
       JavaPairRDD<String, String> partitionRecordKeyPairRDD, HoodieTable 
hoodieTable) {
+    // Step 1: Create JavaPairRDD< Tuple2<PartitionPath, RecordKey>, 
Optional<HoodieRecordLocation> > from input with  
Optional<HoodieRecordLocation> as Empty.
+    JavaPairRDD<Tuple2<String, String>, Optional<HoodieRecordLocation>> 
partitionRecordPairs =
+        partitionRecordKeyPairRDD.mapToPair((PairFunction<Tuple2<String, 
String>, Tuple2<String, String>, Optional<HoodieRecordLocation>>) 
stringStringTuple2
+            -> new Tuple2(stringStringTuple2, Optional.absent()));
+
+    // Step 2: Create JavaRDD< Tuple2 <Partition, FileId> > from partitions to 
be touched
+    JavaRDD<Tuple2<String, String>> partitionFileIdTupleRDD = 
jsc.parallelize(partitionToFileIndexInfo);
+
+    // Step 3: For each partiion, fileId Tuple -> Fetch RDD of triplets ( 
Tuple2 <PartitionPath, recordKey>, HoodieRecordLocation )
+    JavaRDD<Tuple2<Tuple2<String, String>, Option<HoodieRecordLocation>>> 
partitionFileIdLocationEntries = 
partitionFileIdTupleRDD.flatMap(partitionFileIdTuple -> {
+      HoodieDataFile latestDataFile = getLatestDataFile(hoodieTable, 
Pair.of(partitionFileIdTuple._1, partitionFileIdTuple._2));
+      List<Pair<Pair<String, String>, Option<HoodieRecordLocation>>> 
resultList = 
ParquetUtils.fetchRecordKeyPartitionPathFromParquet(hoodieTable.getHadoopConf(),
 new Path(latestDataFile.getPath()),
 
 Review comment:
   for now.. you can assume this... 

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services

Reply via email to