taklwu commented on code in PR #162:
URL: https://github.com/apache/hbase-connectors/pull/162#discussion_r3900485791


##########
spark4/hbase-spark4/src/main/scala/org/apache/hadoop/hbase/spark/datasources/HBaseBatch.scala:
##########
@@ -0,0 +1,129 @@
+/*
+ * 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.hadoop.hbase.spark.datasources
+
+import org.apache.hadoop.fs.Path
+import org.apache.hadoop.hbase.{HBaseConfiguration, TableName}
+import org.apache.hadoop.hbase.spark.{HBaseConnectionCache, Logging}
+import org.apache.spark.sql.connector.read.{Batch, InputPartition, 
PartitionReaderFactory}
+import org.apache.spark.sql.sources._
+import org.apache.spark.sql.types.StructType
+import org.apache.yetus.audience.InterfaceAudience
+
+/**
+ * This is a new class in the spark4 module. Implements Batch.
+ * Responsible for physical planning: splits the read into partitions.
+ * Calls RegionLocator.getStartEndKeys() to discover HBase regions,
+ * intersects them with the row key filter's scan ranges, and produces an 
array of InputPartition objects.
+ *
+ * In the spark 3 DS V1 model, this logic was inside 
HBaseTableScanRDD.getPartitions().
+ *
+ * @param requiredSchema
+ * @param properties
+ * @param catalog
+ * @param rowKeyFilter
+ * @param pushedFilters
+ * @param encoderClsName
+ */
[email protected]
+class HBaseBatch(
+    requiredSchema: StructType,
+    properties: Map[String, String],
+    catalog: HBaseTableCatalog,
+    rowKeyFilter: RowKeyFilter,
+    pushedFilters: Array[Filter],
+    encoderClsName: String)
+    extends Batch
+    with Logging {
+
+  override def planInputPartitions(): Array[InputPartition] = {
+    val conf = HBaseConfiguration.create()
+    val configResources = properties.get(HBaseSparkConf.HBASE_CONFIG_LOCATION)
+    configResources.foreach(_.split(",").foreach(r => conf.addResource(new 
Path(r))))
+
+    val connection = HBaseConnectionCache.getConnection(conf)
+    try {
+      val tableName = s"${catalog.namespace}:${catalog.name}"
+      val regionLocator = 
connection.getRegionLocator(TableName.valueOf(tableName))
+      try {
+        val keys = regionLocator.getStartEndKeys
+        val startKeys = keys.getFirst
+        val endKeys = keys.getSecond
+
+        val regions = startKeys.zip(endKeys).zipWithIndex.map { case ((start, 
end), idx) =>
+          HBaseRegion(idx, Some(start), Some(end))
+        }
+
+        val scanRanges = rowKeyFilter.ranges.toSeq
+        val points = rowKeyFilter.points.toSeq
+
+        if (scanRanges.isEmpty && points.isEmpty) {
+          regions.map { region =>
+            HBaseInputPartition(
+              region.index,
+              region.start.orNull,
+              region.end.orNull): InputPartition
+          }
+        } else {
+          regions.flatMap { region =>
+            val regionRange = Range(region)
+            val intersectedRanges = Ranges.and(regionRange, scanRanges.map { 
sr =>
+              Range(
+                Option(sr.lowerBound).filter(_.nonEmpty).map(Bound(_, 
sr.isLowerBoundEqualTo)),
+                Option(sr.upperBound).map(Bound(_, sr.isUpperBoundEqualTo)))
+            })
+            val intersectedPoints = Points.and(regionRange, points.toSeq)
+
+            if (intersectedRanges.nonEmpty || intersectedPoints.nonEmpty) {
+              val startRow = 
intersectedRanges.headOption.flatMap(_.lower).map(_.b)
+                .orElse(intersectedPoints.headOption)
+                .orElse(region.start)
+                .orNull
+              val stopRow = 
intersectedRanges.lastOption.flatMap(_.upper).map(_.b)

Review Comment:
   this is the bigger gap I checked again with cursor as well.



##########
spark4/hbase-spark4/src/main/scala/org/apache/hadoop/hbase/spark/datasources/HBaseBatch.scala:
##########
@@ -0,0 +1,129 @@
+/*
+ * 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.hadoop.hbase.spark.datasources
+
+import org.apache.hadoop.fs.Path
+import org.apache.hadoop.hbase.{HBaseConfiguration, TableName}
+import org.apache.hadoop.hbase.spark.{HBaseConnectionCache, Logging}
+import org.apache.spark.sql.connector.read.{Batch, InputPartition, 
PartitionReaderFactory}
+import org.apache.spark.sql.sources._
+import org.apache.spark.sql.types.StructType
+import org.apache.yetus.audience.InterfaceAudience
+
+/**
+ * This is a new class in the spark4 module. Implements Batch.
+ * Responsible for physical planning: splits the read into partitions.
+ * Calls RegionLocator.getStartEndKeys() to discover HBase regions,
+ * intersects them with the row key filter's scan ranges, and produces an 
array of InputPartition objects.
+ *
+ * In the spark 3 DS V1 model, this logic was inside 
HBaseTableScanRDD.getPartitions().
+ *
+ * @param requiredSchema
+ * @param properties
+ * @param catalog
+ * @param rowKeyFilter
+ * @param pushedFilters
+ * @param encoderClsName
+ */
[email protected]
+class HBaseBatch(
+    requiredSchema: StructType,
+    properties: Map[String, String],
+    catalog: HBaseTableCatalog,
+    rowKeyFilter: RowKeyFilter,
+    pushedFilters: Array[Filter],
+    encoderClsName: String)
+    extends Batch
+    with Logging {
+
+  override def planInputPartitions(): Array[InputPartition] = {
+    val conf = HBaseConfiguration.create()
+    val configResources = properties.get(HBaseSparkConf.HBASE_CONFIG_LOCATION)
+    configResources.foreach(_.split(",").foreach(r => conf.addResource(new 
Path(r))))
+
+    val connection = HBaseConnectionCache.getConnection(conf)
+    try {
+      val tableName = s"${catalog.namespace}:${catalog.name}"
+      val regionLocator = 
connection.getRegionLocator(TableName.valueOf(tableName))
+      try {
+        val keys = regionLocator.getStartEndKeys
+        val startKeys = keys.getFirst
+        val endKeys = keys.getSecond
+
+        val regions = startKeys.zip(endKeys).zipWithIndex.map { case ((start, 
end), idx) =>
+          HBaseRegion(idx, Some(start), Some(end))
+        }
+
+        val scanRanges = rowKeyFilter.ranges.toSeq
+        val points = rowKeyFilter.points.toSeq
+
+        if (scanRanges.isEmpty && points.isEmpty) {
+          regions.map { region =>
+            HBaseInputPartition(
+              region.index,
+              region.start.orNull,
+              region.end.orNull): InputPartition
+          }
+        } else {
+          regions.flatMap { region =>
+            val regionRange = Range(region)
+            val intersectedRanges = Ranges.and(regionRange, scanRanges.map { 
sr =>
+              Range(
+                Option(sr.lowerBound).filter(_.nonEmpty).map(Bound(_, 
sr.isLowerBoundEqualTo)),
+                Option(sr.upperBound).map(Bound(_, sr.isUpperBoundEqualTo)))
+            })
+            val intersectedPoints = Points.and(regionRange, points.toSeq)
+
+            if (intersectedRanges.nonEmpty || intersectedPoints.nonEmpty) {
+              val startRow = 
intersectedRanges.headOption.flatMap(_.lower).map(_.b)
+                .orElse(intersectedPoints.headOption)
+                .orElse(region.start)
+                .orNull
+              val stopRow = 
intersectedRanges.lastOption.flatMap(_.upper).map(_.b)
+                
.orElse(intersectedPoints.lastOption.map(Utils.incrementByteArray))
+                .orElse(region.end)
+                .orNull
+              Some(HBaseInputPartition(region.index, startRow, stopRow): 
InputPartition)

Review Comment:
   seems like a behavior difference from V1 that `HBaseInputPartition` that 
uses `HBasePartitionReader.scala` are scanning instead of `Get` , do you think 
this is good ? if not , please try to align what Spark3 does with Get.



##########
spark4/hbase-spark4/src/main/scala/org/apache/hadoop/hbase/spark/datasources/HBasePartitionReader.scala:
##########
@@ -0,0 +1,317 @@
+/*
+ * 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.hadoop.hbase.spark.datasources
+
+import org.apache.hadoop.fs.Path
+import org.apache.hadoop.hbase.{CellUtil, HBaseConfiguration, TableName}
+import org.apache.hadoop.hbase.client.{Result, ResultScanner, Scan}
+import org.apache.hadoop.hbase.spark.{AndLogicExpression, 
DynamicLogicExpression,
+  EqualLogicExpression, GreaterThanLogicExpression, 
GreaterThanOrEqualLogicExpression,
+  HBaseConnectionCache, IsNullLogicExpression, LessThanLogicExpression,
+  LessThanOrEqualLogicExpression, Logging, OrLogicExpression, 
PassThroughLogicExpression,
+  PushdownMappedField, SmartConnection, SparkSQLPushDownFilter, 
StartsWithLogicExpression}
+import org.apache.hadoop.hbase.util.Bytes
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.GenericInternalRow
+import org.apache.spark.sql.connector.read.PartitionReader
+import org.apache.spark.sql.sources._
+import org.apache.spark.sql.types._
+import org.apache.spark.unsafe.types.UTF8String
+import org.apache.yetus.audience.InterfaceAudience
+import scala.collection.mutable.ListBuffer
+import scala.jdk.CollectionConverters._
+
+/**
+ * This is a new class in the spark4 module. Extends 
PartitionReader[InternalRow] for reading data from HBase regions.
+ * The actual execution: opens an HBase scanner on the partition's range, 
attaches the SparkSQLPushDownFilter,
+ * reads Result objects, and converts them to InternalRow. Implements 
next()/get()/close().
+ *
+ *
+ * In the spark 3 DS V1 model, this logic was inside DefaultSource.buildScan()
+ * which returned an RDD[Row] with its own compute() method.
+ *
+ * @param partition
+ * @param requiredSchema
+ * @param properties
+ * @param catalog
+ * @param pushedFilters
+ * @param encoderClsName
+ * @param usePushDownColumnFilter
+ */
[email protected]
+class HBasePartitionReader(
+    partition: HBaseInputPartition,
+    requiredSchema: StructType,
+    properties: Map[String, String],
+    catalog: HBaseTableCatalog,
+    pushedFilters: Array[Filter],
+    encoderClsName: String,
+    usePushDownColumnFilter: Boolean)
+    extends PartitionReader[InternalRow]
+    with Logging {
+
+  private val conf = HBaseConfiguration.create()
+  private val configResources = 
properties.get(HBaseSparkConf.HBASE_CONFIG_LOCATION)
+  configResources.foreach(_.split(",").foreach(r => conf.addResource(new 
Path(r))))
+
+  private val connection: SmartConnection = 
HBaseConnectionCache.getConnection(conf)
+  private val tableName = s"${catalog.namespace}:${catalog.name}"
+  private val table = connection.getTable(TableName.valueOf(tableName))
+
+  private val scanner: ResultScanner = {
+    val scan = new Scan()
+
+    if (partition.startRow != null && partition.startRow.nonEmpty) {
+      scan.withStartRow(partition.startRow)
+    }
+    if (partition.stopRow != null && partition.stopRow.nonEmpty) {
+      scan.withStopRow(partition.stopRow)
+    }
+
+    val blockCacheEnable = properties
+      .get(HBaseSparkConf.QUERY_CACHEBLOCKS)
+      .map(_.toBoolean)
+      .getOrElse(HBaseSparkConf.DEFAULT_QUERY_CACHEBLOCKS)
+    scan.setCacheBlocks(blockCacheEnable)

Review Comment:
   +1



##########
spark4/hbase-spark4/src/main/scala/org/apache/hadoop/hbase/spark/datasources/HBaseBatch.scala:
##########
@@ -0,0 +1,129 @@
+/*
+ * 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.hadoop.hbase.spark.datasources
+
+import org.apache.hadoop.fs.Path
+import org.apache.hadoop.hbase.{HBaseConfiguration, TableName}
+import org.apache.hadoop.hbase.spark.{HBaseConnectionCache, Logging}
+import org.apache.spark.sql.connector.read.{Batch, InputPartition, 
PartitionReaderFactory}
+import org.apache.spark.sql.sources._
+import org.apache.spark.sql.types.StructType
+import org.apache.yetus.audience.InterfaceAudience
+
+/**
+ * This is a new class in the spark4 module. Implements Batch.
+ * Responsible for physical planning: splits the read into partitions.
+ * Calls RegionLocator.getStartEndKeys() to discover HBase regions,
+ * intersects them with the row key filter's scan ranges, and produces an 
array of InputPartition objects.
+ *
+ * In the spark 3 DS V1 model, this logic was inside 
HBaseTableScanRDD.getPartitions().
+ *
+ * @param requiredSchema
+ * @param properties
+ * @param catalog
+ * @param rowKeyFilter
+ * @param pushedFilters
+ * @param encoderClsName
+ */
[email protected]
+class HBaseBatch(
+    requiredSchema: StructType,
+    properties: Map[String, String],
+    catalog: HBaseTableCatalog,
+    rowKeyFilter: RowKeyFilter,
+    pushedFilters: Array[Filter],
+    encoderClsName: String)
+    extends Batch
+    with Logging {
+
+  override def planInputPartitions(): Array[InputPartition] = {

Review Comment:
   we may need to support `getPreferredLocations` like V1 does , you can have 
it in the future PR.



##########
spark4/hbase-spark4/src/main/scala/org/apache/hadoop/hbase/spark/datasources/HBaseScanBuilder.scala:
##########
@@ -0,0 +1,87 @@
+/*
+ * 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.hadoop.hbase.spark.datasources
+
+import org.apache.hadoop.hbase.spark.Logging
+import org.apache.spark.sql.connector.read.{Scan, ScanBuilder, 
SupportsPushDownFilters, SupportsPushDownRequiredColumns}
+import org.apache.spark.sql.sources._
+import org.apache.spark.sql.types.StructType
+import org.apache.yetus.audience.InterfaceAudience
+import scala.collection.mutable.ListBuffer
+
+/**
+ * This is a new class in the spark4 module.
+ * Implements ScanBuilder, SupportsPushDownFilters, and 
SupportsPushDownRequiredColumns.
+ * This is where Catalyst negotiates with the connector. Spark calls 
pushFilters() with
+ * candidate predicates and the builder accepts what it can handle and returns 
the rest.
+ * Spark calls pruneColumns() to say which columns it actually needs.
+ * Then build() produces the final scan plan.
+ *
+ * In the spark 3 V1 model, this negotiation happened implicitly via
+ * PrunedFilteredScan.buildScan(requiredColumns, filters) as a single method 
call with no back-and-forth.
+ *
+ * @param schema
+ * @param properties
+ */
[email protected]
+class HBaseScanBuilder(schema: StructType, properties: Map[String, String])
+    extends ScanBuilder
+    with SupportsPushDownFilters
+    with SupportsPushDownRequiredColumns
+    with Logging {
+
+  private val catalog = HBaseTableCatalog(properties)
+  private val encoderClsName =
+    properties.getOrElse(HBaseSparkConf.QUERY_ENCODER, 
HBaseSparkConf.DEFAULT_QUERY_ENCODER)
+  @transient private val encoder = JavaBytesEncoder.create(encoderClsName)
+
+  private var _pushedFilters: Array[Filter] = Array.empty
+  private var requiredSchema: StructType = schema
+
+  override def pushFilters(filters: Array[Filter]): Array[Filter] = {
+    val supported = new ListBuffer[Filter]()
+    val unsupported = new ListBuffer[Filter]()
+
+    filters.foreach {
+      case f @ EqualTo(attr, _) if catalog.sMap.map.contains(attr) => 
supported += f
+      case f @ LessThan(attr, _) if catalog.sMap.map.contains(attr) => 
supported += f
+      case f @ GreaterThan(attr, _) if catalog.sMap.map.contains(attr) => 
supported += f
+      case f @ LessThanOrEqual(attr, _) if catalog.sMap.map.contains(attr) => 
supported += f
+      case f @ GreaterThanOrEqual(attr, _) if catalog.sMap.map.contains(attr) 
=> supported += f
+      case f @ StringStartsWith(attr, _) if catalog.sMap.map.contains(attr) => 
supported += f
+      case f @ IsNull(attr) if catalog.sMap.map.contains(attr) => supported += 
f
+      case f @ IsNotNull(attr) if catalog.sMap.map.contains(attr) => supported 
+= f
+      case f @ Or(_, _) => supported += f
+      case f @ And(_, _) => supported += f

Review Comment:
   recheck with Cursor, they found the same with below comments
   
   > Or/And are pushed even when nested predicates reference unknown columns. 
V1 effectively only pushed filters it could interpret. Consider recursively 
validating leaf attributes, or only pushing compounds whose children are all 
supported.
   



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