clintropolis commented on code in PR #14542: URL: https://github.com/apache/druid/pull/14542#discussion_r1260776677
########## processing/src/main/java/org/apache/druid/query/filter/EqualityFilter.java: ########## @@ -0,0 +1,578 @@ +/* + * 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.druid.query.filter; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.common.base.Predicate; +import com.google.common.base.Predicates; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Range; +import com.google.common.collect.RangeSet; +import com.google.common.collect.TreeRangeSet; +import org.apache.druid.error.DruidException; +import org.apache.druid.java.util.common.IAE; +import org.apache.druid.math.expr.ExprEval; +import org.apache.druid.math.expr.ExpressionType; +import org.apache.druid.query.cache.CacheKeyBuilder; +import org.apache.druid.query.extraction.ExtractionFn; +import org.apache.druid.query.filter.vector.VectorValueMatcher; +import org.apache.druid.query.filter.vector.VectorValueMatcherColumnProcessorFactory; +import org.apache.druid.segment.BaseDoubleColumnValueSelector; +import org.apache.druid.segment.BaseFloatColumnValueSelector; +import org.apache.druid.segment.BaseLongColumnValueSelector; +import org.apache.druid.segment.BaseObjectColumnValueSelector; +import org.apache.druid.segment.ColumnInspector; +import org.apache.druid.segment.ColumnProcessorFactory; +import org.apache.druid.segment.ColumnProcessors; +import org.apache.druid.segment.ColumnSelector; +import org.apache.druid.segment.ColumnSelectorFactory; +import org.apache.druid.segment.DimensionSelector; +import org.apache.druid.segment.column.ColumnCapabilities; +import org.apache.druid.segment.column.ColumnIndexSupplier; +import org.apache.druid.segment.column.ColumnType; +import org.apache.druid.segment.column.TypeSignature; +import org.apache.druid.segment.column.TypeStrategy; +import org.apache.druid.segment.column.ValueType; +import org.apache.druid.segment.filter.DimensionPredicateFilter; +import org.apache.druid.segment.filter.Filters; +import org.apache.druid.segment.filter.PredicateValueMatcherFactory; +import org.apache.druid.segment.filter.ValueMatchers; +import org.apache.druid.segment.index.BitmapColumnIndex; +import org.apache.druid.segment.index.semantic.StringValueSetIndex; +import org.apache.druid.segment.nested.StructuredData; +import org.apache.druid.segment.vector.VectorColumnSelectorFactory; + +import javax.annotation.Nullable; +import java.nio.ByteBuffer; +import java.util.Comparator; +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +public class EqualityFilter extends AbstractOptimizableDimFilter implements Filter +{ + private final String column; + private final ColumnType matchValueType; + private final Object matchValue; + @Nullable + private final ExtractionFn extractionFn; + @Nullable + private final FilterTuning filterTuning; + private final DruidPredicateFactory predicateFactory; + + @JsonCreator + public EqualityFilter( + @JsonProperty("column") String column, + @JsonProperty("matchValueType") ColumnType matchValueType, + @JsonProperty("matchValue") Object matchValue, + @JsonProperty("extractionFn") @Nullable ExtractionFn extractionFn, + @JsonProperty("filterTuning") @Nullable FilterTuning filterTuning + ) + { + if (column == null) { + throw DruidException.forPersona(DruidException.Persona.USER) + .ofCategory(DruidException.Category.INVALID_INPUT) + .build("Invalid equality filter, column cannot be null"); + } + this.column = column; + if (matchValueType == null) { + throw DruidException.forPersona(DruidException.Persona.USER) + .ofCategory(DruidException.Category.INVALID_INPUT) + .build("Invalid equality filter on column [%s], matchValueType cannot be null", column); + } + this.matchValueType = matchValueType; + if (matchValue == null) { + throw DruidException.forPersona(DruidException.Persona.USER) + .ofCategory(DruidException.Category.INVALID_INPUT) + .build("Invalid equality filter on column [%s], matchValue cannot be null", column); + } + this.matchValue = matchValue; + this.extractionFn = extractionFn; + this.filterTuning = filterTuning; + this.predicateFactory = new EqualityPredicateFactory(matchValue, matchValueType); + } + + @Override + public byte[] getCacheKey() + { + final TypeStrategy<Object> typeStrategy = matchValueType.getStrategy(); + final int size = typeStrategy.estimateSizeBytes(matchValue); + final ByteBuffer valueBuffer = ByteBuffer.allocate(size); + typeStrategy.write(valueBuffer, matchValue, size); + return new CacheKeyBuilder(DimFilterUtils.EQUALS_CACHE_ID) + .appendByte(DimFilterUtils.STRING_SEPARATOR) + .appendString(column) + .appendByte(DimFilterUtils.STRING_SEPARATOR) + .appendString(matchValueType.asTypeString()) + .appendByte(DimFilterUtils.STRING_SEPARATOR) + .appendByteArray(valueBuffer.array()) + .appendByte(DimFilterUtils.STRING_SEPARATOR) + .appendByteArray(extractionFn == null ? new byte[0] : extractionFn.getCacheKey()) + .build(); + } + + @Override + public DimFilter optimize() + { + return this; + } + + @Override + public Filter toFilter() + { + if (extractionFn == null) { + return this; + } else { + return new DimensionPredicateFilter(column, predicateFactory, extractionFn, filterTuning); + } + } + + @JsonProperty + public String getColumn() + { + return column; + } + + @JsonProperty + public ColumnType getMatchValueType() + { + return matchValueType; + } + + @JsonProperty + public Object getMatchValue() + { + return matchValue; + } + + @Nullable + @JsonProperty + @JsonInclude(JsonInclude.Include.NON_NULL) + public ExtractionFn getExtractionFn() + { + return extractionFn; + } + + @Nullable + @JsonProperty + @JsonInclude(JsonInclude.Include.NON_NULL) + public FilterTuning getFilterTuning() + { + return filterTuning; + } + + @Override + public String toString() + { + DimFilter.DimFilterToStringBuilder bob = new DimFilter.DimFilterToStringBuilder().appendDimension( + column, + extractionFn + ) + .append(" = ") + .append(matchValue); + + if (!ColumnType.STRING.equals(matchValueType)) { + bob.append(" (" + matchValueType.asTypeString() + ")"); + } + return bob.appendFilterTuning(filterTuning).build(); + } + + @Override + public boolean equals(Object o) + { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EqualityFilter that = (EqualityFilter) o; + if (!column.equals(that.column)) { + return false; + } + if (!Objects.equals(matchValueType, that.matchValueType)) { + return false; + } + if (!Objects.equals(extractionFn, that.extractionFn)) { + return false; + } + if (!Objects.equals(filterTuning, that.filterTuning)) { + return false; + } + if (matchValueType.isArray()) { + // just use predicate to see if the values are the same + final ExprEval<?> thatValue = ExprEval.ofType( + ExpressionType.fromColumnType(that.matchValueType), + that.matchValue + ); + final Predicate<Object[]> arrayPredicate = predicateFactory.makeArrayPredicate(matchValueType); + return arrayPredicate.apply(thatValue.asArray()); + } else { + return Objects.equals(matchValue, that.matchValue); + } + } + + @Override + public int hashCode() + { + return Objects.hash(column, matchValueType, matchValue, extractionFn, filterTuning); + } + + @Override + public RangeSet<String> getDimensionRangeSet(String dimension) + { + if (!Objects.equals(getColumn(), dimension) || getExtractionFn() != null) { + return null; + } + RangeSet<String> retSet = TreeRangeSet.create(); + retSet.add(Range.singleton(String.valueOf(matchValue))); + return retSet; + } + + @Nullable + @Override + public BitmapColumnIndex getBitmapColumnIndex(ColumnIndexSelector selector) + { + if (!Filters.checkFilterTuningUseIndex(column, selector, filterTuning)) { + return null; + } + + final ColumnIndexSupplier indexSupplier = selector.getIndexSupplier(column); + if (indexSupplier == null) { + return Filters.makeNullIndex(false, selector); + } + + final StringValueSetIndex valueSetIndex = indexSupplier.as(StringValueSetIndex.class); + if (valueSetIndex == null) { + // column exists, but has no index + return null; + } + return valueSetIndex.forValue(String.valueOf(matchValue)); + } + + @Override + public ValueMatcher makeMatcher(ColumnSelectorFactory factory) + { + return ColumnProcessors.makeProcessor( + column, + new TypedConstantValueMatcherFactory(matchValue, matchValueType), + factory + ); + } + + @Override + public VectorValueMatcher makeVectorMatcher(VectorColumnSelectorFactory factory) + { + final ColumnCapabilities capabilities = factory.getColumnCapabilities(column); + + if (matchValueType.isPrimitive() && (capabilities == null || capabilities.isPrimitive())) { + return ColumnProcessors.makeVectorProcessor( + column, + VectorValueMatcherColumnProcessorFactory.instance(), + factory + ).makeMatcher(matchValue, matchValueType); + } + return ColumnProcessors.makeVectorProcessor( + column, + VectorValueMatcherColumnProcessorFactory.instance(), + factory + ).makeMatcher(new EqualityPredicateFactory(matchValue, matchValueType)); + } + + @Override + public boolean supportsSelectivityEstimation(ColumnSelector columnSelector, ColumnIndexSelector indexSelector) + { + return Filters.supportsSelectivityEstimation(this, column, columnSelector, indexSelector); + } + + @Override + public boolean canVectorizeMatcher(ColumnInspector inspector) + { + return true; + } + + @Override + public Set<String> getRequiredColumns() + { + return ImmutableSet.of(column); + } + + @Override + public boolean supportsRequiredColumnRewrite() + { + return true; + } + + @Override + public Filter rewriteRequiredColumns(Map<String, String> columnRewrites) + { + String rewriteDimensionTo = columnRewrites.get(column); + + if (rewriteDimensionTo == null) { + throw new IAE( + "Received a non-applicable rewrite: %s, filter's dimension: %s", + columnRewrites, + columnRewrites + ); + } + + return new EqualityFilter( + rewriteDimensionTo, + matchValueType, + matchValue, + extractionFn, + filterTuning + ); + } + + private static class EqualityPredicateFactory implements DruidPredicateFactory + { + private final ExprEval<?> matchValue; + private final ColumnType matchValueType; + + private final Object initLock = new Object(); + + private volatile DruidLongPredicate longPredicate; + private volatile DruidFloatPredicate floatPredicate; + private volatile DruidDoublePredicate doublePredicate; + + public EqualityPredicateFactory(Object matchValue, ColumnType matchValueType) + { + this.matchValue = ExprEval.ofType(ExpressionType.fromColumnType(matchValueType), matchValue); + this.matchValueType = matchValueType; Review Comment: >I'm a little concerned that this code is trying to force materialize something that it doesn't need to force materialize. I'm a bit confused as to how this would work with something like a sketch or other complex object where we are passing in an object that the column would know how to deal with, but the expression evaluation system doesn't. I'm scared that we will have to teach expressions about how to deal with all of the types when we've already taught the column how to deal with them and all we really want is the Object to be passed through un-changed such that the column can do the right thing. I think your concern might be with mixing up `ExprEval.ofType` with `ExprEval.bestEffortOf`, the latter of which blindly tries to find the best type and is used by the 'auto' indexers. `ExprEval.ofType` what is used for expression bindings backed by columns at query time, and is a fairly light wrapper. When used with complex types, it has some special handling when the value is `String` (which is assumed to be base64 and decoded into `byte[]`) or `byte[]` which will be fed to the complex serde to turn into objects, but otherwise is basically a wrapper that holds type information but otherwise does nothing to the thing it is holding (this is how expressions that operate on complex columns are able to do their thing as well). This is also a large part of why `matchValueType` is specified here, for future expandability. > So, all of that said, to say, if I'm a column implementation of a relatively complex object (let's say HllSketch) and I want to support this Equality operator (I want someone to be able to pass in the base64 encoded string of the HllSketch and I want to find the rows that match it), how can I do that? Or do I need to create my own "HllSketchFilter" and use that instead? Right now complex types do not define an equality method, only a sorting comparator, but I imagine a future where we add this to the type serde (or something), which would allow equality comparison for arbitrary complex types. Since complex types right now end up using the object processor/predicate, equality is only currently supported for things which can work with `Objects.equals`, however, if we add this mechanism I think it would be pretty easy to allow all complex types to opt-in to supporting this, and replace the current special handling i have to support nested column equality https://github.com/apache/druid/pull/14542/files#diff-b5d0b80ff07d3a5ceaa2a651d619216fcd09d77805f9412d09935a912db774f4R412 -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
