package org.apache.lucene.queries.function;
import java.io.IOException;
import java.util.Objects;
import java.util.function.DoublePredicate;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.search.ConstantScoreScorer;
import org.apache.lucene.search.ConstantScoreWeight;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.search.DoubleValues;
import org.apache.lucene.search.DoubleValuesSource;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.QueryVisitor;
import org.apache.lucene.search.ScoreMode;
import org.apache.lucene.search.Scorer;
import org.apache.lucene.search.TwoPhaseIterator;
import org.apache.lucene.search.Weight;
public final class FunctionMatchQuery extends Query {
private final DoubleValuesSource source;
private final DoublePredicate filter;
public FunctionMatchQuery(DoubleValuesSource source, DoublePredicate filter) {
this.source = source;
this.filter = filter;
}
@Override
public String toString(String field) {
return "FunctionMatchQuery(" + source.toString() + ")";
}
@Override
public void visit(QueryVisitor visitor) {
visitor.visitLeaf(this);
}
@Override
public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException {
DoubleValuesSource vs = source.rewrite(searcher);
return new ConstantScoreWeight(this, boost) {
@Override
public Scorer scorer(LeafReaderContext context) throws IOException {
DoubleValues values = vs.getValues(context, null);
DocIdSetIterator approximation = DocIdSetIterator.all(context.reader().maxDoc());
TwoPhaseIterator twoPhase = new TwoPhaseIterator(approximation) {
@Override
public boolean matches() throws IOException {
return values.advanceExact(approximation.docID()) && filter.test(values.doubleValue());
}
@Override
public float matchCost() {
return 100;
}
};
return new ConstantScoreScorer(this, score(), scoreMode, twoPhase);
}
@Override
public boolean isCacheable(LeafReaderContext ctx) {
return source.isCacheable(ctx);
}
};
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FunctionMatchQuery that = (FunctionMatchQuery) o;
return Objects.equals(source, that.source) && Objects.equals(filter, that.filter);
}
@Override
public int hashCode() {
return Objects.hash(source, filter);
}
}