HyukjinKwon commented on a change in pull request #27366:
URL: https://github.com/apache/spark/pull/27366#discussion_r454951179



##########
File path: 
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/csv/CSVFilters.scala
##########
@@ -54,138 +53,49 @@ class CSVFilters(filters: Seq[sources.Filter], 
requiredSchema: StructType) {
       for (filter <- filters) {
         val refs = filter.references
         val index = if (refs.isEmpty) {
-          // For example, AlwaysTrue and AlwaysFalse doesn't have any 
references
+          // For example, `AlwaysTrue` and `AlwaysFalse` doesn't have any 
references
           // Filters w/o refs always return the same result. Taking into 
account
-          // that predicates are combined via And, we can apply such filters 
only
+          // that predicates are combined via `And`, we can apply such filters 
only
           // once at the position 0.
           0
         } else {
           // readSchema must contain attributes of all filters.
-          // Accordingly, fieldIndex() returns a valid index always.
+          // Accordingly, `fieldIndex()` returns a valid index always.
           refs.map(requiredSchema.fieldIndex).max
         }
         groupedFilters(index) :+= filter
       }
       if (len > 0 && !groupedFilters(0).isEmpty) {
-        // We assume that filters w/o refs like AlwaysTrue and AlwaysFalse
+        // We assume that filters w/o refs like `AlwaysTrue` and `AlwaysFalse`
         // can be evaluated faster that others. We put them in front of others.
         val (literals, others) = 
groupedFilters(0).partition(_.references.isEmpty)
         groupedFilters(0) = literals ++ others
       }
       for (i <- 0 until len) {
         if (!groupedFilters(i).isEmpty) {
-          val reducedExpr = groupedFilters(i)
-            .flatMap(CSVFilters.filterToExpression(_, toRef))
-            .reduce(And)
-          groupedPredicates(i) = Predicate.create(reducedExpr)
+          groupedPredicates(i) = toPredicate(groupedFilters(i))
         }
       }
     }
     groupedPredicates
   }
 
   /**
-   * Applies all filters that refer to row fields at the positions from 0 to 
index.
+   * Applies all filters that refer to row fields at the positions from 0 to 
`index`.
    * @param row The internal row to check.
    * @param index Maximum field index. The function assumes that all fields
-   *              from 0 to index position are set.
-   * @return false iff row fields at the position from 0 to index pass filters
+   *              from 0 to `index`` position are set.

Review comment:
       oops  ` `` ` 

##########
File path: 
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/json/JsonFilters.scala
##########
@@ -0,0 +1,159 @@
+/*
+ * 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.spark.sql.catalyst.json
+
+import org.apache.spark.sql.catalyst.{InternalRow, StructFilters}
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.sources
+import org.apache.spark.sql.types.StructType
+
+/**
+ * The class provides API for applying pushed down source filters to rows with
+ * a struct schema parsed from JSON records. The class should be used in this 
way:
+ * 1. Before processing of the next row, `JacksonParser` (parser for short) 
resets the internal
+ *    state of `JsonFilters` by calling the `reset()` method.
+ * 2. The parser reads JSON fields one-by-one in streaming fashion. It 
converts an incoming
+ *    field value to the desired type from the schema. After that, it sets the 
value to an instance
+ *    of `InternalRow` at the position according to the schema. Order of 
parsed JSON fields can
+ *    be different from the order in the schema.
+ * 3. Per every JSON field of the top-level JSON object, the parser calls 
`skipRow` by passing
+ *    an `InternalRow` in which some of fields can be already set, and the 
position of the JSON
+ *    field according to the schema.
+ *    3.1 `skipRow` finds a group of predicates that refers to this JSON field.
+ *    3.2 Per each predicate from the group, `skipRow` decrements its 
reference counter.
+ *    3.2.1 If predicate reference counter becomes 0, it means that all 
predicate attributes have
+ *          been already set in the internal row, and the predicate can be 
applied to it. `skipRow`
+ *          invokes the predicate for the row.
+ *    3.3 `skipRow` applies predicates until one of them returns `false`. In 
that case, the method
+ *        returns `true` to the parser.
+ *    3.4 If all predicates with zero reference counter return `true`, the 
final result of
+ *        the method is `false` which tells the parser to not skip the row.
+ * 4. If the parser gets `true` from `JsonFilters.skipRow`, it must not call 
the method anymore
+ *    for this internal row, and should go the step 1.
+ *
+ * `JsonFilters` assumes that:
+ *   - `reset()` is called before any `skipRow()` calls for new row.
+ *   - `skipRow()` can be called for any valid index of the struct fields,
+ *      and in any order.
+ *   - After `skipRow()` returns `true`, the internal state of `JsonFilters` 
can be inconsistent,
+ *     so, `skipRow()` must not be called for the current row anymore without 
`reset()`.
+ *
+ * @param pushedFilters The pushed down source filters. The filters should 
refer to
+ *                      the fields of the provided schema.
+ * @param schema The required schema of records from datasource files.
+ */
+class JsonFilters(pushedFilters: Seq[sources.Filter], schema: StructType)
+  extends StructFilters(pushedFilters, schema) {
+
+  /**
+   * Stateful JSON predicate that keeps track of its dependent references in 
the
+   * current row via `refCount`.
+   *
+   * @param predicate The predicate compiled from pushed down source filters.
+   * @param totalRefs The total amount of all filters references which the 
predicate
+   *                  compiled from.
+   */
+  case class JsonPredicate(predicate: BasePredicate, totalRefs: Int) {
+    // The current number of predicate references in the row that have been 
not set yet.
+    // When `refCount` reaches zero, the predicate has all dependencies are 
set, and can
+    // be applied to the row.
+    var refCount: Int = totalRefs
+
+    def reset(): Unit = {
+      refCount = totalRefs
+    }
+  }
+
+  // Predicates compiled from the pushed down filters. The predicates are 
grouped by their
+  // attributes. The i-th group contains predicates that refer to the i-th 
field of the given
+  // schema. A predicates can be placed to many groups if it has many 
attributes. For example:
+  //  schema: i INTEGER, s STRING
+  //  filters: IsNotNull("i"), AlwaysTrue, Or(EqualTo("i", 0), 
StringStartsWith("s", "abc"))
+  //  predicates:
+  //    0: Array(IsNotNull("i"), AlwaysTrue, Or(EqualTo("i", 0), 
StringStartsWith("s", "abc")))
+  //    1: Array(AlwaysTrue, Or(EqualTo("i", 0), StringStartsWith("s", "abc")))
+  private val predicates: Array[Array[JsonPredicate]] = {
+    val groupedPredicates = 
Array.fill(schema.length)(Array.empty[JsonPredicate])
+    if (SQLConf.get.jsonFilterPushDown) {
+      val groupedByRefSet = filters

Review comment:
       What about we specify the types in the `val`s here? e.g.:
   
   ```scala
   val groupedByRefSet: Map[Set[String], JsonPredicate] = filters
   ...
   val withLiterals: Map[Set[String], JsonPredicate] 
   ...
   // maybe
   val groupedByFields: Map[String, Seq[JsonPredicate]] = withLiterals.toSeq
     .flatMap { case (refSet, pred) => refSet.map(ref => (ref, pred)) }
     .groupBy { case (ref, _) => ref }
     .map { case (ref, pairs) => (ref, pairs.map { case (_, pred) => pred }) }
   ```




----------------------------------------------------------------
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:
[email protected]



---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to