You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hudi.apache.org by si...@apache.org on 2022/12/13 22:11:46 UTC
[hudi] 05/10: [HUDI-4881] Push down filters if possible when syncing partitions to Hive (#6725)
This is an automated email from the ASF dual-hosted git repository.
sivabalan pushed a commit to branch release-0.12.2-shadow
in repository https://gitbox.apache.org/repos/asf/hudi.git
commit ae21564b053c62e07966cec6ead55ebea5d57af1
Author: RexAn <bo...@gmail.com>
AuthorDate: Sat Dec 10 03:07:46 2022 +0800
[HUDI-4881] Push down filters if possible when syncing partitions to Hive (#6725)
---
.../apache/hudi/common/util/CollectionUtils.java | 9 +
.../java/org/apache/hudi/hive/HiveSyncConfig.java | 11 ++
.../java/org/apache/hudi/hive/HiveSyncTool.java | 34 +++-
.../org/apache/hudi/hive/HoodieHiveSyncClient.java | 13 ++
.../expression/AttributeReferenceExpression.java | 37 ++++
.../hudi/hive/expression/BinaryOperator.java | 75 ++++++++
.../apache/hudi/hive/expression/Expression.java | 53 ++++++
.../hudi/hive/expression/ExpressionVisitor.java | 31 +++
.../hudi/hive/expression/LeafExpression.java | 29 +++
.../org/apache/hudi/hive/expression/Literal.java | 43 +++++
.../apache/hudi/hive/util/FilterGenVisitor.java | 119 ++++++++++++
.../org/apache/hudi/hive/util/HiveSchemaUtil.java | 33 ++--
.../hudi/hive/util/PartitionFilterGenerator.java | 212 +++++++++++++++++++++
.../org/apache/hudi/hive/TestHiveSyncTool.java | 103 +++++++---
.../hive/util/TestPartitionFilterGenerator.java | 134 +++++++++++++
.../hudi/sync/common/HoodieMetaSyncOperations.java | 9 +
16 files changed, 902 insertions(+), 43 deletions(-)
diff --git a/hudi-common/src/main/java/org/apache/hudi/common/util/CollectionUtils.java b/hudi-common/src/main/java/org/apache/hudi/common/util/CollectionUtils.java
index 521fab019ba..4c489ef95f7 100644
--- a/hudi-common/src/main/java/org/apache/hudi/common/util/CollectionUtils.java
+++ b/hudi-common/src/main/java/org/apache/hudi/common/util/CollectionUtils.java
@@ -151,6 +151,15 @@ public class CollectionUtils {
return combined;
}
+ /**
+ * Zip two lists into a Map. Will throw Exception if the size is different between these two lists.
+ */
+ public static <K, V> Map<K, V> zipToMap(List<K> keys, List<V> values) {
+ checkArgument(keys.size() == values.size(),
+ "keys' size must be equal with the values' size");
+ return IntStream.range(0, keys.size()).boxed().collect(Collectors.toMap(keys::get, values::get));
+ }
+
/**
* Returns difference b/w {@code one} {@link Set} of elements and {@code another}
*/
diff --git a/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/HiveSyncConfig.java b/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/HiveSyncConfig.java
index d9d733119aa..11eba393e6a 100644
--- a/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/HiveSyncConfig.java
+++ b/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/HiveSyncConfig.java
@@ -65,6 +65,17 @@ public class HiveSyncConfig extends HoodieSyncConfig {
public static final ConfigProperty<String> HIVE_SYNC_BUCKET_SYNC_SPEC = HiveSyncConfigHolder.HIVE_SYNC_BUCKET_SYNC_SPEC;
public static final ConfigProperty<String> HIVE_SYNC_COMMENT = HiveSyncConfigHolder.HIVE_SYNC_COMMENT;
+ public static final ConfigProperty<Boolean> HIVE_SYNC_FILTER_PUSHDOWN_ENABLED = ConfigProperty
+ .key("hoodie.datasource.hive_sync.filter_pushdown_enabled")
+ .defaultValue(false)
+ .withDocumentation("Whether to enable push down partitions by filter");
+
+ public static final ConfigProperty<Integer> HIVE_SYNC_FILTER_PUSHDOWN_MAX_SIZE = ConfigProperty
+ .key("hoodie.datasource.hive_sync.filter_pushdown_max_size")
+ .defaultValue(1000)
+ .withDocumentation("Max size limit to push down partition filters, if the estimate push down "
+ + "filters exceed this size, will directly try to fetch all partitions");
+
public static String getBucketSpec(String bucketCols, int bucketNum) {
return "CLUSTERED BY (" + bucketCols + " INTO " + bucketNum + " BUCKETS";
}
diff --git a/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/HiveSyncTool.java b/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/HiveSyncTool.java
index 88e7d743e1d..f40654d969b 100644
--- a/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/HiveSyncTool.java
+++ b/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/HiveSyncTool.java
@@ -25,6 +25,7 @@ import org.apache.hudi.exception.HoodieException;
import org.apache.hudi.exception.InvalidTableException;
import org.apache.hudi.hadoop.utils.HoodieInputFormatUtils;
import org.apache.hudi.hive.util.HiveSchemaUtil;
+import org.apache.hudi.hive.util.PartitionFilterGenerator;
import org.apache.hudi.sync.common.HoodieSyncClient;
import org.apache.hudi.sync.common.HoodieSyncTool;
import org.apache.hudi.sync.common.model.FieldSchema;
@@ -46,6 +47,7 @@ import java.util.Properties;
import java.util.Set;
import java.util.stream.Collectors;
+import static org.apache.hudi.hive.HiveSyncConfig.HIVE_SYNC_FILTER_PUSHDOWN_ENABLED;
import static org.apache.hudi.hive.HiveSyncConfigHolder.HIVE_AUTO_CREATE_DATABASE;
import static org.apache.hudi.hive.HiveSyncConfigHolder.HIVE_IGNORE_EXCEPTIONS;
import static org.apache.hudi.hive.HiveSyncConfigHolder.HIVE_SYNC_OMIT_METADATA_FIELDS;
@@ -309,14 +311,44 @@ public class HiveSyncTool extends HoodieSyncTool implements AutoCloseable {
return schemaChanged;
}
+ /**
+ * Fetch partitions from meta service, will try to push down more filters to avoid fetching
+ * too many unnecessary partitions.
+ *
+ * @param writtenPartitions partitions has been added, updated, or dropped since last synced.
+ */
+ private List<Partition> getTablePartitions(String tableName, List<String> writtenPartitions) {
+ if (!config.getBooleanOrDefault(HIVE_SYNC_FILTER_PUSHDOWN_ENABLED)) {
+ return syncClient.getAllPartitions(tableName);
+ }
+
+ List<String> partitionKeys = config.getSplitStrings(META_SYNC_PARTITION_FIELDS).stream()
+ .map(String::toLowerCase)
+ .collect(Collectors.toList());
+
+ List<FieldSchema> partitionFields = syncClient.getMetastoreFieldSchemas(tableName)
+ .stream()
+ .filter(f -> partitionKeys.contains(f.getName()))
+ .collect(Collectors.toList());
+
+ return syncClient.getPartitionsByFilter(tableName,
+ PartitionFilterGenerator.generatePushDownFilter(writtenPartitions, partitionFields, config));
+ }
+
/**
* Syncs the list of storage partitions passed in (checks if the partition is in hive, if not adds it or if the
* partition path does not match, it updates the partition path).
+ *
+ * @param writtenPartitionsSince partitions has been added, updated, or dropped since last synced.
*/
private boolean syncPartitions(String tableName, List<String> writtenPartitionsSince, Set<String> droppedPartitions) {
boolean partitionsChanged;
try {
- List<Partition> hivePartitions = syncClient.getAllPartitions(tableName);
+ if (writtenPartitionsSince.isEmpty() || config.getSplitStrings(META_SYNC_PARTITION_FIELDS).isEmpty()) {
+ return false;
+ }
+
+ List<Partition> hivePartitions = getTablePartitions(tableName, writtenPartitionsSince);
List<PartitionEvent> partitionEvents =
syncClient.getPartitionEvents(hivePartitions, writtenPartitionsSince, droppedPartitions);
diff --git a/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/HoodieHiveSyncClient.java b/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/HoodieHiveSyncClient.java
index 5e31f88d486..7d163016565 100644
--- a/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/HoodieHiveSyncClient.java
+++ b/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/HoodieHiveSyncClient.java
@@ -181,6 +181,19 @@ public class HoodieHiveSyncClient extends HoodieSyncClient {
}
}
+ @Override
+ public List<Partition> getPartitionsByFilter(String tableName, String filter) {
+ try {
+ return client.listPartitionsByFilter(databaseName, tableName, filter, (short)-1)
+ .stream()
+ .map(p -> new Partition(p.getValues(), p.getSd().getLocation()))
+ .collect(Collectors.toList());
+ } catch (TException e) {
+ throw new HoodieHiveSyncException("Failed to get partitions for table "
+ + tableId(databaseName, tableName) + " with filter " + filter, e);
+ }
+ }
+
@Override
public void createTable(String tableName, MessageType storageSchema, String inputFormatClass,
String outputFormatClass, String serdeClass,
diff --git a/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/expression/AttributeReferenceExpression.java b/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/expression/AttributeReferenceExpression.java
new file mode 100644
index 00000000000..3be19330a19
--- /dev/null
+++ b/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/expression/AttributeReferenceExpression.java
@@ -0,0 +1,37 @@
+/*
+ * 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.expression;
+
+public class AttributeReferenceExpression extends LeafExpression {
+
+ private final String name;
+
+ public AttributeReferenceExpression(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public <T> T accept(ExpressionVisitor<T> exprVisitor) {
+ return exprVisitor.visitAttribute(this);
+ }
+}
diff --git a/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/expression/BinaryOperator.java b/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/expression/BinaryOperator.java
new file mode 100644
index 00000000000..d2bc83e9452
--- /dev/null
+++ b/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/expression/BinaryOperator.java
@@ -0,0 +1,75 @@
+/*
+ * 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.expression;
+
+import java.util.Arrays;
+
+/**
+ * The expression that accept two child expressions.
+ */
+public class BinaryOperator extends Expression {
+
+ private final Operator operator;
+ private final Expression left;
+ private final Expression right;
+
+ private BinaryOperator(Expression left, Operator operator, Expression right) {
+ super(Arrays.asList(left, right));
+ this.left = left;
+ this.operator = operator;
+ this.right = right;
+ }
+
+ public static BinaryOperator and(Expression left, Expression right) {
+ return new BinaryOperator(left, Operator.AND, right);
+ }
+
+ public static BinaryOperator or(Expression left, Expression right) {
+ return new BinaryOperator(left, Operator.OR, right);
+ }
+
+ public static BinaryOperator eq(Expression left, Expression right) {
+ return new BinaryOperator(left, Operator.EQ, right);
+ }
+
+ public static BinaryOperator gteq(Expression left, Expression right) {
+ return new BinaryOperator(left, Operator.GT_EQ, right);
+ }
+
+ public static BinaryOperator lteq(Expression left, Expression right) {
+ return new BinaryOperator(left, Operator.LT_EQ, right);
+ }
+
+ public Operator getOperator() {
+ return operator;
+ }
+
+ public Expression getLeft() {
+ return left;
+ }
+
+ public Expression getRight() {
+ return right;
+ }
+
+ @Override
+ public <T> T accept(ExpressionVisitor<T> exprVisitor) {
+ return exprVisitor.visitBinaryOperator(this);
+ }
+}
diff --git a/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/expression/Expression.java b/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/expression/Expression.java
new file mode 100644
index 00000000000..8a64237ae1b
--- /dev/null
+++ b/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/expression/Expression.java
@@ -0,0 +1,53 @@
+/*
+ * 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.expression;
+
+import java.util.List;
+
+public abstract class Expression {
+
+ public enum Operator {
+ AND("AND", "&&"),
+ OR("OR", "||"),
+ GT(">", ">"),
+ LT("<", "<"),
+ EQ("=", "="),
+ GT_EQ(">=", ">="),
+ LT_EQ("<=", "<=");
+
+ public final String sqlOperator;
+ public final String symbol;
+
+ Operator(String sqlOperator, String symbol) {
+ this.sqlOperator = sqlOperator;
+ this.symbol = symbol;
+ }
+ }
+
+ private final List<Expression> children;
+
+ public Expression(List<Expression> children) {
+ this.children = children;
+ }
+
+ /**
+ * Traverses the expression with the provided {@link ExpressionVisitor}
+ */
+ public abstract <T> T accept(ExpressionVisitor<T> exprVisitor);
+}
diff --git a/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/expression/ExpressionVisitor.java b/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/expression/ExpressionVisitor.java
new file mode 100644
index 00000000000..9f6ea7b1597
--- /dev/null
+++ b/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/expression/ExpressionVisitor.java
@@ -0,0 +1,31 @@
+/*
+ * 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.expression;
+
+/**
+ * Visitor used to travers the expression.
+ */
+public interface ExpressionVisitor<T> {
+
+ T visitBinaryOperator(BinaryOperator binaryOperator);
+
+ T visitLiteral(Literal literal);
+
+ T visitAttribute(AttributeReferenceExpression attribute);
+}
diff --git a/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/expression/LeafExpression.java b/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/expression/LeafExpression.java
new file mode 100644
index 00000000000..318a79116ca
--- /dev/null
+++ b/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/expression/LeafExpression.java
@@ -0,0 +1,29 @@
+/*
+ * 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.expression;
+
+/**
+ * Expression that without any child expressions.
+ */
+public abstract class LeafExpression extends Expression {
+
+ public LeafExpression() {
+ super(null);
+ }
+}
diff --git a/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/expression/Literal.java b/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/expression/Literal.java
new file mode 100644
index 00000000000..f84756a6a85
--- /dev/null
+++ b/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/expression/Literal.java
@@ -0,0 +1,43 @@
+/*
+ * 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.expression;
+
+public class Literal extends LeafExpression {
+
+ private final String value;
+ private final String type;
+
+ public Literal(String value, String type) {
+ this.value = value;
+ this.type = type;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ @Override
+ public <T> T accept(ExpressionVisitor<T> exprVisitor) {
+ return exprVisitor.visitLiteral(this);
+ }
+}
diff --git a/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/util/FilterGenVisitor.java b/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/util/FilterGenVisitor.java
new file mode 100644
index 00000000000..f1d4724cc1b
--- /dev/null
+++ b/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/util/FilterGenVisitor.java
@@ -0,0 +1,119 @@
+/*
+ * 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.AttributeReferenceExpression;
+import org.apache.hudi.hive.expression.BinaryOperator;
+import org.apache.hudi.hive.expression.Expression;
+import org.apache.hudi.hive.expression.ExpressionVisitor;
+import org.apache.hudi.hive.expression.Literal;
+
+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");
+ }
+ }
+
+ private String visitAnd(Expression left, Expression right) {
+ String leftResult = left.accept(this);
+ String rightResult = right.accept(this);
+
+ if (leftResult.isEmpty()) {
+ if (rightResult.isEmpty()) {
+ return "";
+ }
+
+ return rightResult;
+ } else if (rightResult.isEmpty()) {
+ return leftResult;
+ }
+
+ return "(" + makeBinaryOperatorString(leftResult, Expression.Operator.AND, rightResult) + ")";
+ }
+
+ private String visitOr(Expression left, Expression right) {
+ String leftResult = left.accept(this);
+ String rightResult = right.accept(this);
+
+ if (!leftResult.isEmpty() && !rightResult.isEmpty()) {
+ return "(" + makeBinaryOperatorString(leftResult, Expression.Operator.OR, rightResult) + ")";
+ }
+ return "";
+ }
+
+ private String visitBinaryComparator(Expression left, Expression.Operator operator, Expression right) {
+ String leftResult = left.accept(this);
+ String rightResult = right.accept(this);
+
+ if (!leftResult.isEmpty() && !rightResult.isEmpty()) {
+ return makeBinaryOperatorString(leftResult, operator, rightResult);
+ }
+
+ return "";
+ }
+
+ @Override
+ public String visitBinaryOperator(BinaryOperator expr) {
+ switch (expr.getOperator()) {
+ case AND:
+ return visitAnd(expr.getLeft(), expr.getRight());
+ case OR:
+ return visitOr(expr.getLeft(), expr.getRight());
+ case EQ:
+ case GT:
+ case LT:
+ case GT_EQ:
+ case LT_EQ:
+ return visitBinaryComparator(expr.getLeft(), expr.getOperator(), expr.getRight());
+ default:
+ return "";
+ }
+ }
+
+ @Override
+ public String visitLiteral(Literal literalExpr) {
+ switch (literalExpr.getType().toLowerCase(Locale.ROOT)) {
+ case HiveSchemaUtil.STRING_TYPE_NAME:
+ return quoteStringLiteral(literalExpr.getValue());
+ case HiveSchemaUtil.INT_TYPE_NAME:
+ case HiveSchemaUtil.BIGINT_TYPE_NAME:
+ case HiveSchemaUtil.DATE_TYPE_NAME:
+ return literalExpr.getValue();
+ default:
+ return "";
+ }
+ }
+
+ @Override
+ public String visitAttribute(AttributeReferenceExpression attribute) {
+ return attribute.getName();
+ }
+}
diff --git a/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/util/HiveSchemaUtil.java b/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/util/HiveSchemaUtil.java
index 50a6aabd2bb..3309b24f758 100644
--- a/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/util/HiveSchemaUtil.java
+++ b/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/util/HiveSchemaUtil.java
@@ -56,6 +56,15 @@ public class HiveSchemaUtil {
private static final Logger LOG = LogManager.getLogger(HiveSchemaUtil.class);
public static final String HIVE_ESCAPE_CHARACTER = "`";
+ public static final String BOOLEAN_TYPE_NAME = "boolean";
+ public static final String INT_TYPE_NAME = "int";
+ public static final String BIGINT_TYPE_NAME = "bigint";
+ public static final String FLOAT_TYPE_NAME = "float";
+ public static final String DOUBLE_TYPE_NAME = "double";
+ public static final String STRING_TYPE_NAME = "string";
+ public static final String BINARY_TYPE_NAME = "binary";
+ public static final String DATE_TYPE_NAME = "date";
+
/**
* Get the schema difference between the storage schema and hive table schema.
*/
@@ -238,17 +247,17 @@ public class HiveSchemaUtil {
return parquetPrimitiveTypeName.convert(new PrimitiveType.PrimitiveTypeNameConverter<String, RuntimeException>() {
@Override
public String convertBOOLEAN(PrimitiveType.PrimitiveTypeName primitiveTypeName) {
- return "boolean";
+ return BOOLEAN_TYPE_NAME;
}
@Override
public String convertINT32(PrimitiveType.PrimitiveTypeName primitiveTypeName) {
- return "int";
+ return INT_TYPE_NAME;
}
@Override
public String convertINT64(PrimitiveType.PrimitiveTypeName primitiveTypeName) {
- return "bigint";
+ return BIGINT_TYPE_NAME;
}
@Override
@@ -258,25 +267,25 @@ public class HiveSchemaUtil {
@Override
public String convertFLOAT(PrimitiveType.PrimitiveTypeName primitiveTypeName) {
- return "float";
+ return FLOAT_TYPE_NAME;
}
@Override
public String convertDOUBLE(PrimitiveType.PrimitiveTypeName primitiveTypeName) {
- return "double";
+ return DOUBLE_TYPE_NAME;
}
@Override
public String convertFIXED_LEN_BYTE_ARRAY(PrimitiveType.PrimitiveTypeName primitiveTypeName) {
- return "binary";
+ return BINARY_TYPE_NAME;
}
@Override
public String convertBINARY(PrimitiveType.PrimitiveTypeName primitiveTypeName) {
if (originalType == OriginalType.UTF8 || originalType == OriginalType.ENUM) {
- return "string";
+ return STRING_TYPE_NAME;
} else {
- return "binary";
+ return BINARY_TYPE_NAME;
}
}
});
@@ -314,7 +323,7 @@ public class HiveSchemaUtil {
return createHiveMap(convertField(keyType, supportTimestamp, doFormat), convertField(valueType, supportTimestamp, doFormat), doFormat);
case ENUM:
case UTF8:
- return "string";
+ return STRING_TYPE_NAME;
case MAP_KEY_VALUE:
// MAP_KEY_VALUE was supposed to be used to annotate key and
// value group levels in a
@@ -420,9 +429,9 @@ public class HiveSchemaUtil {
newType = newType.toLowerCase();
if (prevType.equals(newType)) {
return true;
- } else if (prevType.equalsIgnoreCase("int") && newType.equalsIgnoreCase("bigint")) {
+ } else if (prevType.equalsIgnoreCase(INT_TYPE_NAME) && newType.equalsIgnoreCase(BIGINT_TYPE_NAME)) {
return true;
- } else if (prevType.equalsIgnoreCase("float") && newType.equalsIgnoreCase("double")) {
+ } else if (prevType.equalsIgnoreCase(FLOAT_TYPE_NAME) && newType.equalsIgnoreCase(DOUBLE_TYPE_NAME)) {
return true;
} else {
return prevType.contains("struct") && newType.toLowerCase().contains("struct");
@@ -516,6 +525,6 @@ public class HiveSchemaUtil {
// Default the unknown partition fields to be String
// TODO - all partition fields should be part of the schema. datestr is treated as special.
// Dont do that
- return "String";
+ return STRING_TYPE_NAME;
}
}
diff --git a/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/util/PartitionFilterGenerator.java b/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/util/PartitionFilterGenerator.java
new file mode 100644
index 00000000000..8202408d8bd
--- /dev/null
+++ b/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/util/PartitionFilterGenerator.java
@@ -0,0 +1,212 @@
+/*
+ * 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.AttributeReferenceExpression;
+import org.apache.hudi.hive.expression.BinaryOperator;
+import org.apache.hudi.hive.expression.Expression;
+import org.apache.hudi.hive.expression.Literal;
+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.Objects;
+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 {
+
+ private static final Set<String> SUPPORT_TYPES = new HashSet<String>() {
+ {
+ add(HiveSchemaUtil.INT_TYPE_NAME);
+ add(HiveSchemaUtil.BIGINT_TYPE_NAME);
+ add(HiveSchemaUtil.DATE_TYPE_NAME);
+ add(HiveSchemaUtil.STRING_TYPE_NAME);
+ }
+ };
+
+ /**
+ * Build expression from the Partition list. Here we're trying to match all partitions.
+ *
+ * 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 exp = BinaryOperator.eq(new AttributeReferenceExpression(field.getName()),
+ new Literal(value, field.getType()));
+ if (root != null) {
+ root = BinaryOperator.and(root, exp);
+ } else {
+ root = exp;
+ }
+ }
+ return root;
+ }).reduce(null, (result, expr) -> {
+ if (result == null) {
+ return expr;
+ } else {
+ return 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;
+ }
+
+ /**
+ * As HMS only accept DATE, INT, STRING, BIGINT to push down partition filters, here we only
+ * do the comparison for these types.
+ */
+ @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);
+ return Long.signum(l1 - l2);
+ case HiveSchemaUtil.DATE_TYPE_NAME:
+ case HiveSchemaUtil.STRING_TYPE_NAME:
+ return s1.compareTo(s2);
+ default:
+ throw new IllegalArgumentException("The value type: " + valueType + " doesn't support to "
+ + "be pushed down to HMS, acceptable types: " + String.join(",", SUPPORT_TYPES));
+ }
+ }
+ }
+
+ /**
+ * 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();
+
+ if (!SUPPORT_TYPES.contains(fieldSchema.getType())) {
+ return null;
+ }
+
+ String[] values = fieldWithValues.getValue();
+
+ if (values.length == 1) {
+ return BinaryOperator.eq(new AttributeReferenceExpression(fieldSchema.getName()),
+ new Literal(values[0], fieldSchema.getType()));
+ }
+
+ Arrays.sort(values, new ValueComparator(fieldSchema.getType()));
+
+ return BinaryOperator.and(
+ BinaryOperator.gteq(
+ new AttributeReferenceExpression(fieldSchema.getName()),
+ new Literal(values[0], fieldSchema.getType())),
+ BinaryOperator.lteq(
+ new AttributeReferenceExpression(fieldSchema.getName()),
+ new Literal(values[values.length - 1], fieldSchema.getType())));
+ })
+ .filter(Objects::nonNull)
+ .reduce(null, (result, expr) -> {
+ if (result == null) {
+ return expr;
+ } else {
+ return BinaryOperator.and(result, expr);
+ }
+ });
+ }
+
+ public static String generatePushDownFilter(List<String> writtenPartitions, List<FieldSchema> partitionFields, HiveSyncConfig config) {
+ PartitionValueExtractor partitionValueExtractor = ReflectionUtils
+ .loadClass(config.getStringOrDefault(META_SYNC_PARTITION_EXTRACTOR_CLASS));
+
+ List<Partition> partitions = writtenPartitions.stream().map(s -> {
+ List<String> values = partitionValueExtractor.extractPartitionValuesInPath(s);
+
+ if (values.size() != partitionFields.size()) {
+ throw new HoodieHiveSyncException("Partition fields and values should be same length"
+ + ", but got partitionFields: " + partitionFields + " with values: " + values);
+ }
+
+ return new Partition(values, null);
+ }).collect(Collectors.toList());
+
+ Expression filter;
+ int estimateSize = partitionFields.size() * partitions.size();
+ if (estimateSize > config.getIntOrDefault(HIVE_SYNC_FILTER_PUSHDOWN_MAX_SIZE)) {
+ filter = buildMinMaxPartitionExpression(partitions, partitionFields);
+ } else {
+ filter = buildPartitionExpression(partitions, partitionFields);
+ }
+
+ if (filter != null) {
+ return generateFilterString(filter);
+ }
+
+ return "";
+ }
+
+ private static String generateFilterString(Expression filter) {
+ return filter.accept(new FilterGenVisitor());
+ }
+}
diff --git a/hudi-sync/hudi-hive-sync/src/test/java/org/apache/hudi/hive/TestHiveSyncTool.java b/hudi-sync/hudi-hive-sync/src/test/java/org/apache/hudi/hive/TestHiveSyncTool.java
index 98c40c3e0bc..1096a02d560 100644
--- a/hudi-sync/hudi-hive-sync/src/test/java/org/apache/hudi/hive/TestHiveSyncTool.java
+++ b/hudi-sync/hudi-hive-sync/src/test/java/org/apache/hudi/hive/TestHiveSyncTool.java
@@ -62,6 +62,7 @@ import java.util.Set;
import java.util.stream.Collectors;
import static org.apache.hudi.common.fs.FSUtils.getRelativePartitionPath;
+import static org.apache.hudi.hive.HiveSyncConfig.HIVE_SYNC_FILTER_PUSHDOWN_ENABLED;
import static org.apache.hudi.hive.HiveSyncConfigHolder.HIVE_AUTO_CREATE_DATABASE;
import static org.apache.hudi.hive.HiveSyncConfigHolder.HIVE_CREATE_MANAGED_TABLE;
import static org.apache.hudi.hive.HiveSyncConfigHolder.HIVE_IGNORE_EXCEPTIONS;
@@ -97,12 +98,24 @@ public class TestHiveSyncTool {
return SYNC_MODES;
}
- // useSchemaFromCommitMetadata, syncMode
+ // syncMode, enablePushDown
+ private static Iterable<Object[]> syncModeAndEnablePushDown() {
+ List<Object[]> opts = new ArrayList<>();
+ for (Object mode : SYNC_MODES) {
+ opts.add(new Object[] {mode, "true"});
+ opts.add(new Object[] {mode, "false"});
+ }
+ return opts;
+ }
+
+ // useSchemaFromCommitMetadata, syncMode, enablePushDown
private static Iterable<Object[]> syncModeAndSchemaFromCommitMetadata() {
List<Object[]> opts = new ArrayList<>();
for (Object mode : SYNC_MODES) {
- opts.add(new Object[] {true, mode});
- opts.add(new Object[] {false, mode});
+ opts.add(new Object[] {true, mode, "true"});
+ opts.add(new Object[] {false, mode, "true"});
+ opts.add(new Object[] {true, mode, "false"});
+ opts.add(new Object[] {false, mode, "false"});
}
return opts;
}
@@ -115,21 +128,26 @@ public class TestHiveSyncTool {
HiveTestUtil.shutdown();
}
+ // (useSchemaFromCommitMetadata, isManagedTable, syncMode, enablePushDown)
private static Iterable<Object[]> syncModeAndSchemaFromCommitMetadataAndManagedTable() {
List<Object[]> opts = new ArrayList<>();
for (Object mode : SYNC_MODES) {
- opts.add(new Object[] {true, true, mode});
- opts.add(new Object[] {false, false, mode});
+ opts.add(new Object[] {true, true, mode, "true"});
+ opts.add(new Object[] {false, false, mode, "true"});
+ opts.add(new Object[] {true, true, mode, "false"});
+ opts.add(new Object[] {false, false, mode, "false"});
}
return opts;
}
- // (useJdbc, useSchemaFromCommitMetadata, syncAsDataSource)
+ // (useJdbc, useSchemaFromCommitMetadata, syncAsDataSource, enablePushDown)
private static Iterable<Object[]> syncDataSourceTableParams() {
List<Object[]> opts = new ArrayList<>();
for (Object mode : SYNC_MODES) {
- opts.add(new Object[] {true, true, mode});
- opts.add(new Object[] {false, false, mode});
+ opts.add(new Object[] {true, true, mode, "true"});
+ opts.add(new Object[] {false, false, mode, "true"});
+ opts.add(new Object[] {true, true, mode, "false"});
+ opts.add(new Object[] {false, false, mode, "false"});
}
return opts;
}
@@ -146,8 +164,9 @@ public class TestHiveSyncTool {
@ParameterizedTest
@MethodSource({"syncModeAndSchemaFromCommitMetadata"})
- public void testBasicSync(boolean useSchemaFromCommitMetadata, String syncMode) throws Exception {
+ public void testBasicSync(boolean useSchemaFromCommitMetadata, String syncMode, String enablePushDown) throws Exception {
hiveSyncProps.setProperty(HIVE_SYNC_MODE.key(), syncMode);
+ hiveSyncProps.setProperty(HIVE_SYNC_FILTER_PUSHDOWN_ENABLED.key(), enablePushDown);
String instantTime = "100";
HiveTestUtil.createCOWTable(instantTime, 5, useSchemaFromCommitMetadata);
@@ -253,7 +272,8 @@ public class TestHiveSyncTool {
@MethodSource({"syncDataSourceTableParams"})
public void testSyncCOWTableWithProperties(boolean useSchemaFromCommitMetadata,
boolean syncAsDataSourceTable,
- String syncMode) throws Exception {
+ String syncMode,
+ String enablePushDown) throws Exception {
Map<String, String> serdeProperties = new HashMap<String, String>() {
{
put("path", HiveTestUtil.basePath);
@@ -270,6 +290,7 @@ public class TestHiveSyncTool {
hiveSyncProps.setProperty(HIVE_SYNC_AS_DATA_SOURCE_TABLE.key(), String.valueOf(syncAsDataSourceTable));
hiveSyncProps.setProperty(HIVE_TABLE_SERDE_PROPERTIES.key(), ConfigUtils.configToString(serdeProperties));
hiveSyncProps.setProperty(HIVE_TABLE_PROPERTIES.key(), ConfigUtils.configToString(tableProperties));
+ hiveSyncProps.setProperty(HIVE_SYNC_FILTER_PUSHDOWN_ENABLED.key(), enablePushDown);
String instantTime = "100";
HiveTestUtil.createCOWTable(instantTime, 5, useSchemaFromCommitMetadata);
@@ -345,7 +366,8 @@ public class TestHiveSyncTool {
@MethodSource({"syncDataSourceTableParams"})
public void testSyncMORTableWithProperties(boolean useSchemaFromCommitMetadata,
boolean syncAsDataSourceTable,
- String syncMode) throws Exception {
+ String syncMode,
+ String enablePushDown) throws Exception {
Map<String, String> serdeProperties = new HashMap<String, String>() {
{
put("path", HiveTestUtil.basePath);
@@ -362,6 +384,7 @@ public class TestHiveSyncTool {
hiveSyncProps.setProperty(HIVE_SYNC_AS_DATA_SOURCE_TABLE.key(), String.valueOf(syncAsDataSourceTable));
hiveSyncProps.setProperty(HIVE_TABLE_SERDE_PROPERTIES.key(), ConfigUtils.configToString(serdeProperties));
hiveSyncProps.setProperty(HIVE_TABLE_PROPERTIES.key(), ConfigUtils.configToString(tableProperties));
+ hiveSyncProps.setProperty(HIVE_SYNC_FILTER_PUSHDOWN_ENABLED.key(), enablePushDown);
String instantTime = "100";
String deltaCommitTime = "101";
@@ -417,9 +440,11 @@ public class TestHiveSyncTool {
@MethodSource({"syncModeAndSchemaFromCommitMetadataAndManagedTable"})
public void testSyncManagedTable(boolean useSchemaFromCommitMetadata,
boolean isManagedTable,
- String syncMode) throws Exception {
+ String syncMode,
+ String enablePushDown) throws Exception {
hiveSyncProps.setProperty(HIVE_SYNC_MODE.key(), syncMode);
hiveSyncProps.setProperty(HIVE_CREATE_MANAGED_TABLE.key(), String.valueOf(isManagedTable));
+ hiveSyncProps.setProperty(HIVE_SYNC_FILTER_PUSHDOWN_ENABLED.key(), enablePushDown);
String instantTime = "100";
HiveTestUtil.createCOWTable(instantTime, 5, useSchemaFromCommitMetadata);
@@ -444,9 +469,11 @@ public class TestHiveSyncTool {
}
@ParameterizedTest
- @MethodSource("syncMode")
- public void testSyncWithSchema(String syncMode) throws Exception {
+ @MethodSource("syncModeAndEnablePushDown")
+ public void testSyncWithSchema(String syncMode, String enablePushDown) throws Exception {
hiveSyncProps.setProperty(HIVE_SYNC_MODE.key(), syncMode);
+ hiveSyncProps.setProperty(HIVE_SYNC_FILTER_PUSHDOWN_ENABLED.key(), enablePushDown);
+
String commitTime = "100";
HiveTestUtil.createCOWTableWithSchema(commitTime, "/complex.schema.avsc");
@@ -459,9 +486,11 @@ public class TestHiveSyncTool {
}
@ParameterizedTest
- @MethodSource("syncMode")
- public void testSyncIncremental(String syncMode) throws Exception {
+ @MethodSource("syncModeAndEnablePushDown")
+ public void testSyncIncremental(String syncMode, String enablePushDown) throws Exception {
hiveSyncProps.setProperty(HIVE_SYNC_MODE.key(), syncMode);
+ hiveSyncProps.setProperty(HIVE_SYNC_FILTER_PUSHDOWN_ENABLED.key(), enablePushDown);
+
String commitTime1 = "100";
HiveTestUtil.createCOWTable(commitTime1, 5, true);
reinitHiveSyncClient();
@@ -494,9 +523,11 @@ public class TestHiveSyncTool {
}
@ParameterizedTest
- @MethodSource("syncMode")
- public void testSyncIncrementalWithSchemaEvolution(String syncMode) throws Exception {
+ @MethodSource("syncModeAndEnablePushDown")
+ public void testSyncIncrementalWithSchemaEvolution(String syncMode, String enablePushDown) throws Exception {
hiveSyncProps.setProperty(HIVE_SYNC_MODE.key(), syncMode);
+ hiveSyncProps.setProperty(HIVE_SYNC_FILTER_PUSHDOWN_ENABLED.key(), enablePushDown);
+
String commitTime1 = "100";
HiveTestUtil.createCOWTable(commitTime1, 5, true);
reinitHiveSyncClient();
@@ -595,8 +626,10 @@ public class TestHiveSyncTool {
@ParameterizedTest
@MethodSource("syncModeAndSchemaFromCommitMetadata")
- public void testSyncMergeOnRead(boolean useSchemaFromCommitMetadata, String syncMode) throws Exception {
+ public void testSyncMergeOnRead(boolean useSchemaFromCommitMetadata, String syncMode, String enablePushDown) throws Exception {
hiveSyncProps.setProperty(HIVE_SYNC_MODE.key(), syncMode);
+ hiveSyncProps.setProperty(HIVE_SYNC_FILTER_PUSHDOWN_ENABLED.key(), enablePushDown);
+
String instantTime = "100";
String deltaCommitTime = "101";
HiveTestUtil.createMORTable(instantTime, deltaCommitTime, 5, true,
@@ -659,8 +692,10 @@ public class TestHiveSyncTool {
@ParameterizedTest
@MethodSource("syncModeAndSchemaFromCommitMetadata")
- public void testSyncMergeOnReadRT(boolean useSchemaFromCommitMetadata, String syncMode) throws Exception {
+ public void testSyncMergeOnReadRT(boolean useSchemaFromCommitMetadata, String syncMode, String enablePushDown) throws Exception {
hiveSyncProps.setProperty(HIVE_SYNC_MODE.key(), syncMode);
+ hiveSyncProps.setProperty(HIVE_SYNC_FILTER_PUSHDOWN_ENABLED.key(), enablePushDown);
+
String instantTime = "100";
String deltaCommitTime = "101";
String snapshotTableName = HiveTestUtil.TABLE_NAME + HiveSyncTool.SUFFIX_SNAPSHOT_TABLE;
@@ -724,9 +759,11 @@ public class TestHiveSyncTool {
}
@ParameterizedTest
- @MethodSource("syncMode")
- public void testMultiPartitionKeySync(String syncMode) throws Exception {
+ @MethodSource("syncModeAndEnablePushDown")
+ public void testMultiPartitionKeySync(String syncMode, String enablePushDown) throws Exception {
hiveSyncProps.setProperty(HIVE_SYNC_MODE.key(), syncMode);
+ hiveSyncProps.setProperty(HIVE_SYNC_FILTER_PUSHDOWN_ENABLED.key(), enablePushDown);
+
String instantTime = "100";
HiveTestUtil.createCOWTable(instantTime, 5, true);
@@ -791,9 +828,10 @@ public class TestHiveSyncTool {
}
@ParameterizedTest
- @MethodSource("syncMode")
- public void testDropPartitionKeySync(String syncMode) throws Exception {
+ @MethodSource("syncModeAndEnablePushDown")
+ public void testDropPartitionKeySync(String syncMode, String enablePushDown) throws Exception {
hiveSyncProps.setProperty(HIVE_SYNC_MODE.key(), syncMode);
+ hiveSyncProps.setProperty(HIVE_SYNC_FILTER_PUSHDOWN_ENABLED.key(), enablePushDown);
String instantTime = "100";
HiveTestUtil.createCOWTable(instantTime, 1, true);
@@ -835,9 +873,10 @@ public class TestHiveSyncTool {
}
@ParameterizedTest
- @MethodSource("syncMode")
- public void testDropPartition(String syncMode) throws Exception {
+ @MethodSource("syncModeAndEnablePushDown")
+ public void testDropPartition(String syncMode, String enablePushDown) throws Exception {
hiveSyncProps.setProperty(HIVE_SYNC_MODE.key(), syncMode);
+ hiveSyncProps.setProperty(HIVE_SYNC_FILTER_PUSHDOWN_ENABLED.key(), enablePushDown);
String instantTime = "100";
HiveTestUtil.createCOWTable(instantTime, 1, true);
@@ -887,9 +926,11 @@ public class TestHiveSyncTool {
}
@ParameterizedTest
- @MethodSource("syncMode")
- public void testNonPartitionedSync(String syncMode) throws Exception {
+ @MethodSource("syncModeAndEnablePushDown")
+ public void testNonPartitionedSync(String syncMode, String enablePushDown) throws Exception {
hiveSyncProps.setProperty(HIVE_SYNC_MODE.key(), syncMode);
+ hiveSyncProps.setProperty(HIVE_SYNC_FILTER_PUSHDOWN_ENABLED.key(), enablePushDown);
+
String instantTime = "100";
HiveTestUtil.createCOWTable(instantTime, 5, true);
// Set partition value extractor to NonPartitionedExtractor
@@ -913,9 +954,11 @@ public class TestHiveSyncTool {
}
@ParameterizedTest
- @MethodSource("syncMode")
- public void testReadSchemaForMOR(String syncMode) throws Exception {
+ @MethodSource("syncModeAndEnablePushDown")
+ public void testReadSchemaForMOR(String syncMode, String enablePushDown) throws Exception {
hiveSyncProps.setProperty(HIVE_SYNC_MODE.key(), syncMode);
+ hiveSyncProps.setProperty(HIVE_SYNC_FILTER_PUSHDOWN_ENABLED.key(), enablePushDown);
+
String commitTime = "100";
String snapshotTableName = HiveTestUtil.TABLE_NAME + HiveSyncTool.SUFFIX_SNAPSHOT_TABLE;
HiveTestUtil.createMORTable(commitTime, "", 5, false, true);
diff --git a/hudi-sync/hudi-hive-sync/src/test/java/org/apache/hudi/hive/util/TestPartitionFilterGenerator.java b/hudi-sync/hudi-hive-sync/src/test/java/org/apache/hudi/hive/util/TestPartitionFilterGenerator.java
new file mode 100644
index 00000000000..7488709aca6
--- /dev/null
+++ b/hudi-sync/hudi-hive-sync/src/test/java/org/apache/hudi/hive/util/TestPartitionFilterGenerator.java
@@ -0,0 +1,134 @@
+/*
+ * 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.HiveSyncConfig;
+import org.apache.hudi.sync.common.model.FieldSchema;
+import org.junit.jupiter.api.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Properties;
+
+import static org.apache.hudi.hive.HiveSyncConfig.HIVE_SYNC_FILTER_PUSHDOWN_MAX_SIZE;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+public class TestPartitionFilterGenerator {
+
+ @Test
+ public void testPushDownFilters() {
+ Properties props = new Properties();
+ HiveSyncConfig config = new HiveSyncConfig(props);
+ List<FieldSchema> partitionFieldSchemas = new ArrayList<>(4);
+ partitionFieldSchemas.add(new FieldSchema("date", "date"));
+ partitionFieldSchemas.add(new FieldSchema("year", "string"));
+ partitionFieldSchemas.add(new FieldSchema("month", "int"));
+ partitionFieldSchemas.add(new FieldSchema("day", "bigint"));
+
+ List<String> writtenPartitions = new ArrayList<>();
+ writtenPartitions.add("2022-09-01/2022/9/1");
+
+ assertEquals("(((date = 2022-09-01 AND year = \"2022\") AND month = 9) AND day = 1)",
+ PartitionFilterGenerator.generatePushDownFilter(writtenPartitions, partitionFieldSchemas, config));
+
+ writtenPartitions.add("2022-09-02/2022/9/2");
+ assertEquals(
+ "((((date = 2022-09-01 AND year = \"2022\") AND month = 9) AND day = 1) OR (((date = 2022-09-02 AND year = \"2022\") AND month = 9) AND day = 2))",
+ PartitionFilterGenerator.generatePushDownFilter(writtenPartitions, partitionFieldSchemas, config));
+
+ // If there are incompatible types to convert as filters inside partition
+ partitionFieldSchemas.clear();
+ writtenPartitions.clear();
+ partitionFieldSchemas.add(new FieldSchema("date", "date"));
+ partitionFieldSchemas.add(new FieldSchema("finished", "boolean"));
+
+ writtenPartitions.add("2022-09-01/true");
+ assertEquals("date = 2022-09-01",
+ PartitionFilterGenerator.generatePushDownFilter(writtenPartitions, partitionFieldSchemas, config));
+ writtenPartitions.add("2022-09-02/true");
+ assertEquals("(date = 2022-09-01 OR date = 2022-09-02)",
+ PartitionFilterGenerator.generatePushDownFilter(writtenPartitions, partitionFieldSchemas, config));
+
+ // If no compatible types matched to convert as filters
+ partitionFieldSchemas.clear();
+ writtenPartitions.clear();
+ partitionFieldSchemas.add(new FieldSchema("finished", "boolean"));
+
+ writtenPartitions.add("true");
+ assertEquals("",
+ PartitionFilterGenerator.generatePushDownFilter(writtenPartitions, partitionFieldSchemas, config));
+ writtenPartitions.add("false");
+ assertEquals("",
+ PartitionFilterGenerator.generatePushDownFilter(writtenPartitions, partitionFieldSchemas, config));
+ }
+
+ @Test
+ public void testPushDownFilterIfExceedLimit() {
+ Properties props = new Properties();
+ props.put(HIVE_SYNC_FILTER_PUSHDOWN_MAX_SIZE.key(), "0");
+ HiveSyncConfig config = new HiveSyncConfig(props);
+ List<FieldSchema> partitionFieldSchemas = new ArrayList<>(4);
+ partitionFieldSchemas.add(new FieldSchema("date", "date"));
+ partitionFieldSchemas.add(new FieldSchema("year", "string"));
+ partitionFieldSchemas.add(new FieldSchema("month", "int"));
+ partitionFieldSchemas.add(new FieldSchema("day", "bigint"));
+
+ List<String> writtenPartitions = new ArrayList<>();
+ writtenPartitions.add("2022-09-01/2022/9/1");
+
+ assertEquals("(((date = 2022-09-01 AND year = \"2022\") AND month = 9) AND day = 1)",
+ PartitionFilterGenerator.generatePushDownFilter(writtenPartitions, partitionFieldSchemas, config));
+
+ writtenPartitions.add("2022-09-02/2022/9/2");
+ writtenPartitions.add("2022-09-03/2022/9/2");
+ writtenPartitions.add("2022-09-04/2022/9/2");
+ assertEquals(
+ "((((date >= 2022-09-01 AND date <= 2022-09-04) AND year = \"2022\") AND month = 9) AND (day >= 1 AND day <= 2))",
+ PartitionFilterGenerator.generatePushDownFilter(writtenPartitions, partitionFieldSchemas, config));
+
+ // If there are incompatible types to convert as filters inside partition
+ partitionFieldSchemas.clear();
+ writtenPartitions.clear();
+ partitionFieldSchemas.add(new FieldSchema("date", "date"));
+ partitionFieldSchemas.add(new FieldSchema("finished", "boolean"));
+
+ writtenPartitions.add("2022-09-01/true");
+ assertEquals("date = 2022-09-01",
+ PartitionFilterGenerator.generatePushDownFilter(writtenPartitions, partitionFieldSchemas, config));
+ writtenPartitions.add("2022-09-02/true");
+ writtenPartitions.add("2022-09-03/false");
+ writtenPartitions.add("2022-09-04/false");
+ assertEquals("(date >= 2022-09-01 AND date <= 2022-09-04)",
+ PartitionFilterGenerator.generatePushDownFilter(writtenPartitions, partitionFieldSchemas, config));
+
+ // If no compatible types matched to convert as filters
+ partitionFieldSchemas.clear();
+ writtenPartitions.clear();
+ partitionFieldSchemas.add(new FieldSchema("finished", "boolean"));
+
+ writtenPartitions.add("true");
+ assertEquals("",
+ PartitionFilterGenerator.generatePushDownFilter(writtenPartitions, partitionFieldSchemas, config));
+ writtenPartitions.add("false");
+ writtenPartitions.add("false");
+ writtenPartitions.add("false");
+ assertEquals("",
+ PartitionFilterGenerator.generatePushDownFilter(writtenPartitions, partitionFieldSchemas, config));
+ }
+}
diff --git a/hudi-sync/hudi-sync-common/src/main/java/org/apache/hudi/sync/common/HoodieMetaSyncOperations.java b/hudi-sync/hudi-sync-common/src/main/java/org/apache/hudi/sync/common/HoodieMetaSyncOperations.java
index 933c05e20d9..b6875757652 100644
--- a/hudi-sync/hudi-sync-common/src/main/java/org/apache/hudi/sync/common/HoodieMetaSyncOperations.java
+++ b/hudi-sync/hudi-sync-common/src/main/java/org/apache/hudi/sync/common/HoodieMetaSyncOperations.java
@@ -96,6 +96,15 @@ public interface HoodieMetaSyncOperations {
return Collections.emptyList();
}
+ /**
+ * Get the metadata of partitions that belong to the specified table
+ * @param tableName
+ * @return
+ */
+ default List<Partition> getPartitionsByFilter(String tableName, String filter) {
+ return Collections.emptyList();
+ }
+
/**
* Check if a database already exists in the metastore.
*/