KnightChess commented on code in PR #10191:
URL: https://github.com/apache/hudi/pull/10191#discussion_r1407354272


##########
hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/BucketIndexSupport.scala:
##########
@@ -0,0 +1,164 @@
+/*
+ * 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
+
+import org.apache.hadoop.fs.FileStatus
+import org.apache.hudi.common.config.HoodieMetadataConfig
+import org.apache.hudi.common.fs.FSUtils
+import org.apache.hudi.common.table.HoodieTableConfig
+import org.apache.hudi.config.HoodieIndexConfig
+import org.apache.hudi.index.HoodieIndex
+import org.apache.hudi.index.HoodieIndex.IndexType
+import org.apache.hudi.index.bucket.BucketIdentifier
+import org.apache.log4j.LogManager
+import org.apache.spark.sql.catalyst.expressions
+import org.apache.spark.sql.catalyst.expressions.{And, Attribute, EmptyRow, 
Expression, Literal}
+import org.apache.spark.sql.types.{DoubleType, FloatType}
+import org.apache.spark.util.collection.BitSet
+
+import scala.collection.{JavaConverters, mutable}
+
+class BucketIndexSupport(metadataConfig: HoodieMetadataConfig) {
+
+  private val log = LogManager.getLogger(getClass);
+
+  /**
+   * Returns the configured bucket field for the table
+   */
+  private def getBucketHashField: Option[String] = {
+    val bucketHashFields = 
metadataConfig.getString(HoodieIndexConfig.BUCKET_INDEX_HASH_FIELD)
+    if (bucketHashFields == null) {
+      val recordKeys = 
metadataConfig.getString(HoodieTableConfig.RECORDKEY_FIELDS)
+      if (recordKeys == null) {
+        Option.apply(null)
+      } else {
+        val recordKeyArray = recordKeys.split(",")
+        if (recordKeyArray.length == 1) {
+          Option.apply(recordKeyArray(0))
+        } else {
+          log.warn("bucket query index only support one bucket field")
+          Option.apply(null)
+        }
+      }
+    } else {
+      val fields = bucketHashFields.split(",")
+      if (fields.length == 1) {
+        Option.apply(fields(0))
+      } else {
+        log.warn("bucket query index only support one bucket field")
+        Option.apply(null)
+      }
+    }
+  }
+
+  def getCandidateFiles(allFiles: Seq[FileStatus], bucketIds: BitSet): 
Set[String] = {
+    val candidateFiles: mutable.Set[String] = mutable.Set.empty
+    for (file <- allFiles) {
+      val fileId = FSUtils.getFileIdFromFilePath(file.getPath)
+      val fileBucketId = BucketIdentifier.bucketIdFromFileId(fileId)
+      if (bucketIds.get(fileBucketId)) {
+        candidateFiles += file.getPath.getName
+      }
+    }
+    candidateFiles.toSet
+  }
+
+  def filterQueriesWithBucketHashField(queryFilters: Seq[Expression]): 
Option[BitSet] = {
+    val bucketNumber = 
metadataConfig.getInt(HoodieIndexConfig.BUCKET_INDEX_NUM_BUCKETS)
+    val bucketHashFieldOpt = getBucketHashField
+    if (bucketHashFieldOpt.isEmpty || queryFilters.isEmpty) {
+      None
+    } else {
+      val matchedBuckets = getExpressionBuckets(queryFilters.reduce(And), 
bucketHashFieldOpt.get, bucketNumber)
+
+      val numBucketsSelected = matchedBuckets.cardinality()
+
+      // None means all the buckets need to be scanned
+      if (numBucketsSelected == bucketNumber) {
+        log.info("bucket query match all file slice, fallback other index")
+        None
+      } else {
+        Some(matchedBuckets)
+      }
+    }
+  }
+
+  private def getExpressionBuckets(expr: Expression, bucketColumnName: String, 
numBuckets: Int): BitSet = {
+
+    def getBucketNumber(attr: Attribute, v: Any): Int = {
+      
BucketIdentifier.getBucketId(JavaConverters.seqAsJavaListConverter(List.apply(String.valueOf(v))).asJava,
 numBuckets)
+    }
+
+    def getBucketSetFromIterable(attr: Attribute, iter: Iterable[Any]): BitSet 
= {
+      val matchedBuckets = new BitSet(numBuckets)
+      iter
+        .map(v => getBucketNumber(attr, v))
+        .foreach(bucketNum => matchedBuckets.set(bucketNum))
+      matchedBuckets
+    }
+
+    def getBucketSetFromValue(attr: Attribute, v: Any): BitSet = {
+      val matchedBuckets = new BitSet(numBuckets)
+      matchedBuckets.set(getBucketNumber(attr, v))
+      matchedBuckets
+    }
+
+    expr match {
+      case expressions.Equality(a: Attribute, Literal(v, _)) if a.name == 
bucketColumnName =>
+        getBucketSetFromValue(a, v)
+      case expressions.In(a: Attribute, list)
+        if list.forall(_.isInstanceOf[Literal]) && a.name == bucketColumnName 
=>
+        getBucketSetFromIterable(a, list.map(e => e.eval(EmptyRow)))
+      case expressions.InSet(a: Attribute, hset) if a.name == bucketColumnName 
=>
+        getBucketSetFromIterable(a, hset)
+      case expressions.IsNull(a: Attribute) if a.name == bucketColumnName =>
+        getBucketSetFromValue(a, null)
+      case expressions.IsNaN(a: Attribute)
+        if a.name == bucketColumnName && a.dataType == FloatType =>
+        getBucketSetFromValue(a, Float.NaN)
+      case expressions.IsNaN(a: Attribute)
+        if a.name == bucketColumnName && a.dataType == DoubleType =>
+        getBucketSetFromValue(a, Double.NaN)
+      case expressions.And(left, right) =>
+        getExpressionBuckets(left, bucketColumnName, numBuckets) &
+          getExpressionBuckets(right, bucketColumnName, numBuckets)
+      case expressions.Or(left, right) =>
+        getExpressionBuckets(left, bucketColumnName, numBuckets) |
+          getExpressionBuckets(right, bucketColumnName, numBuckets)
+      case _ =>
+        val matchedBuckets = new BitSet(numBuckets)
+        matchedBuckets.setUntil(numBuckets)
+        matchedBuckets
+    }
+  }
+
+  /**
+   * Return true if metadata table is enabled and record index metadata 
partition is available.
+   * table is bucket index writer, use default use bucket index try query
+   * - table may not set bucket field, it will use record key field, now only 
support simple key
+   * - only support simple bucket engine null
+   */
+  def isIndexAvailable: Boolean = {
+    getBucketHashField.isDefined &&
+      metadataConfig.getStringOrDefault(HoodieIndexConfig.INDEX_TYPE, 
"").equalsIgnoreCase(IndexType.BUCKET.name()) &&
+      
metadataConfig.getStringOrDefault(HoodieIndexConfig.BUCKET_INDEX_ENGINE_TYPE).equalsIgnoreCase(HoodieIndex.BucketIndexEngineType.SIMPLE.name())
 &&
+      metadataConfig.getBooleanOrDefault(HoodieIndexConfig.BUCKET_QUERY_INDEX) 
&&
+      metadataConfig.getInt(HoodieIndexConfig.BUCKET_INDEX_NUM_BUCKETS) != null

Review Comment:
   bucket number will not save in hudi meta on write, so will not use default 
number to avoid diff number be used. Now, if user want to use bucket query, 
need to set bucket number



-- 
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: commits-unsubscr...@hudi.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org

Reply via email to