boneanxs commented on code in PR #6725:
URL: https://github.com/apache/hudi/pull/6725#discussion_r1028798030


##########
hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/util/PartitionFilterGenerator.java:
##########
@@ -0,0 +1,191 @@
+/*
+ * 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.hive.util;
+
+import org.apache.hudi.common.util.ReflectionUtils;
+import org.apache.hudi.common.util.collection.Pair;
+import org.apache.hudi.hive.HiveSyncConfig;
+import org.apache.hudi.hive.HoodieHiveSyncException;
+import org.apache.hudi.hive.expression.BinaryOperator;
+import org.apache.hudi.hive.expression.Expression;
+import org.apache.hudi.hive.expression.LeafExpression;
+import org.apache.hudi.sync.common.model.FieldSchema;
+import org.apache.hudi.sync.common.model.Partition;
+import org.apache.hudi.sync.common.model.PartitionValueExtractor;
+
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+import static 
org.apache.hudi.hive.HiveSyncConfig.HIVE_SYNC_FILTER_PUSHDOWN_MAX_SIZE;
+import static 
org.apache.hudi.sync.common.HoodieSyncConfig.META_SYNC_PARTITION_EXTRACTOR_CLASS;
+
+public class PartitionFilterGenerator {
+
+  /**
+   * Build expression from the Partition list.
+   *
+   * ex. partitionSchema(date, hour) [Partition(2022-09-01, 12), 
Partition(2022-09-02, 13)] =>
+   *     Or(And(Equal(Attribute(date), Literal(2022-09-01)), 
Equal(Attribute(hour), Literal(12))),
+   *     And(Equal(Attribute(date), Literal(2022-09-02)), 
Equal(Attribute(hour), Literal(13))))
+   */
+  private static Expression buildPartitionExpression(List<Partition> 
partitions, List<FieldSchema> partitionFields) {
+    return partitions.stream().map(partition -> {
+      List<String> partitionValues = partition.getValues();
+      Expression root = null;
+
+      for (int i = 0; i < partitionFields.size(); i++) {
+        FieldSchema field = partitionFields.get(i);
+        String value = partitionValues.get(i);
+        BinaryOperator.EqualTo exp = new BinaryOperator.EqualTo(new 
LeafExpression.AttributeReferenceExpression(field.getName()),
+            new LeafExpression.Literal(value, field.getType()));
+        if (root != null) {
+          root = new BinaryOperator.And(root, exp);
+        } else {
+          root = exp;
+        }
+      }
+      return root;
+    }).reduce(null, (result, expr) -> {
+      if (result == null) {
+        return expr;
+      } else {
+        return new BinaryOperator.Or(result, expr);
+      }
+    });
+  }
+
+  /**
+   * Extract partition values from the {@param partitions}, and binding to
+   * corresponding partition fieldSchemas.
+   */
+  private static List<Pair<FieldSchema, String[]>> 
extractFieldValues(List<Partition> partitions, List<FieldSchema> 
partitionFields) {
+    return IntStream.range(0, partitionFields.size())
+        .mapToObj(i -> {
+          Set<String> values = new HashSet<String>();
+          for (int j = 0; j < partitions.size(); j++) {
+            values.add(partitions.get(j).getValues().get(i));
+          }
+          return Pair.of(partitionFields.get(i), values.toArray(new 
String[0]));
+        })
+        .collect(Collectors.toList());
+  }
+
+  private static class ValueComparator implements Comparator<String> {
+
+    private final String valueType;
+    public ValueComparator(String type) {
+      this.valueType = type;
+    }
+
+    @Override
+    public int compare(String s1, String s2) {
+      switch (valueType.toLowerCase(Locale.ROOT)) {
+        case HiveSchemaUtil.INT_TYPE_NAME:
+          int i1 = Integer.parseInt(s1);
+          int i2 = Integer.parseInt(s2);
+          return i1 - i2;
+        case HiveSchemaUtil.BIGINT_TYPE_NAME:
+          long l1 = Long.parseLong(s1);
+          long l2 = Long.parseLong(s2);
+          long result = l1 - l2;
+          if (result > 0) {
+            return 1;
+          }
+
+          if (result < 0) {
+            return -1;
+          }
+
+          return 0;
+        default:
+          return s1.compareTo(s2);
+      }
+    }
+  }
+
+  /**
+   * This method will extract the min value and the max value of each field,
+   * and construct GreatThanOrEqual and LessThanOrEqual to build the 
expression.
+   *
+   * This method can reduce the Expression tree level a lot if each field has 
too many values.
+   */
+  private static Expression buildMinMaxPartitionExpression(List<Partition> 
partitions, List<FieldSchema> partitionFields) {
+    return extractFieldValues(partitions, 
partitionFields).stream().map(fieldWithValues -> {
+      FieldSchema fieldSchema = fieldWithValues.getKey();
+      String[] values = fieldWithValues.getValue();
+
+      if (values.length == 1) {
+        return new BinaryOperator.EqualTo(new 
LeafExpression.AttributeReferenceExpression(fieldSchema.getName()),
+            new LeafExpression.Literal(values[0], fieldSchema.getType()));
+      }
+
+      Arrays.sort(values, new ValueComparator(fieldSchema.getType()));

Review Comment:
   Yes, here just use a simple sort to get `min` and `max` value to avoid write 
many codes here. Given that usually array `values` doesn't have too many items, 
the cost of `sort` can be acceptable?



##########
hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/util/FilterGenVisitor.java:
##########
@@ -0,0 +1,104 @@
+/*
+ * 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.hive.util;
+
+import org.apache.hudi.hive.expression.Expression;
+import org.apache.hudi.hive.expression.ExpressionVisitor;
+import org.apache.hudi.hive.expression.LeafExpression;
+
+import java.util.Locale;
+
+public class FilterGenVisitor implements ExpressionVisitor<String> {
+
+  private String makeBinaryOperatorString(String left,  Expression.Operator 
operator, String right) {
+    return String.format("%s %s %s", left, operator.sqlOperator, right);
+  }
+
+  private String quoteStringLiteral(String value) {
+    if (!value.contains("\"")) {
+      return "\"" + value + "\"";
+    } else if (!value.contains("'")) {
+      return "'" + value + "'";
+    } else {
+      throw new UnsupportedOperationException("Cannot pushdown filters if \" 
and ' both exist");
+    }
+  }
+
+  @Override
+  public String visitAnd(Expression left, Expression right) {
+    String leftResult = left.accept(this);
+    String rightResult = right.accept(this);
+
+    if (leftResult.isEmpty() && rightResult.isEmpty()) {

Review Comment:
   Will change, looks this is different code habit 😄, I always try to avoid 
if() else if() chain in codes.



##########
hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/util/PartitionFilterGenerator.java:
##########
@@ -0,0 +1,191 @@
+/*
+ * 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.hive.util;
+
+import org.apache.hudi.common.util.ReflectionUtils;
+import org.apache.hudi.common.util.collection.Pair;
+import org.apache.hudi.hive.HiveSyncConfig;
+import org.apache.hudi.hive.HoodieHiveSyncException;
+import org.apache.hudi.hive.expression.BinaryOperator;
+import org.apache.hudi.hive.expression.Expression;
+import org.apache.hudi.hive.expression.LeafExpression;
+import org.apache.hudi.sync.common.model.FieldSchema;
+import org.apache.hudi.sync.common.model.Partition;
+import org.apache.hudi.sync.common.model.PartitionValueExtractor;
+
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+import static 
org.apache.hudi.hive.HiveSyncConfig.HIVE_SYNC_FILTER_PUSHDOWN_MAX_SIZE;
+import static 
org.apache.hudi.sync.common.HoodieSyncConfig.META_SYNC_PARTITION_EXTRACTOR_CLASS;
+
+public class PartitionFilterGenerator {
+
+  /**
+   * Build expression from the Partition list.
+   *
+   * ex. partitionSchema(date, hour) [Partition(2022-09-01, 12), 
Partition(2022-09-02, 13)] =>
+   *     Or(And(Equal(Attribute(date), Literal(2022-09-01)), 
Equal(Attribute(hour), Literal(12))),
+   *     And(Equal(Attribute(date), Literal(2022-09-02)), 
Equal(Attribute(hour), Literal(13))))
+   */
+  private static Expression buildPartitionExpression(List<Partition> 
partitions, List<FieldSchema> partitionFields) {
+    return partitions.stream().map(partition -> {
+      List<String> partitionValues = partition.getValues();
+      Expression root = null;
+
+      for (int i = 0; i < partitionFields.size(); i++) {
+        FieldSchema field = partitionFields.get(i);
+        String value = partitionValues.get(i);
+        BinaryOperator.EqualTo exp = new BinaryOperator.EqualTo(new 
LeafExpression.AttributeReferenceExpression(field.getName()),
+            new LeafExpression.Literal(value, field.getType()));
+        if (root != null) {
+          root = new BinaryOperator.And(root, exp);
+        } else {
+          root = exp;
+        }
+      }
+      return root;
+    }).reduce(null, (result, expr) -> {
+      if (result == null) {
+        return expr;
+      } else {
+        return new BinaryOperator.Or(result, expr);
+      }
+    });
+  }
+
+  /**
+   * Extract partition values from the {@param partitions}, and binding to
+   * corresponding partition fieldSchemas.
+   */
+  private static List<Pair<FieldSchema, String[]>> 
extractFieldValues(List<Partition> partitions, List<FieldSchema> 
partitionFields) {
+    return IntStream.range(0, partitionFields.size())
+        .mapToObj(i -> {
+          Set<String> values = new HashSet<String>();
+          for (int j = 0; j < partitions.size(); j++) {
+            values.add(partitions.get(j).getValues().get(i));
+          }
+          return Pair.of(partitionFields.get(i), values.toArray(new 
String[0]));
+        })
+        .collect(Collectors.toList());
+  }
+
+  private static class ValueComparator implements Comparator<String> {
+
+    private final String valueType;
+    public ValueComparator(String type) {
+      this.valueType = type;
+    }
+
+    @Override
+    public int compare(String s1, String s2) {
+      switch (valueType.toLowerCase(Locale.ROOT)) {
+        case HiveSchemaUtil.INT_TYPE_NAME:
+          int i1 = Integer.parseInt(s1);
+          int i2 = Integer.parseInt(s2);
+          return i1 - i2;
+        case HiveSchemaUtil.BIGINT_TYPE_NAME:
+          long l1 = Long.parseLong(s1);
+          long l2 = Long.parseLong(s2);
+          long result = l1 - l2;
+          if (result > 0) {
+            return 1;
+          }
+
+          if (result < 0) {
+            return -1;
+          }
+
+          return 0;
+        default:
+          return s1.compareTo(s2);

Review Comment:
   HMS only accept `Date`, `INT`, `String`, `BIGINT` to push down partition 
filters, and we also will only extract literal values for these 
types(`FilterGenVisitor#visitLiteral`).
   
   I will throw exception here in case misunderstanding.



##########
hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/HiveSyncTool.java:
##########
@@ -309,14 +311,36 @@ private boolean syncSchema(String tableName, boolean 
tableExists, boolean useRea
     return schemaChanged;
   }
 
+  /**
+   * Fetch partitions from meta service, will try to push down more filters to 
avoid fetching
+   * too many unnecessary partitions.
+   */
+  private List<Partition> getTablePartitions(String tableName, List<String> 
writtenPartitionsSince) {

Review Comment:
   Added it in the method `syncPartitions`, will also add it here.



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