Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
import org.apache.pinot.spi.utils.CommonConstants.Broker.Request.QueryOptionKey;
import org.apache.pinot.spi.utils.CommonConstants.MultiStageQueryRunner.JoinOverFlowMode;
import org.apache.pinot.spi.utils.CommonConstants.MultiStageQueryRunner.WindowOverFlowMode;
import org.apache.pinot.spi.utils.CommonConstants.Server.AndRestrictionPushdownMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand Down Expand Up @@ -342,6 +343,26 @@ public static boolean isAndScanReorderingEnabled(Map<String, String> queryOption
return Boolean.parseBoolean(queryOptions.get(QueryOptionKey.AND_SCAN_REORDERING));
}

/// Per-query override of [AndRestrictionPushdownMode], or `null` when the query does not set one, in which case
/// the server default applies.
@Nullable
public static AndRestrictionPushdownMode getAndRestrictionPushdownMode(Map<String, String> queryOptions) {
String mode = queryOptions.get(QueryOptionKey.AND_RESTRICTION_PUSHDOWN_MODE);
return mode != null ? parseAndRestrictionPushdownMode(QueryOptionKey.AND_RESTRICTION_PUSHDOWN_MODE, mode) : null;
}

/// Parses an [AndRestrictionPushdownMode], naming the offending key and the legal values on failure. The option
/// reads like a toggle, so `true`/`false` is a likely mistake and the message has to say so.
Comment thread
gortiz marked this conversation as resolved.
Resolved
public static AndRestrictionPushdownMode parseAndRestrictionPushdownMode(String key, String value) {
try {
return AndRestrictionPushdownMode.valueOf(value.toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(
String.format("Invalid value for %s: '%s'. Expected one of: %s (this option is a mode, not a boolean toggle)",
key, value, Arrays.toString(AndRestrictionPushdownMode.values())));
}
}

public static boolean isSkipUpsert(Map<String, String> queryOptions) {
return Boolean.parseBoolean(queryOptions.get(QueryOptionKey.SKIP_UPSERT));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,20 @@
package org.apache.pinot.core.common;

import org.apache.pinot.core.operator.dociditerators.AndDocIdIterator;
import org.apache.pinot.core.operator.dociditerators.BitmapBasedDocIdIterator;
import org.apache.pinot.core.operator.dociditerators.BitmapDocIdIterator;
import org.apache.pinot.core.operator.dociditerators.EmptyDocIdIterator;
import org.apache.pinot.core.operator.dociditerators.OrDocIdIterator;
import org.apache.pinot.core.operator.dociditerators.RangelessBitmapDocIdIterator;
import org.apache.pinot.core.operator.dociditerators.ScanBasedDocIdIterator;
import org.apache.pinot.core.operator.dociditerators.SortedDocIdIterator;
import org.apache.pinot.core.operator.docidsets.BitmapDocIdSet;
import org.apache.pinot.core.operator.docidsets.EmptyDocIdSet;
import org.apache.pinot.core.operator.docidsets.RangelessBitmapDocIdSet;
import org.apache.pinot.segment.spi.Constants;
import org.apache.pinot.spi.utils.Pairs.IntPair;
import org.roaringbitmap.RoaringBitmapWriter;
import org.roaringbitmap.buffer.ImmutableRoaringBitmap;
import org.roaringbitmap.buffer.MutableRoaringBitmap;


Expand All @@ -48,20 +52,97 @@ public interface BlockDocIdSet {
/// filtering phase. This method should be called after the filtering is done.
long getNumEntriesScannedInFilter();

/// Returns whether evaluating this DocIdSet costs time proportional to the number of documents it is asked about,
/// i.e. whether the subtree still has a scan- or expression-based predicate left to evaluate.
///
/// Only such a subtree gains anything from being handed a candidate set. An index-only subtree produces the same
/// bitmap either way, so restricting it just adds intersection work. Note this is a property of the *DocIdSet*, not
/// of the operator that built it: an operator that scans internally and hands back a bitmap -- a non-exact range
/// index, an H3 index -- has already paid for the scan by the time its DocIdSet exists, and correctly reports
/// `false`.
default boolean isScanBased() {
return false;
}

/// Returns whether a parent AND may defer calling [#iterator] on this DocIdSet and reach it through [#applyAnd]
/// instead.
///
/// True only for a composite DocIdSet (AND, OR, NOT) whose subtree is still scan-based. Forwarding a candidate set
/// to its children is how a restriction from an enclosing AND reaches a scan-based predicate nested inside an OR,
/// which would otherwise be evaluated against every document that branch matches. A leaf is never deferrable: its
/// index lookup has already happened, and a scan-based leaf is already reached through
/// [ScanBasedDocIdIterator#applyAnd] by the enclosing AND.
///
/// This says nothing about whether [#applyAnd] may be called -- every DocIdSet supports it.
default boolean isApplyAndDeferrable() {
return false;
}

/// Returns the document ids matching this DocIdSet that are also in `docIds`, i.e. the intersection of this
/// DocIdSet with the given candidate set.
///
/// `docIds` is never modified, so the same candidate set may be handed to several DocIdSets. The returned bitmap
/// must not be modified by the caller either: it may be a view of a bitmap the DocIdSet still owns.
///
/// Like [ScanBasedDocIdIterator#applyAnd], this method consumes the DocIdSet: call it at most once, and never
/// together with [#iterator]. [#getNumEntriesScannedInFilter] stays valid afterwards.
default ImmutableRoaringBitmap applyAnd(ImmutableRoaringBitmap docIds) {
if (docIds.isEmpty()) {
Comment thread
gortiz marked this conversation as resolved.
Resolved
// Nothing is evaluated, so the iterator will not close itself
release();
return new MutableRoaringBitmap();
}
BlockDocIdIterator docIdIterator = iterator();
if (docIdIterator instanceof ScanBasedDocIdIterator) {
// The scan only visits the candidate documents, which is the whole point of the push-down
return ((ScanBasedDocIdIterator) docIdIterator).applyAnd(docIds);
Comment thread
gortiz marked this conversation as resolved.
Resolved
}
if (docIdIterator instanceof BitmapBasedDocIdIterator) {
return ImmutableRoaringBitmap.and(((BitmapBasedDocIdIterator) docIdIterator).getDocIds(), docIds);
}
if (docIdIterator instanceof SortedDocIdIterator) {
MutableRoaringBitmap docIdsFromRanges = new MutableRoaringBitmap();
for (IntPair docIdRange : ((SortedDocIdIterator) docIdIterator).getDocIdRanges()) {
// NOTE: docIdRange has inclusive start and end.
docIdsFromRanges.add(docIdRange.getLeft(), docIdRange.getRight() + 1L);
}
docIdsFromRanges.and(docIds);
return docIdsFromRanges;
}
// Generic fallback: drive the iterator from the candidate set so that it is only asked about candidate documents
return collect(new AndDocIdIterator(
new BlockDocIdIterator[]{new RangelessBitmapDocIdIterator(docIds), docIdIterator}));
}

/// Releases a DocIdSet that will not be evaluated, e.g. an OR branch a short-circuit skipped past.
///
/// Scan-based DocIdSets build their iterator in the constructor, and that iterator holds a
/// `ForwardIndexReaderContext` -- a direct ByteBuffer for a chunk-compressed column. Evaluation normally releases it
/// because the iterator closes itself on reaching EOF, so a DocIdSet that is never evaluated has to be released
/// explicitly. Calling this instead of evaluating never reads any data.
default void release() {
iterator().close();
}

/// Materializes the document ids remaining in the given iterator.
static MutableRoaringBitmap collect(BlockDocIdIterator docIdIterator) {
Comment thread
gortiz marked this conversation as resolved.
Resolved
RoaringBitmapWriter<MutableRoaringBitmap> bitmapWriter =
RoaringBitmapWriter.bufferWriter().runCompress(false).get();
int docId;
while ((docId = docIdIterator.next()) != Constants.EOF) {
bitmapWriter.add(docId);
}
return bitmapWriter.get();
}

/// For scan-based FilterBlockDocIdSet, pre-scans the documents and returns a non-scan-based FilterBlockDocIdSet.
default BlockDocIdSet toNonScanDocIdSet() {
BlockDocIdIterator docIdIterator = iterator();
// NOTE: AND and OR DocIdIterator might contain scan-based DocIdIterator
// TODO: This scan is not counted in the execution stats
if (docIdIterator instanceof ScanBasedDocIdIterator || docIdIterator instanceof AndDocIdIterator
|| docIdIterator instanceof OrDocIdIterator) {
RoaringBitmapWriter<MutableRoaringBitmap> bitmapWriter =
RoaringBitmapWriter.bufferWriter().runCompress(false).get();
int docId;
while ((docId = docIdIterator.next()) != Constants.EOF) {
bitmapWriter.add(docId);
}
return RangelessBitmapDocIdSet.create(bitmapWriter.get());
return RangelessBitmapDocIdSet.create(collect(docIdIterator));
}

// NOTE: AND and OR DocIdSet might return BitmapBasedDocIdIterator after processing the iterators. Create a new
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,34 +81,39 @@ public int advance(int targetDocId) {

@Override
public MutableRoaringBitmap applyAnd(BatchIterator docIdIterator, OptionalInt firstDoc, OptionalInt lastDoc) {
if (!docIdIterator.hasNext()) {
return new MutableRoaringBitmap();
}
RoaringBitmapWriter<MutableRoaringBitmap> result;
if (firstDoc.isPresent() && lastDoc.isPresent()) {
result = RoaringBitmapWriter.bufferWriter()
.expectedRange(firstDoc.getAsInt(), lastDoc.getAsInt())
.runCompress(false)
.get();
} else {
result = RoaringBitmapWriter.bufferWriter()
.runCompress(false)
.get();
}
int[] buffer = new int[OPTIMAL_ITERATOR_BATCH_SIZE];
while (docIdIterator.hasNext()) {
int limit = docIdIterator.nextBatch(buffer);
for (int i = 0; i < limit; i++) {
int nextDocId = buffer[i];
// TODO: The performance can be improved by batching the docID lookups similar to how it's done in
// SVScanDocIdIterator
boolean doesValueMatch = _valueMatcher.doesValueMatch(nextDocId);
if (doesValueMatch) {
result.add(nextDocId);
// NOTE: Close the reader context once the candidates are consumed: unlike next(), this path never reaches EOF
try {
if (!docIdIterator.hasNext()) {
return new MutableRoaringBitmap();
}
RoaringBitmapWriter<MutableRoaringBitmap> result;
if (firstDoc.isPresent() && lastDoc.isPresent()) {
result = RoaringBitmapWriter.bufferWriter()
.expectedRange(firstDoc.getAsInt(), lastDoc.getAsInt())
.runCompress(false)
.get();
} else {
result = RoaringBitmapWriter.bufferWriter()
.runCompress(false)
.get();
}
int[] buffer = new int[OPTIMAL_ITERATOR_BATCH_SIZE];
while (docIdIterator.hasNext()) {
int limit = docIdIterator.nextBatch(buffer);
for (int i = 0; i < limit; i++) {
int nextDocId = buffer[i];
// TODO: The performance can be improved by batching the docID lookups similar to how it's done in
// SVScanDocIdIterator
boolean doesValueMatch = _valueMatcher.doesValueMatch(nextDocId);
if (doesValueMatch) {
result.add(nextDocId);
}
}
}
return result.get();
} finally {
close();
}
return result.get();
}

@Override
Expand Down
Loading
Loading