diff --git a/parquet-column/src/main/java/org/apache/parquet/filter2/predicate/Operators.java b/parquet-column/src/main/java/org/apache/parquet/filter2/predicate/Operators.java index 32b443091b..f148a99fe1 100644 --- a/parquet-column/src/main/java/org/apache/parquet/filter2/predicate/Operators.java +++ b/parquet-column/src/main/java/org/apache/parquet/filter2/predicate/Operators.java @@ -117,7 +117,7 @@ public static final class BinaryColumn extends Column implements Support } // base class for Eq, NotEq, Lt, Gt, LtEq, GtEq - static abstract class ColumnFilterPredicate> implements FilterPredicate, Serializable { + public static abstract class ColumnFilterPredicate> implements FilterPredicate, Serializable { private final Column column; private final T value; private final String toString; @@ -250,7 +250,7 @@ public R accept(Visitor visitor) { } // base class for And, Or - private static abstract class BinaryLogicalFilterPredicate implements FilterPredicate, Serializable { + public static abstract class BinaryLogicalFilterPredicate implements FilterPredicate, Serializable { private final FilterPredicate left; private final FilterPredicate right; private final String toString; diff --git a/parquet-column/src/main/java/org/apache/parquet/filter2/recordlevel/FilteringRecordMaterializer.java b/parquet-column/src/main/java/org/apache/parquet/filter2/recordlevel/FilteringRecordMaterializer.java index d8fa677924..f5381fd35b 100644 --- a/parquet-column/src/main/java/org/apache/parquet/filter2/recordlevel/FilteringRecordMaterializer.java +++ b/parquet-column/src/main/java/org/apache/parquet/filter2/recordlevel/FilteringRecordMaterializer.java @@ -84,7 +84,17 @@ public static List intArrayToList(int[] arr) { return list; } + public boolean getFilterResult() { + // find out if the predicate thinks we should keep this record + boolean keep = IncrementallyUpdatedFilterPredicateEvaluator.evaluate(filterPredicate); + // reset the stateful predicate no matter what + IncrementallyUpdatedFilterPredicateResetter.reset(filterPredicate); + return keep; + } + public T getFilteredCurrentRecord() { + return delegate.getCurrentRecord(); + } @Override public T getCurrentRecord() { diff --git a/parquet-column/src/main/java/org/apache/parquet/io/FlatSchemaRecordReaderImplementation.java b/parquet-column/src/main/java/org/apache/parquet/io/FlatSchemaRecordReaderImplementation.java new file mode 100644 index 0000000000..62812985d0 --- /dev/null +++ b/parquet-column/src/main/java/org/apache/parquet/io/FlatSchemaRecordReaderImplementation.java @@ -0,0 +1,188 @@ +/* + * 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.parquet.io; + +import java.util.Arrays; +import java.util.HashSet; + +import org.apache.parquet.Log; +import org.apache.parquet.column.ColumnReader; +import org.apache.parquet.column.impl.ColumnReadStoreImpl; +import org.apache.parquet.io.api.Converter; +import org.apache.parquet.io.api.GroupConverter; +import org.apache.parquet.io.api.RecordConsumer; +import org.apache.parquet.io.api.RecordMaterializer; +import org.apache.parquet.schema.MessageType; +import org.apache.parquet.filter2.recordlevel.FilteringRecordMaterializer; + +/** + * used to read reassembled records after filtering + * reads only the required columns for evaluating the filter + * further optimized for db applications that use flat schema + * most of the times. + * assumes a flat schema of record (No nested columns) + * + * @author Yash Datta + * + * @param the type of the materialized record + */ +class FlatSchemaRecordReaderImplementation extends RecordReader { + private static final Log LOG = Log.getLog(FlatSchemaRecordReaderImplementation.class); + private int filterStatesOffset; + private int numCols; + + private final GroupConverter recordRootConverter; + private final FilteringRecordMaterializer recordMaterializer; + + int[] maxDefinitionLevel; + private ColumnReader[] columnReaders; + + private boolean shouldSkipCurrentRecord = false; + + /** + * @param root the root of the schema + * @param recordMaterializer responsible of materializing the records + * @param validating whether we should validate against the schema + * @param columnStore where to read the column data from + * @param fColsPath all columns part of the filter + */ + public FlatSchemaRecordReaderImplementation(MessageColumnIO root, FilteringRecordMaterializer recordMaterializer, boolean validating, ColumnReadStoreImpl columnStore, HashSet fColsPath) { + this.filterStatesOffset = fColsPath.size(); + this.recordMaterializer = recordMaterializer; + this.recordRootConverter = recordMaterializer.getRootConverter(); // TODO: validator(wrap(recordMaterializer), validating, root.getType()); + PrimitiveColumnIO[] leaves = root.getLeaves().toArray(new PrimitiveColumnIO[root.getLeaves().size()]); + numCols = leaves.length; + columnReaders = new ColumnReader[leaves.length]; + int[] order = new int[leaves.length]; + maxDefinitionLevel = new int[leaves.length]; + for(int i=0;i < leaves.length; i++) + order[i] = i; + int temp = 0; + // set the order to access the columns! + for (int i = 0; i < leaves.length; i++ ) { + PrimitiveColumnIO leafColumnIO = leaves[i]; + String[] path = leafColumnIO.getColumnDescriptor().getPath(); + // path[0] will give the column name + if(fColsPath.contains(path[0])){ + int pCtemp = order[temp]; + order[temp] = order[i]; + order[i] = pCtemp; + ++temp; + } + } + + for(int i = 0; i < leaves.length; i++) { + PrimitiveColumnIO leafColumnIO = leaves[order[i]]; + maxDefinitionLevel[i] = leafColumnIO.getDefinitionLevel(); + columnReaders[i] = columnStore.getColumnReader(leafColumnIO.getColumnDescriptor()); + } + } + + //TODO: have those wrappers for a converter + private RecordConsumer validator(RecordConsumer recordConsumer, boolean validating, MessageType schema) { + return validating ? new ValidatingRecordConsumer(recordConsumer, schema) : recordConsumer; + } + + private RecordConsumer wrap(RecordConsumer recordConsumer) { + if (Log.DEBUG) { + return new RecordConsumerLoggingWrapper(recordConsumer); + } + return recordConsumer; + } + + /** + * @see org.apache.parquet.io.RecordReader#read() + */ + @Override + public T read() { + recordRootConverter.start(); + // read all columns part of the filter first + for(int i = 0; i < filterStatesOffset; i++) { + ColumnReader columnReader = columnReaders[i]; + int d = columnReader.getCurrentDefinitionLevel(); + int m = maxDefinitionLevel[i]; + + if (d >= m) { + // not null + columnReader.writeCurrentValueToConverter(); + } + columnReader.consume(); + } + + // evaluate the filter + if(!recordMaterializer.getFilterResult()) { + // row is rejected, skip the rest of the read + for(int i = filterStatesOffset; i < numCols; i++) { + ColumnReader columnReader = columnReaders[i]; + int d = columnReader.getCurrentDefinitionLevel(); + int m = maxDefinitionLevel[i]; + if (d >= m) { + // not null + columnReader.skip(); + } + columnReader.consume(); + } + + recordRootConverter.end(); + shouldSkipCurrentRecord = true; + recordMaterializer.skipCurrentRecord(); + // signal a skip + return null; + } + + // filter passes the row, need to assemble the complete row + for(int i = filterStatesOffset; i < numCols; i++) { + ColumnReader columnReader = columnReaders[i]; + int d = columnReader.getCurrentDefinitionLevel(); + int m = maxDefinitionLevel[i]; + if (d >= m) { + // not null + columnReader.writeCurrentValueToConverter(); + } + columnReader.consume(); + } + + recordRootConverter.end(); + shouldSkipCurrentRecord = false; + + return recordMaterializer.getFilteredCurrentRecord(); + } + + @Override + public boolean shouldSkipCurrentRecord() { + return shouldSkipCurrentRecord; + } + + private static void log(String string) { + LOG.debug(string); + } + + protected RecordMaterializer getMaterializer() { + return recordMaterializer; + } + + protected Converter getRecordConsumer() { + return recordRootConverter; + } + + protected Iterable getColumnReaders() { + // Converting the array to an iterable ensures that the array cannot be altered + return Arrays.asList(columnReaders); + } +} diff --git a/parquet-column/src/main/java/org/apache/parquet/io/MessageColumnIO.java b/parquet-column/src/main/java/org/apache/parquet/io/MessageColumnIO.java index cb1c8d6651..7f5cff23eb 100644 --- a/parquet-column/src/main/java/org/apache/parquet/io/MessageColumnIO.java +++ b/parquet-column/src/main/java/org/apache/parquet/io/MessageColumnIO.java @@ -23,6 +23,7 @@ import java.util.BitSet; import java.util.HashMap; import java.util.List; +import java.util.HashSet; import java.util.Map; import org.apache.parquet.Log; @@ -30,7 +31,6 @@ import org.apache.parquet.column.ColumnWriter; import org.apache.parquet.column.impl.ColumnReadStoreImpl; import org.apache.parquet.column.page.PageReadStore; -import org.apache.parquet.column.values.dictionary.IntList; import org.apache.parquet.filter.UnboundRecordFilter; import org.apache.parquet.filter2.compat.FilterCompat; import org.apache.parquet.filter2.compat.FilterCompat.Filter; @@ -39,6 +39,9 @@ import org.apache.parquet.filter2.compat.FilterCompat.UnboundRecordFilterCompat; import org.apache.parquet.filter2.compat.FilterCompat.Visitor; import org.apache.parquet.filter2.predicate.FilterPredicate; +import org.apache.parquet.filter2.predicate.Operators.ColumnFilterPredicate; +import org.apache.parquet.filter2.predicate.Operators.UserDefined; +import org.apache.parquet.filter2.predicate.Operators.BinaryLogicalFilterPredicate; import org.apache.parquet.filter2.recordlevel.FilteringRecordMaterializer; import org.apache.parquet.filter2.recordlevel.IncrementallyUpdatedFilterPredicate; import org.apache.parquet.filter2.recordlevel.IncrementallyUpdatedFilterPredicateBuilder; @@ -46,6 +49,7 @@ import org.apache.parquet.io.api.RecordConsumer; import org.apache.parquet.io.api.RecordMaterializer; import org.apache.parquet.schema.MessageType; +import org.apache.parquet.schema.Type; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntIterator; @@ -65,6 +69,7 @@ public class MessageColumnIO extends GroupColumnIO { private List leaves; private final boolean validating; + private boolean isFlatSchema; private final String createdBy; MessageColumnIO(MessageType messageType, boolean validating, String createdBy) { @@ -92,6 +97,23 @@ public RecordReader getRecordReader(PageReadStore columns, return getRecordReader(columns, recordMaterializer, FilterCompat.get(filter)); } + private void getFilterColumnNames(final FilterPredicate filterPredicate, + HashSet s) { + + if (filterPredicate instanceof BinaryLogicalFilterPredicate){ + FilterPredicate left = ((BinaryLogicalFilterPredicate)filterPredicate).getLeft(); + FilterPredicate right = ((BinaryLogicalFilterPredicate)filterPredicate).getRight(); + getFilterColumnNames(left, s); + getFilterColumnNames(right, s); + } else if ( filterPredicate instanceof ColumnFilterPredicate ) { + String[] columnPath = ((ColumnFilterPredicate)filterPredicate).getColumn().getColumnPath().toArray(); + s.add(columnPath[0]); + } else if ( filterPredicate instanceof UserDefined ) { + String[] columnPath = ((UserDefined)filterPredicate).getColumn().getColumnPath().toArray(); + s.add(columnPath[0]); + } + } + public RecordReader getRecordReader(final PageReadStore columns, final RecordMaterializer recordMaterializer, final Filter filter) { @@ -108,14 +130,37 @@ public RecordReader getRecordReader(final PageReadStore columns, public RecordReader visit(FilterPredicateCompat filterPredicateCompat) { FilterPredicate predicate = filterPredicateCompat.getFilterPredicate(); + HashSet hSet = new HashSet(); + + getFilterColumnNames(predicate, hSet); IncrementallyUpdatedFilterPredicateBuilder builder = new IncrementallyUpdatedFilterPredicateBuilder(); IncrementallyUpdatedFilterPredicate streamingPredicate = builder.build(predicate); - RecordMaterializer filteringRecordMaterializer = new FilteringRecordMaterializer( + FilteringRecordMaterializer filteringRecordMaterializer = new FilteringRecordMaterializer( recordMaterializer, leaves, builder.getValueInspectorsByColumn(), streamingPredicate); + // if only non-repeating columns present in the schema + if (isFlatSchema) { + return new FlatSchemaRecordReaderImplementation( + MessageColumnIO.this, + filteringRecordMaterializer, + validating, + new ColumnReadStoreImpl(columns, filteringRecordMaterializer.getRootConverter(), getType(), createdBy), + hSet); + } + + if ((hSet.size() > 0) && (hSet.size() != MessageColumnIO.this.getLeaves().size())) { + return new OptFilteredRecordReaderImplementation( + MessageColumnIO.this, + filteringRecordMaterializer, + validating, + new ColumnReadStoreImpl(columns, filteringRecordMaterializer.getRootConverter(), getType(), createdBy), + hSet); + } + + // If filters are applied on all columns! return new RecordReaderImplementation( MessageColumnIO.this, filteringRecordMaterializer, @@ -506,6 +551,14 @@ void setLevels() { void setLeaves(List leaves) { this.leaves = leaves; + isFlatSchema = true; + for (PrimitiveColumnIO primitiveColumnIO : leaves) { + if (primitiveColumnIO.getType().getRepetition() == Type.Repetition.REPEATED || + primitiveColumnIO.getDefinitionLevel() > 1) { + isFlatSchema = false; + break; + } + } } public List getLeaves() { diff --git a/parquet-column/src/main/java/org/apache/parquet/io/OptFilteredRecordReaderImplementation.java b/parquet-column/src/main/java/org/apache/parquet/io/OptFilteredRecordReaderImplementation.java new file mode 100644 index 0000000000..f458e948fe --- /dev/null +++ b/parquet-column/src/main/java/org/apache/parquet/io/OptFilteredRecordReaderImplementation.java @@ -0,0 +1,552 @@ +/* + * 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.parquet.io; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.parquet.Log; +import org.apache.parquet.column.ColumnReader; +import org.apache.parquet.column.impl.ColumnReadStoreImpl; +import org.apache.parquet.io.api.Converter; +import org.apache.parquet.io.api.GroupConverter; +import org.apache.parquet.io.api.PrimitiveConverter; +import org.apache.parquet.io.api.RecordConsumer; +import org.apache.parquet.io.api.RecordMaterializer; +import org.apache.parquet.schema.MessageType; +import org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName; +import org.apache.parquet.filter2.recordlevel.FilteringRecordMaterializer; + +/** + * used to read reassembled records + * Optimized version, reads only the columns required + * for evaluating the filter, then proceeds to skip + * or read the rest of the columns, depending on + * whether filter rejects or accepts the row. + * + * @author Julien Le Dem + * + * @param the type of the materialized record + */ +class OptFilteredRecordReaderImplementation extends RecordReader { + private static final Log LOG = Log.getLog(OptFilteredRecordReaderImplementation.class); + private int filterStatesOffsetId; + private int numCols; + int[] order; + + public static class Case { + + private int id; + private final int startLevel; + private final int depth; + private final int nextLevel; + private final boolean goingUp; + private final boolean goingDown; + private final int nextState; + private final boolean defined; + + public Case(int startLevel, int depth, int nextLevel, int nextState, boolean defined) { + this.startLevel = startLevel; + this.depth = depth; + this.nextLevel = nextLevel; + this.nextState = nextState; + this.defined = defined; + // means going up the tree (towards the leaves) of the record + // true if we need to open up groups in this case + goingUp = startLevel <= depth; + // means going down the tree (towards the root) of the record + // true if we need to close groups in this case + goingDown = depth + 1 > nextLevel; + } + + public void setID(int id) { + this.id = id; + } + + @Override + // this implementation is buggy but the simpler one bellow has duplicates. + // it still works but generates more code than necessary + // a middle ground is necessary +// public int hashCode() { +// int hashCode = 0; +// if (goingUp) { +// hashCode += 1 * (1 + startLevel) + 2 * (1 + depth); +// } +// if (goingDown) { +// hashCode += 3 * (1 + depth) + 5 * (1 + nextLevel); +// } +// return hashCode; +// } + + public int hashCode() { + int hashCode = 17; + hashCode += 31 * startLevel; + hashCode += 31 * depth; + hashCode += 31 * nextLevel; + hashCode += 31 * nextState; + hashCode += 31 * (defined ? 0 : 1); + return hashCode; + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof Case) { + return equals((Case)obj); + } + return false; + }; + + // see comment for hashCode above +// public boolean equals(Case other) { +// if (goingUp && !other.goingUp || !goingUp && other.goingUp) { +// return false; +// } +// if (goingUp && other.goingUp && (startLevel != other.startLevel || depth != other.depth)) { +// return false; +// } +// if (goingDown && !other.goingDown || !goingDown && other.goingDown) { +// return false; +// } +// if (goingDown && other.goingDown && (depth != other.depth || nextLevel != other.nextLevel)) { +// return false; +// } +// return true; +// } + + public boolean equals(Case other) { + return startLevel == other.startLevel + && depth == other.depth + && nextLevel == other.nextLevel + && nextState == other.nextState + && ((defined && other.defined) || (!defined && !other.defined)); + } + + public int getID() { + return id; + } + + public int getStartLevel() { + return startLevel; + } + + public int getDepth() { + return depth; + } + public int getNextLevel() { + return nextLevel; + } + + public int getNextState() { + return nextState; + } + + public boolean isGoingUp() { + return goingUp; + } + + public boolean isGoingDown() { + return goingDown; + } + + public boolean isDefined() { + return defined; + } + + @Override + public String toString() { + return "Case " + startLevel + " -> " + depth + " -> " + nextLevel + "; goto sate_"+getNextState(); + } + + } + + public static class State { + + public final int id; + public final PrimitiveColumnIO primitiveColumnIO; + public final int maxDefinitionLevel; + public final int maxRepetitionLevel; + public final PrimitiveTypeName primitive; + public final ColumnReader column; + public final String[] fieldPath; // indexed by currentLevel + public final int[] indexFieldPath; // indexed by currentLevel + public final GroupConverter[] groupConverterPath; + public final PrimitiveConverter primitiveConverter; + public final String primitiveField; + public final int primitiveFieldIndex; + public final int[] nextLevel; //indexed by next r + + private int[] definitionLevelToDepth; // indexed by current d + private State[] nextState; // indexed by next r + private Case[][][] caseLookup; + private List definedCases; + private List undefinedCases; + + private State(int id, PrimitiveColumnIO primitiveColumnIO, ColumnReader column, int[] nextLevel, GroupConverter[] groupConverterPath, PrimitiveConverter primitiveConverter) { + this.id = id; + this.primitiveColumnIO = primitiveColumnIO; + this.maxDefinitionLevel = primitiveColumnIO.getDefinitionLevel(); + this.maxRepetitionLevel = primitiveColumnIO.getRepetitionLevel(); + this.column = column; + this.nextLevel = nextLevel; + this.groupConverterPath = groupConverterPath; + this.primitiveConverter = primitiveConverter; + this.primitive = primitiveColumnIO.getType().asPrimitiveType().getPrimitiveTypeName(); + this.fieldPath = primitiveColumnIO.getFieldPath(); + this.primitiveField = fieldPath[fieldPath.length - 1]; + this.indexFieldPath = primitiveColumnIO.getIndexFieldPath(); + this.primitiveFieldIndex = indexFieldPath[indexFieldPath.length - 1]; + } + + public int getDepth(int definitionLevel) { + return definitionLevelToDepth[definitionLevel]; + } + + public List getDefinedCases() { + return definedCases; + } + + public List getUndefinedCases() { + return undefinedCases; + } + + public Case getCase(int currentLevel, int d, int nextR) { + return caseLookup[currentLevel][d][nextR]; + } + + public State getNextState(int nextR) { + return nextState[nextR]; + } + } + + private final GroupConverter recordRootConverter; + private final FilteringRecordMaterializer recordMaterializer; + + private State[] states; + private ColumnReader[] columnReaders; + + private boolean shouldSkipCurrentRecord = false; + + /** + * @param root the root of the schema + * @param recordMaterializer responsible of materializing the records + * @param validating whether we should validate against the schema + * @param columnStore where to read the column data from + */ + public OptFilteredRecordReaderImplementation(MessageColumnIO root, FilteringRecordMaterializer recordMaterializer, boolean validating, ColumnReadStoreImpl columnStore, HashSet fColsPath) { + this.recordMaterializer = recordMaterializer; + this.recordRootConverter = recordMaterializer.getRootConverter(); // TODO: validator(wrap(recordMaterializer), validating, root.getType()); + PrimitiveColumnIO[] leaves = root.getLeaves().toArray(new PrimitiveColumnIO[root.getLeaves().size()]); + numCols = leaves.length; + columnReaders = new ColumnReader[leaves.length]; + int[][] nextColumnIdxForRepLevel = new int[leaves.length][]; + int[][] levelToClose = new int[leaves.length][]; + GroupConverter[][] groupConverterPaths = new GroupConverter[leaves.length][]; + PrimitiveConverter[] leafConverters = new PrimitiveConverter[leaves.length]; + int[] firstIndexForLevel = new int[256]; // "256 levels of nesting ought to be enough for anybody" + // rearrange the leaves! + order = new int[leaves.length+1]; + for(int i=0;i <= leaves.length; i++) + order[i] = i; + int temp = 0; + for (int i = 0; i < leaves.length; i++ ) { + PrimitiveColumnIO leafColumnIO = leaves[i]; + String[] path = leafColumnIO.getColumnDescriptor().getPath(); + // path[0] will give the root name ? + if(fColsPath.contains(path[0])){ + int pCtemp = order[temp]; + order[temp] = order[i]; + order[i] = pCtemp; + ++temp; + } + } + this.filterStatesOffsetId = order[temp]; + // build the automaton in the 'order' order + for (int k = 0; k < leaves.length; k++) { + int i = order[k]; + PrimitiveColumnIO leafColumnIO = leaves[i]; + //generate converters along the path from root to leaf + final int[] indexFieldPath = leafColumnIO.getIndexFieldPath(); + groupConverterPaths[i] = new GroupConverter[indexFieldPath.length - 1]; + GroupConverter current = this.recordRootConverter; + for (int j = 0; j < indexFieldPath.length - 1; j++) { + current = current.getConverter(indexFieldPath[j]).asGroupConverter(); + groupConverterPaths[i][j] = current; + } + leafConverters[i] = current.getConverter(indexFieldPath[indexFieldPath.length - 1]).asPrimitiveConverter(); + columnReaders[i] = columnStore.getColumnReader(leafColumnIO.getColumnDescriptor()); + int maxRepetitionLevel = leafColumnIO.getRepetitionLevel(); + nextColumnIdxForRepLevel[i] = new int[maxRepetitionLevel+1]; + + levelToClose[i] = new int[maxRepetitionLevel+1]; //next level + for (int nextRepLevel = 0; nextRepLevel <= maxRepetitionLevel; ++nextRepLevel) { + // remember which is the first for this level + if (leafColumnIO.isFirst(nextRepLevel)) { + firstIndexForLevel[nextRepLevel] = i; + } + int nextColIdx; + //TODO: when we use nextColumnIdxForRepLevel, should we provide current rep level or the rep level for next item + // figure out automaton transition + if (nextRepLevel == 0) { // 0 always means jump to the next (the last one being a special case) + nextColIdx = order[k + 1]; + } else if (leafColumnIO.isLast(nextRepLevel)) { // when we are at the last of the next repetition level we jump back to the first + nextColIdx = firstIndexForLevel[nextRepLevel]; + } else { // otherwise we just go back to the next. + nextColIdx = order[k + 1]; + } + // figure out which level down the tree we need to go back + if (nextColIdx == leaves.length) { // reached the end of the record => close all levels + levelToClose[i][nextRepLevel] = 0; + } else if (leafColumnIO.isLast(nextRepLevel)) { // reached the end of this level => close the repetition level + ColumnIO parent = leafColumnIO.getParent(nextRepLevel); + levelToClose[i][nextRepLevel] = parent.getFieldPath().length == 0 ? 0 : parent.getFieldPath().length - 1; + } else { // otherwise close until the next common parent + levelToClose[i][nextRepLevel] = getCommonParentLevel( + leafColumnIO.getFieldPath(), + leaves[nextColIdx].getFieldPath()); + } + // sanity check: that would be a bug + if (levelToClose[i][nextRepLevel] > leaves[i].getFieldPath().length-1) { + throw new ParquetEncodingException(Arrays.toString(leaves[i].getFieldPath())+" -("+nextRepLevel+")-> "+levelToClose[i][nextRepLevel]); + } + nextColumnIdxForRepLevel[i][nextRepLevel] = nextColIdx; + } + } + states = new State[leaves.length]; + for (int k = 0; k < leaves.length; k++) { + int i = order[k]; + states[i] = new State(i, leaves[i], columnReaders[i], levelToClose[i], groupConverterPaths[i], leafConverters[i]); + int[] definitionLevelToDepth = new int[states[i].primitiveColumnIO.getDefinitionLevel() + 1]; + // for each possible definition level, determine the depth at which to create groups + final ColumnIO[] path = states[i].primitiveColumnIO.getPath(); + int depth = 0; + for (int d = 0; d < definitionLevelToDepth.length; ++d) { + while (depth < (states[i].fieldPath.length - 1) + && d >= path[depth + 1].getDefinitionLevel() + ) { + ++ depth; + } + definitionLevelToDepth[d] = depth - 1; + } + states[i].definitionLevelToDepth = definitionLevelToDepth; + } + for (int k = 0; k < leaves.length; k++) { + int i = order[k]; + State state = states[i]; + int[] nextStateIds = nextColumnIdxForRepLevel[i]; + state.nextState = new State[nextStateIds.length]; + for (int j = 0; j < nextStateIds.length; j++) { + state.nextState[j] = nextStateIds[j] == states.length ? null : states[nextStateIds[j]]; + } + } + for (int k = 0; k < states.length; k++) { + int i = order[k]; + State state = states[i]; + final Map definedCases = new HashMap(); + final Map undefinedCases = new HashMap(); + Case[][][] caseLookup = new Case[state.fieldPath.length][][]; + for (int currentLevel = 0; currentLevel < state.fieldPath.length; ++ currentLevel) { + caseLookup[currentLevel] = new Case[state.maxDefinitionLevel+1][]; + for (int d = 0; d <= state.maxDefinitionLevel; ++ d) { + caseLookup[currentLevel][d] = new Case[state.maxRepetitionLevel+1]; + for (int nextR = 0; nextR <= state.maxRepetitionLevel; ++ nextR) { + int caseStartLevel = currentLevel; + int caseDepth = Math.max(state.getDepth(d), caseStartLevel - 1); + int caseNextLevel = Math.min(state.nextLevel[nextR], caseDepth + 1); + Case currentCase = new Case(caseStartLevel, caseDepth, caseNextLevel, getNextReader(state.id, nextR), d == state.maxDefinitionLevel); + Map cases = currentCase.isDefined() ? definedCases : undefinedCases; + if (!cases.containsKey(currentCase)) { + currentCase.setID(cases.size()); + cases.put(currentCase, currentCase); + } else { + currentCase = cases.get(currentCase); + } + caseLookup[currentLevel][d][nextR] = currentCase; + } + } + } + state.caseLookup = caseLookup; + state.definedCases = new ArrayList(definedCases.values()); + state.undefinedCases = new ArrayList(undefinedCases.values()); + Comparator caseComparator = new Comparator() { + @Override + public int compare(Case o1, Case o2) { + return o1.id - o2.id; + } + }; + Collections.sort(state.definedCases, caseComparator); + Collections.sort(state.undefinedCases, caseComparator); + } + } + + //TODO: have those wrappers for a converter + private RecordConsumer validator(RecordConsumer recordConsumer, boolean validating, MessageType schema) { + return validating ? new ValidatingRecordConsumer(recordConsumer, schema) : recordConsumer; + } + + private RecordConsumer wrap(RecordConsumer recordConsumer) { + if (Log.DEBUG) { + return new RecordConsumerLoggingWrapper(recordConsumer); + } + return recordConsumer; + } + + /** + * @see parquet.io.RecordReader#read() + */ + @Override + public T read() { + int currentLevel = 0; + recordRootConverter.start(); + State currentState = states[order[0]]; + // reconstruct the required rows + do { + ColumnReader columnReader = currentState.column; + int d = columnReader.getCurrentDefinitionLevel(); + // creating needed nested groups until the current field (opening tags) + int depth = currentState.definitionLevelToDepth[d]; + for (; currentLevel <= depth; ++currentLevel) { + currentState.groupConverterPath[currentLevel].start(); + } + // currentLevel = depth + 1 at this point + // set the current value + if (d >= currentState.maxDefinitionLevel) { + // not null + columnReader.writeCurrentValueToConverter(); + } + columnReader.consume(); + + int nextR = currentState.maxRepetitionLevel == 0 ? 0 : columnReader.getCurrentRepetitionLevel(); + // level to go to close current groups + int next = currentState.nextLevel[nextR]; + for (; currentLevel > next; currentLevel--) { + currentState.groupConverterPath[currentLevel - 1].end(); + } + + currentState = currentState.nextState[nextR]; + } while (currentState.id != filterStatesOffsetId); + + // evaluate the filter + if(!recordMaterializer.getFilterResult()) { + // filter rejects the row, skip reading rest of the columns + while(currentState!=null) { + ColumnReader columnReader = currentState.column; + int d = columnReader.getCurrentDefinitionLevel(); + if (d >= currentState.maxDefinitionLevel) { + // not null + columnReader.skip(); + } + + columnReader.consume(); + int nextR = currentState.maxRepetitionLevel == 0 ? 0 : columnReader.getCurrentRepetitionLevel(); + currentState = currentState.nextState[nextR]; + } + + shouldSkipCurrentRecord = true; + recordMaterializer.skipCurrentRecord(); + // signal a skip + return null; + } + + // filter passes the row, assemble the rest of the row + while(currentState!=null) { + ColumnReader columnReader = currentState.column; + int d = columnReader.getCurrentDefinitionLevel(); + // creating needed nested groups until the current field (opening tags) + int depth = currentState.definitionLevelToDepth[d]; + for (; currentLevel <= depth; ++currentLevel) { + currentState.groupConverterPath[currentLevel].start(); + } + // currentLevel = depth + 1 at this point + // set the current value + if (d >= currentState.maxDefinitionLevel) { + // not null + columnReader.writeCurrentValueToConverter(); + } + + columnReader.consume(); + int nextR = currentState.maxRepetitionLevel == 0 ? 0 : columnReader.getCurrentRepetitionLevel(); + // level to go to close current groups + int next = currentState.nextLevel[nextR]; + for (; currentLevel > next; currentLevel--) { + currentState.groupConverterPath[currentLevel - 1].end(); + } + + currentState = currentState.nextState[nextR]; + } + + recordRootConverter.end(); + shouldSkipCurrentRecord = false; + + return recordMaterializer.getFilteredCurrentRecord(); + } + + + @Override + public boolean shouldSkipCurrentRecord() { + return shouldSkipCurrentRecord; + } + + private static void log(String string) { + LOG.debug(string); + } + + int getNextReader(int current, int nextRepetitionLevel) { + State nextState = states[current].nextState[nextRepetitionLevel]; + return nextState == null ? states.length : nextState.id; + } + + int getNextLevel(int current, int nextRepetitionLevel) { + return states[current].nextLevel[nextRepetitionLevel]; + } + + private int getCommonParentLevel(String[] previous, String[] next) { + int i = 0; + while (i < Math.min(previous.length, next.length) && previous[i].equals(next[i])) { + ++i; + } + return i; + } + + protected int getStateCount() { + return states.length; + } + + protected State getState(int i) { + return states[i]; + } + + protected RecordMaterializer getMaterializer() { + return recordMaterializer; + } + + protected Converter getRecordConsumer() { + return recordRootConverter; + } + + protected Iterable getColumnReaders() { + // Converting the array to an iterable ensures that the array cannot be altered + return Arrays.asList(columnReaders); + } +} diff --git a/parquet-hadoop/src/test/java/org/apache/parquet/filter2/recordlevel/FlatSchemaWriter.java b/parquet-hadoop/src/test/java/org/apache/parquet/filter2/recordlevel/FlatSchemaWriter.java new file mode 100644 index 0000000000..bbc4e033e3 --- /dev/null +++ b/parquet-hadoop/src/test/java/org/apache/parquet/filter2/recordlevel/FlatSchemaWriter.java @@ -0,0 +1,198 @@ +/* + * 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.parquet.filter2.recordlevel; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.fs.Path; + +import org.apache.parquet.example.data.Group; +import org.apache.parquet.example.data.simple.SimpleGroup; +import org.apache.parquet.filter2.compat.FilterCompat.Filter; +import org.apache.parquet.hadoop.ParquetReader; +import org.apache.parquet.hadoop.ParquetWriter; +import org.apache.parquet.hadoop.example.GroupReadSupport; +import org.apache.parquet.hadoop.example.GroupWriteSupport; +import org.apache.parquet.schema.MessageType; +import org.apache.parquet.schema.MessageTypeParser; + +public class FlatSchemaWriter { + private static final String schemaString = + "message flatschema {\n" + + " required int32 col0;\n" + + " required int32 col1;\n" + + " optional binary col2 (UTF8);\n" + + " optional binary col3 (UTF8);\n" + + " optional int32 col4;\n" + + " optional double col5;\n" + + " optional int32 col6;\n" + + "}\n"; + + private static final MessageType schema = MessageTypeParser.parseMessageType(schemaString); + + public static class FlatSchema { + private final int col0; + private final int col1; + private final String col2; + private final String col3; + private final int col4; + private final double col5; + private final int col6; + + public FlatSchema(int pcol0, int pcol1, String pcol2, String pcol3, int pcol4, double pcol5, int pcol6) { + this.col0 = pcol0; + this.col1 = pcol1; + this.col2 = pcol2; + this.col3 = pcol3; + this.col4 = pcol4; + this.col5 = pcol5; + this.col6 = pcol6; + } + + public int col0() { + return col0; + } + + public int col1() { + return col1; + } + + public int col4() { + return col4; + } + + public int col6() { + return col6; + } + + public double col5() { + return col5; + } + + public String getCol2() { + return col2; + } + + public String getCol3() { + return col3; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + FlatSchema user = (FlatSchema) o; + + if (col0 != user.col0) return false; + if (col1 != user.col1) return false; + if (col4 != user.col4) return false; + if (col5 != user.col5) return false; + if (col6 != user.col6) return false; + + if (col2 != null ? !col2.equals(user.col2) : user.col2 != null) return false; + if (col3 != null ? !col3.equals(user.col3) : user.col3 != null) return false; + + return true; + } + + @Override + public int hashCode() { + int result = (int) (col0 ^ (col0 >>> 32)); + result = 31 * result + (col2 != null ? col2.hashCode() : 0); + result = 31 * result + (col3 != null ? col3.hashCode() : 0); + result = 31 * result + (int)(col6 ^ (col6 >>> 32)); + return result; + } + } + + public static SimpleGroup groupFromUser(FlatSchema user) { + SimpleGroup root = new SimpleGroup(schema); + root.append("col0", user.col0()); + root.append("col1", user.col1()); + + if (user.getCol2() != null) { + root.append("col2", user.getCol2()); + } + + if (user.getCol3() != null) { + root.append("col3", user.getCol3()); + } + + root.append("col4", user.col4()); + root.append("col5", user.col5()); + root.append("col6", user.col6()); + return root; + } + + public static File writeToFile(List records) throws IOException { + File f = File.createTempFile("phonebook2", ".parquet"); + f.deleteOnExit(); + if (!f.delete()) { + throw new IOException("couldn't delete tmp file" + f); + } + + writeToFile(f, records); + + return f; + } + + public static void writeToFile(File f, List records) throws IOException { + Configuration conf = new Configuration(); + GroupWriteSupport.setSchema(schema, conf); + + ParquetWriter writer = new ParquetWriter(new Path(f.getAbsolutePath()), conf, new GroupWriteSupport()); + for (FlatSchema u : records) { + writer.write(groupFromUser(u)); + } + writer.close(); + } + + public static List readFile(File f, Filter filter) throws IOException { + Configuration conf = new Configuration(); + GroupWriteSupport.setSchema(schema, conf); + + ParquetReader reader = + ParquetReader.builder(new GroupReadSupport(), new Path(f.getAbsolutePath())) + .withConf(conf) + .withFilter(filter) + .build(); + + Group current; + List users = new ArrayList(); + + current = reader.read(); + while (current != null) { + users.add(current); + current = reader.read(); + } + + return users; + } + + public static void main(String[] args) throws IOException { + File f = new File(args[0]); + writeToFile(f, TestRecordLevelFilters.makeRecords()); + } + +} diff --git a/parquet-hadoop/src/test/java/org/apache/parquet/filter2/recordlevel/TestRecordLevelFilters.java b/parquet-hadoop/src/test/java/org/apache/parquet/filter2/recordlevel/TestRecordLevelFilters.java index 5a7d02f19f..c0fe52a2ff 100644 --- a/parquet-hadoop/src/test/java/org/apache/parquet/filter2/recordlevel/TestRecordLevelFilters.java +++ b/parquet-hadoop/src/test/java/org/apache/parquet/filter2/recordlevel/TestRecordLevelFilters.java @@ -34,10 +34,12 @@ import org.apache.parquet.filter2.compat.FilterCompat; import org.apache.parquet.filter2.predicate.FilterPredicate; import org.apache.parquet.filter2.predicate.Operators.BinaryColumn; +import org.apache.parquet.filter2.predicate.Operators.IntColumn; import org.apache.parquet.filter2.predicate.Operators.DoubleColumn; import org.apache.parquet.filter2.predicate.Operators.LongColumn; import org.apache.parquet.filter2.predicate.Statistics; import org.apache.parquet.filter2.predicate.UserDefinedPredicate; +import org.apache.parquet.filter2.recordlevel.FlatSchemaWriter.FlatSchema; import org.apache.parquet.filter2.recordlevel.PhoneBookWriter.Location; import org.apache.parquet.filter2.recordlevel.PhoneBookWriter.PhoneNumber; import org.apache.parquet.filter2.recordlevel.PhoneBookWriter.User; @@ -46,6 +48,7 @@ import static org.junit.Assert.assertEquals; import static org.apache.parquet.filter2.predicate.FilterApi.and; import static org.apache.parquet.filter2.predicate.FilterApi.binaryColumn; +import static org.apache.parquet.filter2.predicate.FilterApi.intColumn; import static org.apache.parquet.filter2.predicate.FilterApi.doubleColumn; import static org.apache.parquet.filter2.predicate.FilterApi.longColumn; import static org.apache.parquet.filter2.predicate.FilterApi.eq; @@ -92,19 +95,37 @@ public static List makeUsers() { return users; } + public static List makeRecords() { + List records = new ArrayList(); + records.add(new FlatSchema(17, 45, null, null, 89, 91.0, 78)); + records.add(new FlatSchema(18, 87, "bob", "opera", 90, 12.0, 104)); + records.add(new FlatSchema(19, 109, "test", "ie", 91, 45.7, 116)); + records.add(new FlatSchema(20, 119, "test", "firefox", 92, 67.9, 119)); + records.add(new FlatSchema(21, 127, "test", "chrome", 93, 89.2, 189)); + return records; + } + private static File phonebookFile; + private static File testBookFile; private static List users; + private static List records; @BeforeClass public static void setup() throws IOException{ users = makeUsers(); + records = makeRecords(); phonebookFile = PhoneBookWriter.writeToFile(users); + testBookFile = FlatSchemaWriter.writeToFile(records); } private static interface UserFilter { boolean keep(User u); } + private static interface FlatSchemaFilter { + boolean keep(FlatSchema u); + } + private static List getExpected(UserFilter f) { List expected = new ArrayList(); for (User u : users) { @@ -115,6 +136,16 @@ private static List getExpected(UserFilter f) { return expected; } + private static List getExpected(FlatSchemaFilter f) { + List expected = new ArrayList(); + for (FlatSchema u : records) { + if (f.keep(u)) { + expected.add(FlatSchemaWriter.groupFromUser(u)); + } + } + return expected; + } + private static void assertFilter(List found, UserFilter f) { List expected = getExpected(f); assertEquals(expected.size(), found.size()); @@ -125,6 +156,16 @@ private static void assertFilter(List found, UserFilter f) { } } + private static void assertFilter(List found, FlatSchemaFilter f) { + List expected = getExpected(f); + assertEquals(expected.size(), found.size()); + Iterator expectedIter = expected.iterator(); + Iterator foundIter = found.iterator(); + while(expectedIter.hasNext()) { + assertEquals(expectedIter.next().toString(), foundIter.next().toString()); + } + } + @Test public void testNoFilter() throws Exception { List found = PhoneBookWriter.readFile(phonebookFile, FilterCompat.NOOP); @@ -273,4 +314,24 @@ public boolean keep(User u) { } }); } + + @Test + public void testComplexFlatRecords() throws Exception { + BinaryColumn col2 = binaryColumn("col2"); + DoubleColumn col5 = doubleColumn("col5"); + IntColumn col4 = intColumn("col4"); + + FilterPredicate pred = and(eq(col2, Binary.fromString("test")), or(eq(col5, 89.2), eq(col4, 92))); + List found = PhoneBookWriter.readFile(testBookFile, FilterCompat.get(pred)); + + assertFilter(found, new FlatSchemaFilter() { + @Override + public boolean keep(FlatSchema u) { + String col2 = u.getCol2(); + Double col5 = u.col5(); + long col4 = u.col4(); + return (((col5 == 89.2)) || col4 == 92) && "test".equals(col2); + } + }); + } }