You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@asterixdb.apache.org by AsterixDB Code Review <do...@asterix-gerrit.ics.uci.edu> on 2026/09/20 17:19:55 UTC
[XL] Change in asterixdb[master]: [ASTERIXDB-3873][EXT]: Bind Parquet filter to file
From Hussain Towaileb <hu...@gmail.com>:
Hussain Towaileb has uploaded this change for review. ( https://asterix-gerrit.ics.uci.edu/c/asterixdb/+/21853?usp=email )
Change subject: [ASTERIXDB-3873][EXT]: Bind Parquet filter to file
......................................................................
[ASTERIXDB-3873][EXT]: Bind Parquet filter to file
The row-group filter was set on the Hadoop configuration after that
configuration had already been serialized for the nodes, so every node
rebuilt one without it and read every row group of every file.
Building a typed predicate while compiling is not possible in any case:
a collection spans files whose schemas may disagree, and a column's
physical type decides which parquet-mr column a predicate has to name.
One built against the wrong column type is rejected when the file is
opened, failing the query over what is only an optimization. The filter
is now described without a physical type and bound to each file's own
schema as that file is opened, dropping any comparison the file cannot
support rather than pushing it. Row groups are eliminated and nothing
else: record-level and column-index filtering stay off, so which rows
match remains the engine's answer.
A rowGroupFilter option turns the whole mechanism off, defaulting to on.
Temporal literals are not pushed while a collection carries a timezone,
because the reader shifts what it reads into that zone and the literal
is not in the frame the file's statistics are in.
Two defects go with it: a comparison was built with its operands in the
order written, so a literal on the left inverted the predicate, and a
column path was flattened to a dotted string, which misresolves a field
whose own name contains one.
Added test cases covering the per-file binding and row-group
elimination.
Ext-ref: MB-74037
Co-Authored-By: Claude Opus 5 <no...@anthropic.com>
Change-Id: If36acc7c4df577499ffc6cfa4eaee5382acd4b8e
---
M asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/HDFSDataSourceFactory.java
A asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/filter/ParquetFilterConverter.java
M asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/filter/ParquetFilterEvaluatorFactory.java
A asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/filter/ParquetFilterExpression.java
M asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/aws/parquet/AwsS3ParquetReaderFactory.java
M asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/azure/parquet/AzureBlobParquetReaderFactory.java
M asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/azure/parquet/AzureDataLakeParquetReaderFactory.java
M asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/gcs/parquet/GCSParquetReaderFactory.java
M asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/hdfs/parquet/MapredParquetInputFormat.java
M asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/hdfs/parquet/ParquetFileRecordReader.java
M asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/hdfs/parquet/ParquetRecordReaderWrapper.java
M asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/util/ExternalDataConstants.java
M asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/util/ExternalDataUtils.java
A asterixdb/asterix-external-data/src/test/java/org/apache/asterix/external/input/filter/ParquetFilterConverterTest.java
M asterixdb/asterix-metadata/src/main/java/org/apache/asterix/metadata/utils/IndexUtil.java
M asterixdb/asterix-metadata/src/main/java/org/apache/asterix/metadata/utils/filter/ParquetFilterBuilder.java
16 files changed, 990 insertions(+), 126 deletions(-)
git pull ssh://asterix-gerrit.ics.uci.edu:29418/asterixdb refs/changes/53/21853/1
diff --git a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/HDFSDataSourceFactory.java b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/HDFSDataSourceFactory.java
index fc7ce6f..8a2b332 100644
--- a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/HDFSDataSourceFactory.java
+++ b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/HDFSDataSourceFactory.java
@@ -44,6 +44,8 @@
import org.apache.asterix.external.api.IExternalDataSourceFactory;
import org.apache.asterix.external.api.IRecordReader;
import org.apache.asterix.external.api.IRecordReaderFactory;
+import org.apache.asterix.external.input.filter.ParquetFilterEvaluatorFactory;
+import org.apache.asterix.external.input.filter.ParquetFilterExpression;
import org.apache.asterix.external.input.filter.embedder.IExternalFilterValueEmbedder;
import org.apache.asterix.external.input.record.reader.abstracts.AbstractExternalInputStreamFactory;
import org.apache.asterix.external.input.record.reader.hdfs.HDFSRecordReader;
@@ -358,7 +360,7 @@
readerConf = confFactory.getConf();
}
return createRecordReader(configuration, read, inputSplits, readSchedule, nodeName, readerConf, context,
- ugi);
+ ugi, rowGroupFilter());
} catch (Exception e) {
throw HyracksDataException.create(e);
}
@@ -381,12 +383,23 @@
return new ExternalStreamRuntimeDataContext(context, partition, valueEmbedder);
}
+ /**
+ * The row-group filter is handed to the reader rather than written into the {@link JobConf}, because the conf
+ * the node reads from is a snapshot taken in {@link #configureHdfsConf}; anything put into the live conf after
+ * that point never leaves the coordinator.
+ */
+ private ParquetFilterExpression rowGroupFilter() {
+ return filterEvaluatorFactory instanceof ParquetFilterEvaluatorFactory
+ ? ((ParquetFilterEvaluatorFactory) filterEvaluatorFactory).getFilterExpression() : null;
+ }
+
private static IRecordReader<?> createRecordReader(Map<String, String> configuration, boolean[] read,
InputSplit[] inputSplits, String[] readSchedule, String nodeName, JobConf conf,
- IExternalDataRuntimeContext context, UserGroupInformation ugi) {
+ IExternalDataRuntimeContext context, UserGroupInformation ugi, ParquetFilterExpression rowGroupFilter) {
if (configuration.get(ExternalDataConstants.KEY_INPUT_FORMAT).trim()
.equals(ExternalDataConstants.INPUT_FORMAT_PARQUET)) {
- return new ParquetFileRecordReader<>(read, inputSplits, readSchedule, nodeName, conf, context, ugi);
+ return new ParquetFileRecordReader<>(read, inputSplits, readSchedule, nodeName, conf, context, ugi,
+ rowGroupFilter);
} else if (configuration.get(ExternalDataConstants.KEY_INPUT_FORMAT).trim()
.equals(ExternalDataConstants.INPUT_FORMAT_AVRO)) {
return new AvroFileRecordReader<>(read, inputSplits, readSchedule, nodeName, conf, context, ugi);
diff --git a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/filter/ParquetFilterConverter.java b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/filter/ParquetFilterConverter.java
new file mode 100644
index 0000000..7a6224d
--- /dev/null
+++ b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/filter/ParquetFilterConverter.java
@@ -0,0 +1,302 @@
+/*
+ * 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.asterix.external.input.filter;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.asterix.external.input.filter.ParquetFilterExpression.Comparison;
+import org.apache.asterix.external.input.filter.ParquetFilterExpression.Operator;
+import org.apache.asterix.om.types.ATypeTag;
+import org.apache.hyracks.util.annotations.AiProvenance;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import org.apache.parquet.column.ColumnDescriptor;
+import org.apache.parquet.filter2.predicate.FilterApi;
+import org.apache.parquet.filter2.predicate.FilterPredicate;
+import org.apache.parquet.filter2.predicate.Operators;
+import org.apache.parquet.io.api.Binary;
+import org.apache.parquet.schema.LogicalTypeAnnotation;
+import org.apache.parquet.schema.MessageType;
+import org.apache.parquet.schema.PrimitiveType;
+
+/**
+ * Binds a {@link ParquetFilterExpression} to the schema of one Parquet file, producing the predicate parquet-mr
+ * uses to skip row groups.
+ * <p>
+ * Conversion is a best effort. Every comparison the file cannot support is dropped, never reported as an error:
+ * parquet-mr validates a predicate against the file's schema when the file is opened and throws if the column is
+ * repeated or if the predicate's type disagrees with the column's, which would fail the query over what is only
+ * an optimization. Dropping a comparison is always safe because the engine evaluates the predicate itself; the
+ * pushed filter only ever decides which row groups are worth reading.
+ */
+@AiProvenance(agent = AiProvenance.Agent.CLAUDE_OPUS_5, tool = AiProvenance.Tool.CLAUDE_CODE_UI, contributionKind = AiProvenance.ContributionKind.GENERATED, notes = "Per-file binding of the row-group filter to the file's own Parquet schema")
+public class ParquetFilterConverter {
+ private static final Logger LOGGER = LogManager.getLogger();
+
+ /** Beyond this magnitude a 64-bit integer is no longer exactly representable as a double. */
+ private static final long MAX_EXACT_DOUBLE = 1L << 53;
+
+ private ParquetFilterConverter() {
+ throw new AssertionError("do not instantiate");
+ }
+
+ /**
+ * @param fileSchema the schema of the file about to be read
+ * @param expression the filter built while compiling the query
+ * @return the predicate to push, or {@code null} when nothing in the filter applies to this file
+ */
+ public static FilterPredicate toParquetFilter(MessageType fileSchema, ParquetFilterExpression expression) {
+ if (fileSchema == null || expression == null) {
+ return null;
+ }
+ return convert(filterableColumns(fileSchema), expression);
+ }
+
+ /**
+ * The leaf columns a predicate may name, by path. Repeated columns are left out: parquet-mr rejects a
+ * predicate on one outright (PARQUET-34), and a column nested anywhere beneath a repeated group -- inside a
+ * list or a map -- carries a non-zero max repetition level.
+ */
+ private static Map<List<String>, PrimitiveType> filterableColumns(MessageType fileSchema) {
+ Map<List<String>, PrimitiveType> columns = new HashMap<>();
+ for (ColumnDescriptor column : fileSchema.getColumns()) {
+ if (column.getMaxRepetitionLevel() > 0) {
+ continue;
+ }
+ columns.put(Arrays.asList(column.getPath()), column.getPrimitiveType());
+ }
+ return columns;
+ }
+
+ private static FilterPredicate convert(Map<List<String>, PrimitiveType> columns,
+ ParquetFilterExpression expression) {
+ if (expression instanceof ParquetFilterExpression.And) {
+ ParquetFilterExpression.And and = (ParquetFilterExpression.And) expression;
+ FilterPredicate left = convert(columns, and.getLeft());
+ FilterPredicate right = convert(columns, and.getRight());
+ // a conjunct that cannot be pushed is simply not pushed; whatever survives still excludes row groups
+ if (left == null) {
+ return right;
+ } else if (right == null) {
+ return left;
+ }
+ return FilterApi.and(left, right);
+ } else if (expression instanceof ParquetFilterExpression.Or) {
+ ParquetFilterExpression.Or or = (ParquetFilterExpression.Or) expression;
+ FilterPredicate left = convert(columns, or.getLeft());
+ FilterPredicate right = convert(columns, or.getRight());
+ // a disjunct that cannot be pushed would keep row groups the other side excludes, so neither is kept
+ if (left == null || right == null) {
+ return null;
+ }
+ return FilterApi.or(left, right);
+ } else if (expression instanceof Comparison) {
+ return convertComparison(columns, (Comparison) expression);
+ }
+ return null;
+ }
+
+ private static FilterPredicate convertComparison(Map<List<String>, PrimitiveType> columns, Comparison comparison) {
+ PrimitiveType type = columns.get(Arrays.asList(comparison.getPath()));
+ if (type == null) {
+ // absent from this file, or repeated
+ return drop(comparison, "column is not a filterable column of this file");
+ }
+ for (String component : comparison.getPath()) {
+ if (component.indexOf('.') >= 0) {
+ // parquet-mr's column factories take a dotted string and split it on every '.', so a component
+ // containing one cannot be named through the public API. Spark reaches the package-private
+ // constructors through a shim it places in parquet's own package; that is not worth doing here.
+ return drop(comparison, "column path component contains a '.'");
+ }
+ }
+ String path = String.join(".", comparison.getPath());
+ LogicalTypeAnnotation annotation = type.getLogicalTypeAnnotation();
+ Operator operator = comparison.getOperator();
+ ATypeTag tag = comparison.getValueTag();
+ Object value = comparison.getValue();
+
+ switch (type.getPrimitiveTypeName()) {
+ case BOOLEAN:
+ if (annotation != null || tag != ATypeTag.BOOLEAN) {
+ return drop(comparison, "boolean column compared against " + tag);
+ } else if (operator != Operator.EQ) {
+ // parquet-mr orders booleans only for equality
+ return drop(comparison, "boolean column with operator " + operator);
+ }
+ return FilterApi.eq(FilterApi.booleanColumn(path), (Boolean) value);
+
+ case INT32:
+ if (annotation instanceof LogicalTypeAnnotation.DateLogicalTypeAnnotation) {
+ if (tag != ATypeTag.DATE) {
+ return drop(comparison, "date column compared against " + tag);
+ }
+ return intComparison(comparison, path, (Long) value, operator);
+ } else if (!isPlainSignedInteger(annotation, 32)) {
+ return drop(comparison, "unsupported 32-bit column annotation " + annotation);
+ }
+ Long intLiteral = asLong(tag, value);
+ if (intLiteral == null) {
+ return drop(comparison, "32-bit integer column compared against " + tag);
+ }
+ return intComparison(comparison, path, intLiteral, operator);
+
+ case INT64:
+ if (annotation instanceof LogicalTypeAnnotation.TimestampLogicalTypeAnnotation) {
+ if (tag != ATypeTag.DATETIME) {
+ return drop(comparison, "timestamp column compared against " + tag);
+ }
+ LogicalTypeAnnotation.TimeUnit unit =
+ ((LogicalTypeAnnotation.TimestampLogicalTypeAnnotation) annotation).getUnit();
+ Long inFileUnit = toTimestampUnit((Long) value, unit);
+ if (inFileUnit == null) {
+ return drop(comparison, "datetime literal does not fit the column's " + unit + " unit");
+ }
+ return compare(FilterApi.longColumn(path), inFileUnit, operator);
+ } else if (!isPlainSignedInteger(annotation, 64)) {
+ return drop(comparison, "unsupported 64-bit column annotation " + annotation);
+ }
+ Long longLiteral = asLong(tag, value);
+ if (longLiteral == null) {
+ return drop(comparison, "64-bit integer column compared against " + tag);
+ }
+ return compare(FilterApi.longColumn(path), longLiteral, operator);
+
+ case DOUBLE:
+ if (annotation != null) {
+ return drop(comparison, "unsupported double column annotation " + annotation);
+ } else if (tag == ATypeTag.DOUBLE) {
+ return compare(FilterApi.doubleColumn(path), (Double) value, operator);
+ }
+ Long doubleLiteral = asLong(tag, value);
+ if (doubleLiteral == null) {
+ return drop(comparison, "double column compared against " + tag);
+ } else if (Math.abs(doubleLiteral) > MAX_EXACT_DOUBLE) {
+ // widening would move the literal, which shifts where the comparison falls
+ return drop(comparison, "integer literal is not exactly representable as a double");
+ }
+ return compare(FilterApi.doubleColumn(path), (double) (long) doubleLiteral, operator);
+
+ case BINARY:
+ if (!(annotation instanceof LogicalTypeAnnotation.StringLogicalTypeAnnotation)) {
+ // raw binary does not order the way a string does
+ return drop(comparison, "unsupported binary column annotation " + annotation);
+ } else if (tag != ATypeTag.STRING) {
+ return drop(comparison, "string column compared against " + tag);
+ }
+ return compare(FilterApi.binaryColumn(path), Binary.fromString((String) value), operator);
+
+ default:
+ // FLOAT is excluded deliberately: every AsterixDB floating-point literal is a double, and
+ // narrowing one to a float moves it, so the pushed comparison would not be the one the engine
+ // evaluates. INT96 and FIXED_LEN_BYTE_ARRAY carry no ordering we can rely on here.
+ return drop(comparison, "unsupported column type " + type.getPrimitiveTypeName());
+ }
+ }
+
+ private static FilterPredicate intComparison(Comparison comparison, String path, Long value, Operator operator) {
+ if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) {
+ // the literal lies outside the column's range; clamping it would change which rows match
+ return drop(comparison, "literal is out of range for a 32-bit column");
+ }
+ return compare(FilterApi.intColumn(path), (int) (long) value, operator);
+ }
+
+ /**
+ * @return the literal as a long when it is an integral AsterixDB value, {@code null} otherwise
+ */
+ private static Long asLong(ATypeTag tag, Object value) {
+ switch (tag) {
+ case TINYINT:
+ case SMALLINT:
+ case INTEGER:
+ case BIGINT:
+ return (Long) value;
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * AsterixDB holds a datetime as milliseconds; the file may store microseconds or nanoseconds.
+ *
+ * @return the literal in the file's unit, or {@code null} when it overflows
+ */
+ private static Long toTimestampUnit(long millis, LogicalTypeAnnotation.TimeUnit unit) {
+ try {
+ switch (unit) {
+ case MILLIS:
+ return millis;
+ case MICROS:
+ return Math.multiplyExact(millis, TimeUnit.MILLISECONDS.toMicros(1));
+ case NANOS:
+ return Math.multiplyExact(millis, TimeUnit.MILLISECONDS.toNanos(1));
+ default:
+ return null;
+ }
+ } catch (ArithmeticException e) {
+ return null;
+ }
+ }
+
+ /**
+ * Whether the column is a plain signed integer of at most {@code maxBitWidth} bits. An unsigned column does
+ * not order the way a signed comparison would, and a decimal carries a scale the literal does not.
+ */
+ private static boolean isPlainSignedInteger(LogicalTypeAnnotation annotation, int maxBitWidth) {
+ if (annotation == null) {
+ return true;
+ } else if (annotation instanceof LogicalTypeAnnotation.IntLogicalTypeAnnotation) {
+ LogicalTypeAnnotation.IntLogicalTypeAnnotation intAnnotation =
+ (LogicalTypeAnnotation.IntLogicalTypeAnnotation) annotation;
+ return intAnnotation.isSigned() && intAnnotation.getBitWidth() <= maxBitWidth;
+ }
+ return false;
+ }
+
+ private static <T extends Comparable<T>, C extends Operators.Column<T> & Operators.SupportsLtGt> FilterPredicate compare(
+ C column, T value, Operator operator) {
+ switch (operator) {
+ case EQ:
+ return FilterApi.eq(column, value);
+ case GT:
+ return FilterApi.gt(column, value);
+ case GT_EQ:
+ return FilterApi.gtEq(column, value);
+ case LT:
+ return FilterApi.lt(column, value);
+ case LT_EQ:
+ return FilterApi.ltEq(column, value);
+ default:
+ return null;
+ }
+ }
+
+ private static FilterPredicate drop(Comparison comparison, String reason) {
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("not pushing row-group filter comparison {}: {}",
+ ParquetFilterExpression.describeShape(comparison), reason);
+ }
+ return null;
+ }
+}
diff --git a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/filter/ParquetFilterEvaluatorFactory.java b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/filter/ParquetFilterEvaluatorFactory.java
index 774e908..3366e6f 100644
--- a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/filter/ParquetFilterEvaluatorFactory.java
+++ b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/filter/ParquetFilterEvaluatorFactory.java
@@ -24,15 +24,14 @@
import org.apache.hyracks.api.application.IServiceContext;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.api.exceptions.IWarningCollector;
-import org.apache.parquet.filter2.predicate.FilterPredicate;
public class ParquetFilterEvaluatorFactory implements IExternalFilterEvaluatorFactory {
private static final long serialVersionUID = 1L;
- private final FilterPredicate filterExpression;
+ private final ParquetFilterExpression filterExpression;
private final IExternalFilterEvaluatorFactory externalFilterEvaluatorFactory;
public ParquetFilterEvaluatorFactory(IExternalFilterEvaluatorFactory externalFilterEvaluatorFactory,
- FilterPredicate expression) {
+ ParquetFilterExpression expression) {
this.externalFilterEvaluatorFactory = externalFilterEvaluatorFactory;
this.filterExpression = expression;
}
@@ -49,7 +48,7 @@
return externalFilterEvaluatorFactory.createValueEmbedder(warningCollector);
}
- public FilterPredicate getFilterExpression() {
+ public ParquetFilterExpression getFilterExpression() {
return filterExpression;
}
}
diff --git a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/filter/ParquetFilterExpression.java b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/filter/ParquetFilterExpression.java
new file mode 100644
index 0000000..b426d0f
--- /dev/null
+++ b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/filter/ParquetFilterExpression.java
@@ -0,0 +1,173 @@
+/*
+ * 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.asterix.external.input.filter;
+
+import java.io.Serializable;
+import java.util.Arrays;
+
+import org.apache.asterix.om.types.ATypeTag;
+import org.apache.hyracks.util.annotations.AiProvenance;
+
+/**
+ * A row-group filter that names columns and literals without committing to a physical Parquet type.
+ * <p>
+ * The filter is built while compiling the query, where only the AsterixDB type of each literal is known, and is
+ * turned into a parquet-mr {@code FilterPredicate} by {@link ParquetFilterConverter} on the node, once the schema
+ * of the file about to be read is in hand. The physical type cannot be chosen any earlier: a collection spans
+ * files whose schemas may disagree, and the physical type of a column decides which {@code FilterApi} column a
+ * predicate has to use. A predicate built against the wrong one is rejected by parquet-mr when the file is
+ * opened, which fails the query rather than skipping the optimization.
+ */
+@AiProvenance(agent = AiProvenance.Agent.CLAUDE_OPUS_5, tool = AiProvenance.Tool.CLAUDE_CODE_UI, contributionKind = AiProvenance.ContributionKind.GENERATED, notes = "Physical-type-agnostic carrier for the Parquet row-group filter")
+public abstract class ParquetFilterExpression implements Serializable {
+ private static final long serialVersionUID = 1L;
+
+ private ParquetFilterExpression() {
+ }
+
+ /**
+ * The comparisons that can be pushed. Parquet evaluates these against a row group's statistics, so only
+ * operators with a total order on the column's values are useful here.
+ */
+ public enum Operator {
+ EQ,
+ GT,
+ GT_EQ,
+ LT,
+ LT_EQ
+ }
+
+ public static final class And extends ParquetFilterExpression {
+ private static final long serialVersionUID = 1L;
+
+ private final ParquetFilterExpression left;
+ private final ParquetFilterExpression right;
+
+ public And(ParquetFilterExpression left, ParquetFilterExpression right) {
+ this.left = left;
+ this.right = right;
+ }
+
+ public ParquetFilterExpression getLeft() {
+ return left;
+ }
+
+ public ParquetFilterExpression getRight() {
+ return right;
+ }
+
+ @Override
+ public String toString() {
+ return "and(" + left + ", " + right + ')';
+ }
+ }
+
+ public static final class Or extends ParquetFilterExpression {
+ private static final long serialVersionUID = 1L;
+
+ private final ParquetFilterExpression left;
+ private final ParquetFilterExpression right;
+
+ public Or(ParquetFilterExpression left, ParquetFilterExpression right) {
+ this.left = left;
+ this.right = right;
+ }
+
+ public ParquetFilterExpression getLeft() {
+ return left;
+ }
+
+ public ParquetFilterExpression getRight() {
+ return right;
+ }
+
+ @Override
+ public String toString() {
+ return "or(" + left + ", " + right + ')';
+ }
+ }
+
+ /**
+ * A comparison between one column and one literal.
+ * <p>
+ * The column is held as its path components rather than a dotted string: parquet-mr splits a dotted string
+ * on every '.', so a field whose own name contains one would resolve to a nested path that does not exist,
+ * and a predicate on a column parquet-mr cannot find excludes every row group without reporting anything.
+ */
+ public static final class Comparison extends ParquetFilterExpression {
+ private static final long serialVersionUID = 1L;
+
+ private final String[] path;
+ private final Operator operator;
+ private final ATypeTag valueTag;
+ private final Object value;
+
+ /**
+ * @param path the column's path components, outermost first
+ * @param operator the comparison, read left to right as {@code column <operator> value}
+ * @param valueTag the AsterixDB type of the literal
+ * @param value the literal, as {@link Long}, {@link Double}, {@link String} or {@link Boolean}
+ */
+ public Comparison(String[] path, Operator operator, ATypeTag valueTag, Object value) {
+ this.path = path;
+ this.operator = operator;
+ this.valueTag = valueTag;
+ this.value = value;
+ }
+
+ public String[] getPath() {
+ return path;
+ }
+
+ public Operator getOperator() {
+ return operator;
+ }
+
+ public ATypeTag getValueTag() {
+ return valueTag;
+ }
+
+ public Object getValue() {
+ return value;
+ }
+
+ @Override
+ public String toString() {
+ return String.join(".", path) + ' ' + operator + ' ' + valueTag + '(' + value + ')';
+ }
+ }
+
+ /**
+ * Mirrors the shape of this expression without its literals, for logging that must not disclose user data.
+ */
+ public static String describeShape(ParquetFilterExpression expression) {
+ if (expression instanceof And) {
+ And and = (And) expression;
+ return "and(" + describeShape(and.getLeft()) + ", " + describeShape(and.getRight()) + ')';
+ } else if (expression instanceof Or) {
+ Or or = (Or) expression;
+ return "or(" + describeShape(or.getLeft()) + ", " + describeShape(or.getRight()) + ')';
+ } else if (expression instanceof Comparison) {
+ Comparison comparison = (Comparison) expression;
+ return Arrays.toString(comparison.getPath()) + ' ' + comparison.getOperator() + ' '
+ + comparison.getValueTag();
+ }
+ return String.valueOf(expression);
+ }
+}
diff --git a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/aws/parquet/AwsS3ParquetReaderFactory.java b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/aws/parquet/AwsS3ParquetReaderFactory.java
index 833cba5..941952e 100644
--- a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/aws/parquet/AwsS3ParquetReaderFactory.java
+++ b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/aws/parquet/AwsS3ParquetReaderFactory.java
@@ -33,7 +33,6 @@
import org.apache.asterix.common.external.IExternalFilterEvaluator;
import org.apache.asterix.common.external.IExternalFilterEvaluatorFactory;
import org.apache.asterix.external.input.HDFSDataSourceFactory;
-import org.apache.asterix.external.input.filter.ParquetFilterEvaluatorFactory;
import org.apache.asterix.external.input.record.reader.abstracts.AbstractExternalInputStreamFactory.IncludeExcludeMatcher;
import org.apache.asterix.external.util.ExternalDataConstants;
import org.apache.asterix.external.util.ExternalDataPrefix;
@@ -45,8 +44,6 @@
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.api.exceptions.IWarningCollector;
import org.apache.hyracks.api.util.ExceptionUtils;
-import org.apache.parquet.filter2.predicate.FilterPredicate;
-import org.apache.parquet.hadoop.ParquetInputFormat;
import com.amazonaws.SdkBaseException;
@@ -94,13 +91,6 @@
IApplicationContext appCtx = (IApplicationContext) serviceCtx.getApplicationContext();
configureAwsS3HdfsJobConf(appCtx, conf, configuration, numberOfPartitions);
configureHdfsConf(conf, configuration);
- if (filterEvaluatorFactory instanceof ParquetFilterEvaluatorFactory) {
- FilterPredicate parquetFilterPredicate =
- ((ParquetFilterEvaluatorFactory) filterEvaluatorFactory).getFilterExpression();
- if (parquetFilterPredicate != null) {
- ParquetInputFormat.setFilterPredicate(conf, parquetFilterPredicate);
- }
- }
} catch (SdkException | SdkBaseException ex) {
throw new RuntimeDataException(ErrorCode.EXTERNAL_SOURCE_ERROR, ex, getMessageOrToString(ex));
} catch (AlgebricksException ex) {
diff --git a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/azure/parquet/AzureBlobParquetReaderFactory.java b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/azure/parquet/AzureBlobParquetReaderFactory.java
index 3347c68..a32e316 100644
--- a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/azure/parquet/AzureBlobParquetReaderFactory.java
+++ b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/azure/parquet/AzureBlobParquetReaderFactory.java
@@ -32,7 +32,6 @@
import org.apache.asterix.common.external.IExternalFilterEvaluator;
import org.apache.asterix.common.external.IExternalFilterEvaluatorFactory;
import org.apache.asterix.external.input.HDFSDataSourceFactory;
-import org.apache.asterix.external.input.filter.ParquetFilterEvaluatorFactory;
import org.apache.asterix.external.input.record.reader.abstracts.AbstractExternalInputStreamFactory.IncludeExcludeMatcher;
import org.apache.asterix.external.util.ExternalDataConstants;
import org.apache.asterix.external.util.ExternalDataPrefix;
@@ -44,8 +43,6 @@
import org.apache.hyracks.api.application.IServiceContext;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.api.exceptions.IWarningCollector;
-import org.apache.parquet.filter2.predicate.FilterPredicate;
-import org.apache.parquet.hadoop.ParquetInputFormat;
import com.azure.storage.blob.BlobServiceClient;
import com.azure.storage.blob.models.BlobItem;
@@ -88,13 +85,6 @@
conf.set(ConfigurationKeys.FS_AZURE_ACCOUNT_IS_HNS_ENABLED, "false");
configureAzureHdfsJobConf(conf, configuration, endPoint);
configureHdfsConf(conf, configuration);
- if (filterEvaluatorFactory instanceof ParquetFilterEvaluatorFactory) {
- FilterPredicate parquetFilterPredicate =
- ((ParquetFilterEvaluatorFactory) filterEvaluatorFactory).getFilterExpression();
- if (parquetFilterPredicate != null) {
- ParquetInputFormat.setFilterPredicate(conf, parquetFilterPredicate);
- }
- }
}
@Override
diff --git a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/azure/parquet/AzureDataLakeParquetReaderFactory.java b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/azure/parquet/AzureDataLakeParquetReaderFactory.java
index fc6374c..bcc8e3e 100644
--- a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/azure/parquet/AzureDataLakeParquetReaderFactory.java
+++ b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/azure/parquet/AzureDataLakeParquetReaderFactory.java
@@ -32,7 +32,6 @@
import org.apache.asterix.common.external.IExternalFilterEvaluator;
import org.apache.asterix.common.external.IExternalFilterEvaluatorFactory;
import org.apache.asterix.external.input.HDFSDataSourceFactory;
-import org.apache.asterix.external.input.filter.ParquetFilterEvaluatorFactory;
import org.apache.asterix.external.input.record.reader.abstracts.AbstractExternalInputStreamFactory.IncludeExcludeMatcher;
import org.apache.asterix.external.util.ExternalDataConstants;
import org.apache.asterix.external.util.ExternalDataPrefix;
@@ -43,8 +42,6 @@
import org.apache.hyracks.api.application.IServiceContext;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.api.exceptions.IWarningCollector;
-import org.apache.parquet.filter2.predicate.FilterPredicate;
-import org.apache.parquet.hadoop.ParquetInputFormat;
import com.azure.storage.file.datalake.DataLakeServiceClient;
import com.azure.storage.file.datalake.models.PathItem;
@@ -87,13 +84,6 @@
conf.set(ConfigurationKeys.FS_AZURE_ACCOUNT_IS_HNS_ENABLED, "true");
configureAzureHdfsJobConf(conf, configuration, endPoint);
configureHdfsConf(conf, configuration);
- if (filterEvaluatorFactory instanceof ParquetFilterEvaluatorFactory) {
- FilterPredicate parquetFilterPredicate =
- ((ParquetFilterEvaluatorFactory) filterEvaluatorFactory).getFilterExpression();
- if (parquetFilterPredicate != null) {
- ParquetInputFormat.setFilterPredicate(conf, parquetFilterPredicate);
- }
- }
}
@Override
diff --git a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/gcs/parquet/GCSParquetReaderFactory.java b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/gcs/parquet/GCSParquetReaderFactory.java
index a2e2c71..a51cc3b 100644
--- a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/gcs/parquet/GCSParquetReaderFactory.java
+++ b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/gcs/parquet/GCSParquetReaderFactory.java
@@ -27,7 +27,6 @@
import org.apache.asterix.common.external.IExternalFilterEvaluator;
import org.apache.asterix.common.external.IExternalFilterEvaluatorFactory;
import org.apache.asterix.external.input.HDFSDataSourceFactory;
-import org.apache.asterix.external.input.filter.ParquetFilterEvaluatorFactory;
import org.apache.asterix.external.input.record.reader.abstracts.AbstractExternalInputStreamFactory.IncludeExcludeMatcher;
import org.apache.asterix.external.util.ExternalDataConstants;
import org.apache.asterix.external.util.ExternalDataPrefix;
@@ -39,8 +38,6 @@
import org.apache.hyracks.api.application.IServiceContext;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.api.exceptions.IWarningCollector;
-import org.apache.parquet.filter2.predicate.FilterPredicate;
-import org.apache.parquet.hadoop.ParquetInputFormat;
import com.google.cloud.storage.Blob;
@@ -78,13 +75,6 @@
int numberOfPartitions = getPartitionConstraint().getLocations().length;
GCSUtils.configureHdfsJobConf(conf, configuration, numberOfPartitions);
configureHdfsConf(conf, configuration);
- if (filterEvaluatorFactory instanceof ParquetFilterEvaluatorFactory) {
- FilterPredicate parquetFilterPredicate =
- ((ParquetFilterEvaluatorFactory) filterEvaluatorFactory).getFilterExpression();
- if (parquetFilterPredicate != null) {
- ParquetInputFormat.setFilterPredicate(conf, parquetFilterPredicate);
- }
- }
}
@Override
diff --git a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/hdfs/parquet/MapredParquetInputFormat.java b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/hdfs/parquet/MapredParquetInputFormat.java
index 0321d20..e8c2785 100644
--- a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/hdfs/parquet/MapredParquetInputFormat.java
+++ b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/hdfs/parquet/MapredParquetInputFormat.java
@@ -25,6 +25,7 @@
import java.io.IOException;
import java.util.List;
+import org.apache.asterix.external.input.filter.ParquetFilterExpression;
import org.apache.asterix.external.input.filter.embedder.IExternalFilterValueEmbedder;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.mapred.InputSplit;
@@ -50,11 +51,12 @@
private final ParquetInputFormat<ArrayBackedValueStorage> realInputFormat = new ParquetInputFormat<>();
private IExternalFilterValueEmbedder valueEmbedder;
+ private ParquetFilterExpression rowGroupFilter;
@Override
public RecordReader<Void, VoidPointable> getRecordReader(InputSplit split, JobConf job, Reporter reporter)
throws IOException {
- return new ParquetRecordReaderWrapper(split, job, reporter, valueEmbedder);
+ return new ParquetRecordReaderWrapper(split, job, reporter, valueEmbedder, rowGroupFilter);
}
@Override
@@ -89,6 +91,10 @@
this.valueEmbedder = valueEmbedder;
}
+ public void setRowGroupFilter(ParquetFilterExpression rowGroupFilter) {
+ this.rowGroupFilter = rowGroupFilter;
+ }
+
public static boolean isTaskSideMetaData(JobConf job) {
return job.getBoolean(ParquetInputFormat.TASK_SIDE_METADATA, true);
}
diff --git a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/hdfs/parquet/ParquetFileRecordReader.java b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/hdfs/parquet/ParquetFileRecordReader.java
index 1d123b6..f4391bc 100644
--- a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/hdfs/parquet/ParquetFileRecordReader.java
+++ b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/hdfs/parquet/ParquetFileRecordReader.java
@@ -22,6 +22,7 @@
import java.security.PrivilegedExceptionAction;
import org.apache.asterix.external.api.IExternalDataRuntimeContext;
+import org.apache.asterix.external.input.filter.ParquetFilterExpression;
import org.apache.asterix.external.input.record.ValueReferenceRecord;
import org.apache.asterix.external.input.record.reader.hdfs.AbstractHDFSRecordReader;
import org.apache.asterix.external.util.HDFSUtils;
@@ -42,10 +43,12 @@
private final IWarningCollector warningCollector;
public ParquetFileRecordReader(boolean[] read, InputSplit[] inputSplits, String[] readSchedule, String nodeName,
- JobConf conf, IExternalDataRuntimeContext context, UserGroupInformation ugi) {
+ JobConf conf, IExternalDataRuntimeContext context, UserGroupInformation ugi,
+ ParquetFilterExpression rowGroupFilter) {
super(read, inputSplits, readSchedule, nodeName, new ValueReferenceRecord<>(), conf, ugi);
this.warningCollector = context.getTaskContext().getWarningCollector();
((MapredParquetInputFormat) inputFormat).setValueEmbedder(context.getValueEmbedder());
+ ((MapredParquetInputFormat) inputFormat).setRowGroupFilter(rowGroupFilter);
}
@Override
diff --git a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/hdfs/parquet/ParquetRecordReaderWrapper.java b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/hdfs/parquet/ParquetRecordReaderWrapper.java
index a293ebb..16d421b 100644
--- a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/hdfs/parquet/ParquetRecordReaderWrapper.java
+++ b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/hdfs/parquet/ParquetRecordReaderWrapper.java
@@ -22,7 +22,10 @@
import org.apache.asterix.common.exceptions.ErrorCode;
import org.apache.asterix.common.exceptions.RuntimeDataException;
+import org.apache.asterix.external.input.filter.ParquetFilterConverter;
+import org.apache.asterix.external.input.filter.ParquetFilterExpression;
import org.apache.asterix.external.input.filter.embedder.IExternalFilterValueEmbedder;
+import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapred.FileSplit;
import org.apache.hadoop.mapred.InputSplit;
import org.apache.hadoop.mapred.JobConf;
@@ -32,9 +35,14 @@
import org.apache.hyracks.data.std.api.IValueReference;
import org.apache.hyracks.data.std.primitive.VoidPointable;
import org.apache.hyracks.util.LogRedactionUtil;
+import org.apache.hyracks.util.annotations.AiProvenance;
+import org.apache.parquet.filter2.predicate.FilterPredicate;
+import org.apache.parquet.hadoop.ParquetFileReader;
import org.apache.parquet.hadoop.ParquetInputFormat;
import org.apache.parquet.hadoop.ParquetRecordReader;
import org.apache.parquet.hadoop.api.ReadSupport;
+import org.apache.parquet.hadoop.util.HadoopInputFile;
+import org.apache.parquet.schema.MessageType;
public class ParquetRecordReaderWrapper implements RecordReader<Void, VoidPointable> {
private final ParquetRecordReader<IValueReference> realReader;
@@ -46,20 +54,21 @@
private boolean eof;
public ParquetRecordReaderWrapper(InputSplit oldSplit, JobConf oldJobConf, Reporter reporter,
- IExternalFilterValueEmbedder valueEmbedder) throws IOException {
+ IExternalFilterValueEmbedder valueEmbedder, ParquetFilterExpression rowGroupFilter) throws IOException {
splitLen = oldSplit.getLength();
try {
ReadSupport<IValueReference> readSupport = ParquetInputFormat.getReadSupportInstance(oldJobConf);
ParquetReadSupport parquetReadSupport = (ParquetReadSupport) readSupport;
parquetReadSupport.setValueEmbedder(valueEmbedder);
- realReader = new ParquetRecordReader<>(readSupport, ParquetInputFormat.getFilter(oldJobConf));
+ JobConf readerConf = withRowGroupFilter(oldJobConf, oldSplit, rowGroupFilter);
+ realReader = new ParquetRecordReader<>(readSupport, ParquetInputFormat.getFilter(readerConf));
if (oldSplit instanceof MapredParquetInputFormat.ParquetInputSplitWrapper) {
realReader.initialize(((MapredParquetInputFormat.ParquetInputSplitWrapper) oldSplit).realSplit,
- oldJobConf, reporter);
+ readerConf, reporter);
} else if (oldSplit instanceof FileSplit) {
- realReader.initialize((FileSplit) oldSplit, oldJobConf, reporter);
+ realReader.initialize((FileSplit) oldSplit, readerConf, reporter);
} else {
throw RuntimeDataException.create(ErrorCode.INVALID_PARQUET_FILE,
LogRedactionUtil.userData(oldSplit.toString()), "invalid file split");
@@ -92,7 +101,45 @@
}
}
- private String getPath(InputSplit split) {
+ /**
+ * Binds the row-group filter to this file and returns the configuration the reader should use.
+ * <p>
+ * The predicate has to be built here rather than when the query was compiled: it names a parquet-mr column
+ * of a specific physical type, and only this file says what that type is. It also has to travel in the
+ * configuration, because that is where {@code ParquetFileReader} looks for it when it decides which row
+ * groups to read.
+ * <p>
+ * Only row-group elimination is wanted. Record-level and column-index filtering would re-decide which
+ * individual rows survive, under parquet-mr's comparison and null semantics rather than the engine's, and
+ * the engine evaluates the predicate itself regardless.
+ *
+ * @return a copy of {@code jobConf} carrying the predicate, or {@code jobConf} when nothing can be pushed
+ */
+ @AiProvenance(agent = AiProvenance.Agent.CLAUDE_OPUS_5, tool = AiProvenance.Tool.CLAUDE_CODE_UI, contributionKind = AiProvenance.ContributionKind.GENERATED, notes = "Bind the row-group filter to the file being read")
+ private static JobConf withRowGroupFilter(JobConf jobConf, InputSplit split, ParquetFilterExpression rowGroupFilter)
+ throws IOException {
+ if (rowGroupFilter == null) {
+ return jobConf;
+ }
+ MessageType fileSchema;
+ // the footer is read again when the reader opens the file; that second read is the price of knowing the
+ // schema before the predicate has to exist, and is only paid when there is a filter to push
+ try (ParquetFileReader reader =
+ ParquetFileReader.open(HadoopInputFile.fromPath(new Path(getPath(split)), jobConf))) {
+ fileSchema = reader.getFileMetaData().getSchema();
+ }
+ FilterPredicate predicate = ParquetFilterConverter.toParquetFilter(fileSchema, rowGroupFilter);
+ if (predicate == null) {
+ return jobConf;
+ }
+ JobConf withFilter = new JobConf(jobConf);
+ ParquetInputFormat.setFilterPredicate(withFilter, predicate);
+ withFilter.setBoolean(ParquetInputFormat.RECORD_FILTERING_ENABLED, false);
+ withFilter.setBoolean(ParquetInputFormat.COLUMN_INDEX_FILTERING_ENABLED, false);
+ return withFilter;
+ }
+
+ private static String getPath(InputSplit split) {
if (split instanceof FileSplit) {
return ((FileSplit) split).getPath().toString();
} else if (split instanceof MapredParquetInputFormat.ParquetInputSplitWrapper) {
diff --git a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/util/ExternalDataConstants.java b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/util/ExternalDataConstants.java
index 5cd9b60..cb72769 100644
--- a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/util/ExternalDataConstants.java
+++ b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/util/ExternalDataConstants.java
@@ -506,5 +506,15 @@
* then we will return the UTC time and issue a warning about that.
*/
public static final String HADOOP_TIMEZONE = ASTERIX_HADOOP_PREFIX + KEY_TIMEZONE;
+
+ /**
+ * Push a query's predicate into the reader, so row groups whose statistics rule them out are skipped
+ * instead of decoded. It never changes an answer -- the engine evaluates the predicate itself either way
+ * -- so this exists to be turned off when a scan is slower with it, which a file whose statistics exclude
+ * nothing can be, since the predicate is then evaluated per row group for no benefit.
+ * Default: true
+ */
+ public static final String ROW_GROUP_FILTER = "rowGroupFilter";
+ public static final boolean DEFAULT_ROW_GROUP_FILTER = true;
}
}
diff --git a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/util/ExternalDataUtils.java b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/util/ExternalDataUtils.java
index b2797cb..6f6a54f 100644
--- a/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/util/ExternalDataUtils.java
+++ b/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/util/ExternalDataUtils.java
@@ -1139,6 +1139,24 @@
String resolved = resolveTimeZone(properties.get(ExternalDataConstants.KEY_TIMEZONE));
properties.put(ExternalDataConstants.KEY_TIMEZONE, resolved);
}
+ validateBoolean(properties, ExternalDataConstants.ParquetOptions.ROW_GROUP_FILTER);
+ }
+ }
+
+ /**
+ * Rejects anything but true or false at DDL time. Empty is rejected too, since {@code parseBoolean} would read
+ * it as a silent off.
+ */
+ @AiProvenance(agent = AiProvenance.Agent.CLAUDE_OPUS_5, tool = AiProvenance.Tool.CLAUDE_CODE_UI, contributionKind = AiProvenance.ContributionKind.GENERATED, notes = "DDL-time validation for the row-group filter flag, following the iceberg variant pushdown flags")
+ private static void validateBoolean(Map<String, String> properties, String propertyName)
+ throws CompilationException {
+ String value = properties.get(propertyName);
+ if (value == null) {
+ return;
+ }
+ if (!ExternalDataConstants.TRUE.equalsIgnoreCase(value)
+ && !ExternalDataConstants.FALSE.equalsIgnoreCase(value)) {
+ throw new CompilationException(ErrorCode.INVALID_REQ_PARAM_VAL, propertyName, value);
}
}
diff --git a/asterixdb/asterix-external-data/src/test/java/org/apache/asterix/external/input/filter/ParquetFilterConverterTest.java b/asterixdb/asterix-external-data/src/test/java/org/apache/asterix/external/input/filter/ParquetFilterConverterTest.java
new file mode 100644
index 0000000..0b3c693
--- /dev/null
+++ b/asterixdb/asterix-external-data/src/test/java/org/apache/asterix/external/input/filter/ParquetFilterConverterTest.java
@@ -0,0 +1,270 @@
+/*
+ * 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.asterix.external.input.filter;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.File;
+import java.nio.file.Files;
+import java.util.Comparator;
+import java.util.stream.Stream;
+
+import org.apache.asterix.external.input.filter.ParquetFilterExpression.Comparison;
+import org.apache.asterix.external.input.filter.ParquetFilterExpression.Operator;
+import org.apache.asterix.om.types.ATypeTag;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.mapred.FileSplit;
+import org.apache.hadoop.mapred.JobConf;
+import org.apache.hadoop.mapred.Reporter;
+import org.apache.hyracks.util.annotations.AiProvenance;
+import org.apache.parquet.example.data.Group;
+import org.apache.parquet.example.data.simple.SimpleGroupFactory;
+import org.apache.parquet.filter2.predicate.FilterPredicate;
+import org.apache.parquet.hadoop.ParquetFileReader;
+import org.apache.parquet.hadoop.ParquetInputFormat;
+import org.apache.parquet.hadoop.ParquetRecordReader;
+import org.apache.parquet.hadoop.example.ExampleParquetWriter;
+import org.apache.parquet.hadoop.example.GroupReadSupport;
+import org.apache.parquet.hadoop.metadata.CompressionCodecName;
+import org.apache.parquet.schema.LogicalTypeAnnotation;
+import org.apache.parquet.schema.MessageType;
+import org.apache.parquet.schema.MessageTypeParser;
+import org.apache.parquet.schema.PrimitiveType;
+import org.apache.parquet.schema.Types;
+import org.junit.Test;
+
+/**
+ * Covers the binding of a row-group filter to one file's schema. The column's physical type is only known here,
+ * so every case is about what that type does or does not allow; a comparison the file cannot support has to be
+ * dropped rather than pushed, because parquet-mr rejects an ill-typed predicate by throwing when the file opens.
+ */
+@AiProvenance(agent = AiProvenance.Agent.CLAUDE_OPUS_5, tool = AiProvenance.Tool.CLAUDE_CODE_UI, contributionKind = AiProvenance.ContributionKind.TEST_GENERATED, notes = "Per-file Parquet row-group filter binding")
+public class ParquetFilterConverterTest {
+
+ private static Comparison comparison(String[] path, Operator operator, ATypeTag tag, Object value) {
+ return new Comparison(path, operator, tag, value);
+ }
+
+ private static Comparison equals(String column, ATypeTag tag, Object value) {
+ return comparison(new String[] { column }, Operator.EQ, tag, value);
+ }
+
+ /** Every AsterixDB integer literal is 64-bit, so a 32-bit column must still be filterable. */
+ @Test
+ public void longLiteralBindsToAnIntegerColumn() {
+ MessageType schema = MessageTypeParser.parseMessageType("message m { required int32 id; }");
+ FilterPredicate predicate = ParquetFilterConverter.toParquetFilter(schema, equals("id", ATypeTag.BIGINT, 5L));
+ assertNotNull(predicate);
+ assertEquals("eq(id, 5)", predicate.toString());
+ }
+
+ @Test
+ public void longLiteralBindsToALongColumn() {
+ MessageType schema = MessageTypeParser.parseMessageType("message m { required int64 id; }");
+ FilterPredicate predicate = ParquetFilterConverter.toParquetFilter(schema, equals("id", ATypeTag.BIGINT, 5L));
+ assertNotNull(predicate);
+ assertEquals("eq(id, 5)", predicate.toString());
+ }
+
+ /** Out of the column's range, the literal cannot be narrowed without changing which rows match. */
+ @Test
+ public void literalOutOfRangeOfAnIntegerColumnIsDropped() {
+ MessageType schema = MessageTypeParser.parseMessageType("message m { required int32 id; }");
+ assertNull(
+ ParquetFilterConverter.toParquetFilter(schema, equals("id", ATypeTag.BIGINT, Integer.MAX_VALUE + 1L)));
+ }
+
+ @Test
+ public void repeatedColumnIsDropped() {
+ MessageType schema = MessageTypeParser.parseMessageType("message m { repeated int64 tags; }");
+ assertNull(ParquetFilterConverter.toParquetFilter(schema, equals("tags", ATypeTag.BIGINT, 1L)));
+ }
+
+ @Test
+ public void columnAbsentFromTheFileIsDropped() {
+ MessageType schema = MessageTypeParser.parseMessageType("message m { required int64 id; }");
+ assertNull(ParquetFilterConverter.toParquetFilter(schema, equals("missing", ATypeTag.BIGINT, 1L)));
+ }
+
+ /**
+ * parquet-mr's column factories split a name on '.', so a field whose own name contains one would resolve to
+ * a nested path that does not exist. Such a predicate excludes every row group and reports nothing, which is
+ * a wrong answer rather than a missed optimization.
+ */
+ @Test
+ public void columnWhoseNameContainsADotIsDropped() {
+ MessageType schema =
+ Types.buildMessage().required(PrimitiveType.PrimitiveTypeName.INT64).named("a.b").named("m");
+ assertNull(ParquetFilterConverter.toParquetFilter(schema, equals("a.b", ATypeTag.BIGINT, 1L)));
+ }
+
+ @Test
+ public void nestedColumnIsPushed() {
+ MessageType schema =
+ MessageTypeParser.parseMessageType("message m { optional group outer { optional int64 inner; } }");
+ FilterPredicate predicate = ParquetFilterConverter.toParquetFilter(schema,
+ comparison(new String[] { "outer", "inner" }, Operator.GT, ATypeTag.BIGINT, 7L));
+ assertNotNull(predicate);
+ assertEquals("gt(outer.inner, 7)", predicate.toString());
+ }
+
+ /** AsterixDB holds a datetime in milliseconds; the file decides the unit the statistics are in. */
+ @Test
+ public void datetimeLiteralIsConvertedToTheColumnsUnit() {
+ MessageType micros = Types.buildMessage().required(PrimitiveType.PrimitiveTypeName.INT64)
+ .as(LogicalTypeAnnotation.timestampType(true, LogicalTypeAnnotation.TimeUnit.MICROS)).named("ts")
+ .named("m");
+ FilterPredicate predicate =
+ ParquetFilterConverter.toParquetFilter(micros, equals("ts", ATypeTag.DATETIME, 1_000L));
+ assertEquals("eq(ts, 1000000)", predicate.toString());
+
+ MessageType millis = Types.buildMessage().required(PrimitiveType.PrimitiveTypeName.INT64)
+ .as(LogicalTypeAnnotation.timestampType(true, LogicalTypeAnnotation.TimeUnit.MILLIS)).named("ts")
+ .named("m");
+ predicate = ParquetFilterConverter.toParquetFilter(millis, equals("ts", ATypeTag.DATETIME, 1_000L));
+ assertEquals("eq(ts, 1000)", predicate.toString());
+ }
+
+ @Test
+ public void stringLiteralBindsToAStringColumn() {
+ MessageType schema = MessageTypeParser.parseMessageType("message m { required binary s (STRING); }");
+ FilterPredicate predicate = ParquetFilterConverter.toParquetFilter(schema, equals("s", ATypeTag.STRING, "abc"));
+ assertNotNull(predicate);
+ assertTrue(predicate.toString(), predicate.toString().startsWith("eq(s, "));
+ }
+
+ /** Raw binary does not order the way a string does. */
+ @Test
+ public void unannotatedBinaryColumnIsDropped() {
+ MessageType schema = MessageTypeParser.parseMessageType("message m { required binary b; }");
+ assertNull(ParquetFilterConverter.toParquetFilter(schema, equals("b", ATypeTag.STRING, "abc")));
+ }
+
+ /** An unsigned column does not order the way the signed comparison the engine ran does. */
+ @Test
+ public void unsignedIntegerColumnIsDropped() {
+ MessageType schema = Types.buildMessage().required(PrimitiveType.PrimitiveTypeName.INT32)
+ .as(LogicalTypeAnnotation.intType(32, false)).named("id").named("m");
+ assertNull(ParquetFilterConverter.toParquetFilter(schema, equals("id", ATypeTag.BIGINT, 1L)));
+ }
+
+ /** Narrowing a double literal to a float would move it, so the pushed comparison would not be the engine's. */
+ @Test
+ public void floatColumnIsDropped() {
+ MessageType schema = MessageTypeParser.parseMessageType("message m { required float f; }");
+ assertNull(ParquetFilterConverter.toParquetFilter(schema, equals("f", ATypeTag.DOUBLE, 1.5d)));
+ }
+
+ @Test
+ public void decimalColumnIsDropped() {
+ MessageType schema = Types.buildMessage().required(PrimitiveType.PrimitiveTypeName.INT64)
+ .as(LogicalTypeAnnotation.decimalType(2, 10)).named("d").named("m");
+ assertNull(ParquetFilterConverter.toParquetFilter(schema, equals("d", ATypeTag.BIGINT, 1L)));
+ }
+
+ /** One conjunct that cannot be pushed leaves the other still pruning. */
+ @Test
+ public void conjunctionKeepsTheSideItCanPush() {
+ MessageType schema = MessageTypeParser.parseMessageType("message m { required int64 id; repeated int64 t; }");
+ FilterPredicate predicate = ParquetFilterConverter.toParquetFilter(schema,
+ new ParquetFilterExpression.And(equals("id", ATypeTag.BIGINT, 5L), equals("t", ATypeTag.BIGINT, 1L)));
+ assertEquals("eq(id, 5)", predicate.toString());
+ }
+
+ /** One disjunct that cannot be pushed would keep row groups the other excludes, so neither is kept. */
+ @Test
+ public void disjunctionIsDroppedWholesale() {
+ MessageType schema = MessageTypeParser.parseMessageType("message m { required int64 id; repeated int64 t; }");
+ assertNull(ParquetFilterConverter.toParquetFilter(schema,
+ new ParquetFilterExpression.Or(equals("id", ATypeTag.BIGINT, 5L), equals("t", ATypeTag.BIGINT, 1L))));
+ }
+
+ /**
+ * Reads a real file through the same call the reader makes, so the test fails if the predicate stops reaching
+ * parquet-mr or stops excluding row groups -- which is the defect this binding exists to fix, and which no
+ * assertion on the compiled plan can see.
+ */
+ @Test
+ public void convertedFilterExcludesRowGroups() throws Exception {
+ File directory = Files.createTempDirectory("parquet-row-group-filter").toFile();
+ try {
+ Path file = new Path(new File(directory, "rows.parquet").getAbsolutePath());
+ MessageType schema = MessageTypeParser.parseMessageType("message m { required int32 id; }");
+ Configuration configuration = new Configuration();
+ SimpleGroupFactory groups = new SimpleGroupFactory(schema);
+ try (org.apache.parquet.hadoop.ParquetWriter<Group> writer = ExampleParquetWriter.builder(file)
+ .withType(schema).withConf(configuration).withRowGroupSize(1024L)
+ .withCompressionCodec(CompressionCodecName.UNCOMPRESSED).withDictionaryEncoding(false).build()) {
+ for (int id = 1; id <= 2000; id++) {
+ writer.write(groups.newGroup().append("id", id));
+ }
+ }
+ int rowGroups;
+ try (ParquetFileReader reader = ParquetFileReader.open(configuration, file)) {
+ rowGroups = reader.getFooter().getBlocks().size();
+ }
+ assertTrue("fixture needs several row groups to show pruning, had " + rowGroups, rowGroups > 1);
+
+ long all = read(file, configuration, schema, null);
+ assertEquals(2000, all);
+ // inside the data: the row group holding it is read whole, the rest are skipped. Rows other than the
+ // matching one still come back, because only row groups are filtered here and the engine is what
+ // decides which rows satisfy the predicate.
+ long surviving = read(file, configuration, schema, equals("id", ATypeTag.BIGINT, 1500L));
+ assertTrue("expected some row groups to be skipped, read " + surviving + " of " + all,
+ surviving > 0 && surviving < all);
+ // outside every row group's statistics, so no row group is worth reading
+ assertEquals(0, read(file, configuration, schema, equals("id", ATypeTag.BIGINT, 101500L)));
+ } finally {
+ try (Stream<java.nio.file.Path> paths = Files.walk(directory.toPath())) {
+ paths.sorted(Comparator.reverseOrder()).map(java.nio.file.Path::toFile).forEach(File::delete);
+ }
+ }
+ }
+
+ private static long read(Path file, Configuration configuration, MessageType schema,
+ ParquetFilterExpression expression) throws Exception {
+ JobConf jobConf = new JobConf(configuration);
+ jobConf.set(ParquetInputFormat.READ_SUPPORT_CLASS, GroupReadSupport.class.getName());
+ if (expression != null) {
+ FilterPredicate predicate = ParquetFilterConverter.toParquetFilter(schema, expression);
+ assertNotNull("expected the comparison to be pushable", predicate);
+ ParquetInputFormat.setFilterPredicate(jobConf, predicate);
+ jobConf.setBoolean(ParquetInputFormat.RECORD_FILTERING_ENABLED, false);
+ jobConf.setBoolean(ParquetInputFormat.COLUMN_INDEX_FILTERING_ENABLED, false);
+ }
+ long length = file.getFileSystem(jobConf).getFileStatus(file).getLen();
+ ParquetRecordReader<Group> reader =
+ new ParquetRecordReader<>(new GroupReadSupport(), ParquetInputFormat.getFilter(jobConf));
+ try {
+ reader.initialize(new FileSplit(file, 0, length, (String[]) null), jobConf, Reporter.NULL);
+ long rows = 0;
+ while (reader.nextKeyValue()) {
+ rows++;
+ }
+ return rows;
+ } finally {
+ reader.close();
+ }
+ }
+}
diff --git a/asterixdb/asterix-metadata/src/main/java/org/apache/asterix/metadata/utils/IndexUtil.java b/asterixdb/asterix-metadata/src/main/java/org/apache/asterix/metadata/utils/IndexUtil.java
index e2cf9f4..54fab9d 100644
--- a/asterixdb/asterix-metadata/src/main/java/org/apache/asterix/metadata/utils/IndexUtil.java
+++ b/asterixdb/asterix-metadata/src/main/java/org/apache/asterix/metadata/utils/IndexUtil.java
@@ -47,6 +47,7 @@
import org.apache.asterix.external.input.filter.NoOpExternalFilterEvaluatorFactory;
import org.apache.asterix.external.input.filter.NoOpIcebergTableFilterEvaluatorFactory;
import org.apache.asterix.external.input.filter.ParquetFilterEvaluatorFactory;
+import org.apache.asterix.external.util.ExternalDataConstants;
import org.apache.asterix.external.util.ExternalDataPrefix;
import org.apache.asterix.metadata.dataset.DatasetFormatInfo;
import org.apache.asterix.metadata.declared.MetadataProvider;
@@ -413,9 +414,18 @@
ExternalFilterBuilder externalFilterBuilder = new ExternalFilterBuilder(pfi, context, typeEnv, prefix);
externalFilterEvaluatorFactory = externalFilterBuilder.build();
}
- ParquetFilterBuilder builder = new ParquetFilterBuilder(
- (ParquetExternalDatasetProjectionFiltrationInfo) projectionFiltrationInfo, context, typeEnv);
- return new ParquetFilterEvaluatorFactory(externalFilterEvaluatorFactory, builder.buildFilterPredicate());
+ String rowGroupFilter = properties.get(ExternalDataConstants.ParquetOptions.ROW_GROUP_FILTER);
+ if (rowGroupFilter != null && !Boolean.parseBoolean(rowGroupFilter)) {
+ return new ParquetFilterEvaluatorFactory(externalFilterEvaluatorFactory, null);
+ }
+ // a timezone option makes the reader shift what it reads, so a temporal literal is not in the frame
+ // the file's statistics are in; such comparisons are left unpushed until MB-74031 converts them
+ String timezone = properties.get(ExternalDataConstants.KEY_TIMEZONE);
+ boolean pushTemporalLiterals = timezone == null || timezone.isEmpty();
+ ParquetFilterBuilder builder =
+ new ParquetFilterBuilder((ParquetExternalDatasetProjectionFiltrationInfo) projectionFiltrationInfo,
+ context, typeEnv, pushTemporalLiterals);
+ return new ParquetFilterEvaluatorFactory(externalFilterEvaluatorFactory, builder.buildFilterExpression());
}
}
diff --git a/asterixdb/asterix-metadata/src/main/java/org/apache/asterix/metadata/utils/filter/ParquetFilterBuilder.java b/asterixdb/asterix-metadata/src/main/java/org/apache/asterix/metadata/utils/filter/ParquetFilterBuilder.java
index 972eeb9..cb9fc3e 100644
--- a/asterixdb/asterix-metadata/src/main/java/org/apache/asterix/metadata/utils/filter/ParquetFilterBuilder.java
+++ b/asterixdb/asterix-metadata/src/main/java/org/apache/asterix/metadata/utils/filter/ParquetFilterBuilder.java
@@ -20,8 +20,10 @@
import java.util.ArrayList;
import java.util.List;
-import java.util.concurrent.TimeUnit;
+import org.apache.asterix.external.input.filter.ParquetFilterExpression;
+import org.apache.asterix.external.input.filter.ParquetFilterExpression.Comparison;
+import org.apache.asterix.external.input.filter.ParquetFilterExpression.Operator;
import org.apache.asterix.om.base.ADate;
import org.apache.asterix.om.base.ADateTime;
import org.apache.asterix.om.base.ADouble;
@@ -47,44 +49,62 @@
import org.apache.hyracks.algebricks.core.jobgen.impl.JobGenContext;
import org.apache.hyracks.algebricks.runtime.base.IScalarEvaluatorFactory;
import org.apache.hyracks.util.LogRedactionUtil;
+import org.apache.hyracks.util.annotations.AiProvenance;
import org.apache.logging.log4j.LogManager;
-import org.apache.parquet.filter2.predicate.FilterApi;
-import org.apache.parquet.filter2.predicate.FilterPredicate;
-import org.apache.parquet.filter2.predicate.Operators;
-import org.apache.parquet.io.api.Binary;
+/**
+ * Builds the row-group filter pushed into Parquet readers.
+ * <p>
+ * The result names columns and literals without choosing a physical Parquet type for either; that choice belongs
+ * to the node reading a particular file, and is made by
+ * {@code org.apache.asterix.external.input.filter.ParquetFilterConverter}.
+ */
public class ParquetFilterBuilder extends AbstractFilterBuilder {
private static final org.apache.logging.log4j.Logger LOGGER = LogManager.getLogger();
+ private final boolean pushTemporalLiterals;
+
+ /**
+ * @param pushTemporalLiterals whether date and datetime comparisons may be pushed. They may not when the
+ * collection carries a timezone option: the reader shifts what it reads into that
+ * zone, so a literal written against what the collection displays is not in the
+ * frame the file's statistics are in, and comparing the two excludes row groups
+ * that hold matching rows (MB-74031).
+ */
public ParquetFilterBuilder(ParquetExternalDatasetProjectionFiltrationInfo projectionFiltrationInfo,
- JobGenContext context, IVariableTypeEnvironment typeEnv) {
+ JobGenContext context, IVariableTypeEnvironment typeEnv, boolean pushTemporalLiterals) {
super(projectionFiltrationInfo.getFilterPaths(), projectionFiltrationInfo.getParquetRowGroupFilterExpression(),
context, typeEnv);
+ this.pushTemporalLiterals = pushTemporalLiterals;
}
- public FilterPredicate buildFilterPredicate() throws AlgebricksException {
- FilterPredicate parquetFilterPredicate = null;
+ public ParquetFilterExpression buildFilterExpression() throws AlgebricksException {
+ ParquetFilterExpression expression = null;
if (filterExpression != null) {
try {
- parquetFilterPredicate = createFilterExpression(filterExpression);
+ expression = createFilterExpression(filterExpression);
} catch (Exception e) {
LOGGER.error("Error creating Parquet row-group filter expression ", e.getMessage());
}
}
- return parquetFilterPredicate;
+ return expression;
}
- private FilterPredicate createComparisonExpression(ILogicalExpression arg1, ILogicalExpression arg2,
+ @AiProvenance(agent = AiProvenance.Agent.CLAUDE_OPUS_5, tool = AiProvenance.Tool.CLAUDE_CODE_UI, contributionKind = AiProvenance.ContributionKind.REFACTORED, notes = "Emit a type-agnostic comparison, and flip the operator when the literal is on the left")
+ private ParquetFilterExpression createComparisonExpression(ILogicalExpression arg1, ILogicalExpression arg2,
FunctionIdentifier fid) throws AlgebricksException {
ILogicalExpression columnName;
ConstantExpression constExpr;
+ boolean constantOnLeft;
if (arg1.getExpressionTag() == LogicalExpressionTag.CONSTANT) {
constExpr = (ConstantExpression) arg1;
columnName = arg2;
+ constantOnLeft = true;
} else if (arg2.getExpressionTag() == LogicalExpressionTag.CONSTANT) {
constExpr = (ConstantExpression) arg2;
columnName = arg1;
+ constantOnLeft = false;
} else {
return null;
}
@@ -93,44 +113,94 @@
return null;
}
AsterixConstantValue constantValue = (AsterixConstantValue) constExpr.getValue();
- String fieldName = createColumnExpression(columnName);
- if (fieldName == null) {
+ String[] path = createColumnExpression(columnName);
+ if (path == null) {
return null;
}
- switch (constantValue.getObject().getType().getTypeTag()) {
+ Operator operator = toOperator(fid);
+ if (operator == null) {
+ return null;
+ }
+ // a comparison reads column-then-literal, so a literal on the left reverses it: 5 < x is x > 5
+ if (constantOnLeft) {
+ operator = flip(operator);
+ }
+
+ ATypeTag tag = constantValue.getObject().getType().getTypeTag();
+ Object value;
+ switch (tag) {
case STRING:
- return createComparisionFunction(FilterApi.binaryColumn(fieldName),
- Binary.fromString(((AString) constantValue.getObject()).getStringValue()), fid);
+ value = ((AString) constantValue.getObject()).getStringValue();
+ break;
case TINYINT:
- return createComparisionFunction(FilterApi.intColumn(fieldName),
- (int) ((AInt8) constantValue.getObject()).getByteValue(), fid);
+ value = (long) ((AInt8) constantValue.getObject()).getByteValue();
+ break;
case SMALLINT:
- return createComparisionFunction(FilterApi.intColumn(fieldName),
- (int) ((AInt16) constantValue.getObject()).getShortValue(), fid);
+ value = (long) ((AInt16) constantValue.getObject()).getShortValue();
+ break;
case INTEGER:
- return createComparisionFunction(FilterApi.intColumn(fieldName),
- ((AInt32) constantValue.getObject()).getIntegerValue(), fid);
- case BOOLEAN:
- if (!fid.equals(AlgebricksBuiltinFunctions.EQ)) {
- throw new RuntimeException("Unsupported comparison function: " + fid);
- }
- return FilterApi.eq(FilterApi.booleanColumn(fieldName), constantValue.isTrue());
+ value = (long) ((AInt32) constantValue.getObject()).getIntegerValue();
+ break;
case BIGINT:
- return createComparisionFunction(FilterApi.longColumn(fieldName),
- ((AInt64) constantValue.getObject()).getLongValue(), fid);
+ value = ((AInt64) constantValue.getObject()).getLongValue();
+ break;
+ case BOOLEAN:
+ if (operator != Operator.EQ) {
+ return null;
+ }
+ value = constantValue.isTrue();
+ break;
case DOUBLE:
- return createComparisionFunction(FilterApi.doubleColumn(fieldName),
- ((ADouble) constantValue.getObject()).getDoubleValue(), fid);
+ value = ((ADouble) constantValue.getObject()).getDoubleValue();
+ break;
case DATE:
- return createComparisionFunction(FilterApi.intColumn(fieldName),
- ((ADate) constantValue.getObject()).getChrononTimeInDays(), fid);
+ if (!pushTemporalLiterals) {
+ return null;
+ }
+ value = (long) ((ADate) constantValue.getObject()).getChrononTimeInDays();
+ break;
case DATETIME:
- Long millis = ((ADateTime) constantValue.getObject()).getChrononTime();
- return createComparisionFunction(FilterApi.longColumn(fieldName),
- TimeUnit.MILLISECONDS.toMicros(millis), fid);
+ if (!pushTemporalLiterals) {
+ return null;
+ }
+ // milliseconds; the node converts to whatever unit the file stores
+ value = ((ADateTime) constantValue.getObject()).getChrononTime();
+ break;
default:
return null;
}
+ return new Comparison(path, operator, tag, value);
+ }
+
+ private static Operator toOperator(FunctionIdentifier fid) {
+ if (fid.equals(AlgebricksBuiltinFunctions.EQ)) {
+ return Operator.EQ;
+ } else if (fid.equals(AlgebricksBuiltinFunctions.GE)) {
+ return Operator.GT_EQ;
+ } else if (fid.equals(AlgebricksBuiltinFunctions.GT)) {
+ return Operator.GT;
+ } else if (fid.equals(AlgebricksBuiltinFunctions.LE)) {
+ return Operator.LT_EQ;
+ } else if (fid.equals(AlgebricksBuiltinFunctions.LT)) {
+ return Operator.LT;
+ } else {
+ return null;
+ }
+ }
+
+ private static Operator flip(Operator operator) {
+ switch (operator) {
+ case GT:
+ return Operator.LT;
+ case GT_EQ:
+ return Operator.LT_EQ;
+ case LT:
+ return Operator.GT;
+ case LT_EQ:
+ return Operator.GT_EQ;
+ default:
+ return operator;
+ }
}
@Override
@@ -138,7 +208,7 @@
return null;
}
- private FilterPredicate createFilterExpression(ILogicalExpression expr) throws AlgebricksException {
+ private ParquetFilterExpression createFilterExpression(ILogicalExpression expr) throws AlgebricksException {
if (expr == null || expr.getExpressionTag() != LogicalExpressionTag.FUNCTION_CALL) {
LOGGER.info("Unsupported expression for row group filter: "
+ LogRedactionUtil.userData(expr == null ? "NULL" : expr.toString()));
@@ -155,39 +225,22 @@
}
List<Mutable<ILogicalExpression>> args = funcExpr.getArguments();
if (fid.equals(AlgebricksBuiltinFunctions.AND) || fid.equals(AlgebricksBuiltinFunctions.OR)) {
- FilterPredicate filterPredicate = createAndOrPredicate(fid, args, 0, args.size());
- if (filterPredicate == null) {
+ ParquetFilterExpression expression = createAndOrPredicate(fid, args, 0, args.size());
+ if (expression == null) {
LOGGER.info("Unable to construct row group filter with OR/AND expression");
}
- return filterPredicate;
+ return expression;
} else {
- FilterPredicate filterPredicate =
+ ParquetFilterExpression expression =
createComparisonExpression(args.get(0).getValue(), args.get(1).getValue(), fid);
- if (filterPredicate == null) {
+ if (expression == null) {
LOGGER.info("Unable to construct row group filter");
}
- return filterPredicate;
+ return expression;
}
}
- private <T extends Comparable<T>, C extends Operators.Column<T> & Operators.SupportsLtGt> FilterPredicate createComparisionFunction(
- C column, T value, FunctionIdentifier fid) {
- if (fid.equals(AlgebricksBuiltinFunctions.EQ)) {
- return FilterApi.eq(column, value);
- } else if (fid.equals(AlgebricksBuiltinFunctions.GE)) {
- return FilterApi.gtEq(column, value);
- } else if (fid.equals(AlgebricksBuiltinFunctions.GT)) {
- return FilterApi.gt(column, value);
- } else if (fid.equals(AlgebricksBuiltinFunctions.LE)) {
- return FilterApi.ltEq(column, value);
- } else if (fid.equals(AlgebricksBuiltinFunctions.LT)) {
- return FilterApi.lt(column, value);
- } else {
- return null;
- }
- }
-
- protected String createColumnExpression(ILogicalExpression expression) {
+ protected String[] createColumnExpression(ILogicalExpression expression) {
ARecordType path = filterPaths.get(expression);
if (path.getFieldNames().length != 1) {
return null;
@@ -195,9 +248,9 @@
// The field could be a nested field
List<String> fieldList = new ArrayList<>();
fieldList = createPathExpression(path, fieldList);
- return String.join(".", fieldList);
+ return fieldList == null ? null : fieldList.toArray(new String[0]);
} else if (path.getFieldTypes()[0].getTypeTag() == ATypeTag.ANY) {
- return path.getFieldNames()[0];
+ return new String[] { path.getFieldNames()[0] };
} else {
return null;
}
@@ -219,12 +272,12 @@
}
// Converts or(pred1, pred2, pred3) to or(pred1, or(pred2, pred3))
- private FilterPredicate createAndOrPredicate(FunctionIdentifier function, List<Mutable<ILogicalExpression>> args,
- int leftInclusive, int rightExclusive) throws AlgebricksException {
+ private ParquetFilterExpression createAndOrPredicate(FunctionIdentifier function,
+ List<Mutable<ILogicalExpression>> args, int leftInclusive, int rightExclusive) throws AlgebricksException {
if (rightExclusive - leftInclusive == 1) {
return createLeafFilterPredicate(args.get(leftInclusive));
} else {
- FilterPredicate left, right;
+ ParquetFilterExpression left, right;
if (rightExclusive - leftInclusive == 2) {
left = createLeafFilterPredicate(args.get(leftInclusive));
right = createLeafFilterPredicate(args.get(leftInclusive + 1));
@@ -242,19 +295,19 @@
} else if (right == null) {
return left;
} else {
- return FilterApi.and(left, right);
+ return new ParquetFilterExpression.And(left, right);
}
} else {
if (left == null || right == null) {
return null;
}
- return FilterApi.or(left, right);
+ return new ParquetFilterExpression.Or(left, right);
}
}
}
- private FilterPredicate createLeafFilterPredicate(Mutable<ILogicalExpression> expression)
+ private ParquetFilterExpression createLeafFilterPredicate(Mutable<ILogicalExpression> expression)
throws AlgebricksException {
if (expression.get().getExpressionTag() == LogicalExpressionTag.FUNCTION_CALL) {
AbstractFunctionCallExpression functionCall = (AbstractFunctionCallExpression) expression.get();
--
To view, visit https://asterix-gerrit.ics.uci.edu/c/asterixdb/+/21853?usp=email
To unsubscribe, or for help writing mail filters, visit https://asterix-gerrit.ics.uci.edu/settings?usp=email
Gerrit-MessageType: newchange
Gerrit-Project: asterixdb
Gerrit-Branch: master
Gerrit-Change-Id: If36acc7c4df577499ffc6cfa4eaee5382acd4b8e
Gerrit-Change-Number: 21853
Gerrit-PatchSet: 1
Gerrit-Owner: Hussain Towaileb <hu...@gmail.com>