You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pinot.apache.org by GitBox <gi...@apache.org> on 2020/11/12 02:23:26 UTC
[GitHub] [incubator-pinot] jtao15 opened a new pull request #6259: Broker time range pruning(#6189)
jtao15 opened a new pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259
For issue #6189:
Add broker time range based pruner for routing.
To enable this pruner, table config need to be set as:
```
"routing": {
"segmentPrunerTypes": ["TimeRange"]
}
```
For multiple pruners, time pruner will by default be the first one.
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] jtao15 commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
jtao15 commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r533974285
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeSegmentPruner.java
##########
@@ -0,0 +1,344 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.interval.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.interval.IntervalTree;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeSegmentPruner.class);
+ private static final long MIN_START_TIME = 0;
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final Interval DEFAULT_INTERVAL = new Interval(MIN_START_TIME, MAX_END_TIME);
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore<ZNRecord> _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final DateTimeFormatSpec _timeFormatSpec;
+
+ private volatile IntervalTree _intervalTree;
+ private final Map<String, Interval> _intervalMap = new HashMap<>();
+
+ public TimeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ _timeFormatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ Preconditions.checkNotNull(_timeFormatSpec.getColumnUnit(),
+ "Time unit must be configured in the field spec for time column: %s of table: %s", _timeColumn,
+ _tableNameWithType);
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ // Bulk load time info for all online segments
+ int numSegments = onlineSegments.size();
+ List<String> segments = new ArrayList<>(numSegments);
+ List<String> segmentZKMetadataPaths = new ArrayList<>(numSegments);
+ for (String segment : segments) {
+ segments.add(segment);
+ segmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+ List<ZNRecord> znRecords = _propertyStore.get(segmentZKMetadataPaths, null, AccessOption.PERSISTENT, false);
+ for (int i = 0; i < numSegments; i++) {
+ String segment = segments.get(i);
+ Interval interval = extractIntervalFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ _intervalMap.put(segment, interval);
+ }
+ _intervalTree = new IntervalTree<>(_intervalMap);
+ }
+
+ private Interval extractIntervalFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ // Segments without metadata or with invalid time interval will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return DEFAULT_INTERVAL;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid time interval for segment: {}, table: {}", segment, _tableNameWithType);
+ return DEFAULT_INTERVAL;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ return new Interval(timeUnit.toMillis(startTime), timeUnit.toMillis(endTime));
+ }
+
+ @Override
+ public synchronized void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ // NOTE: We don't update all the segment ZK metadata for every external view change, but only the new added/removed
+ // ones. The refreshed segment ZK metadata change won't be picked up.
+ for (String segment : onlineSegments) {
+ _intervalMap.computeIfAbsent(segment, k -> extractIntervalFromSegmentZKMetaZNRecord(k,
+ _propertyStore.get(_segmentZKMetadataPathPrefix + k, null, AccessOption.PERSISTENT)));
+ }
+ _intervalMap.keySet().retainAll(onlineSegments);
+ _intervalTree = new IntervalTree<>(_intervalMap);
+ }
+
+
+ @Override
+ public synchronized void refreshSegment(String segment) {
+ Interval interval = extractIntervalFromSegmentZKMetaZNRecord(segment, _propertyStore.get(_segmentZKMetadataPathPrefix + segment, null, AccessOption.PERSISTENT));
+ _intervalMap.put(segment, interval);
+ _intervalTree = new IntervalTree<>(_intervalMap);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _intervalTree based on request time interval and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N: # of all online segments,
+ * M: # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ IntervalTree<String> intervalTree = _intervalTree;
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> intervals = getFilterTimeIntervals(filterQueryTree);
+ if (intervals == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (intervals.isEmpty()) { // invalid query time interval
+ return Collections.emptySet();
+ }
+
+ Set<String> selectedSegments = new HashSet<>();
+ for (Interval interval : intervals) {
+ for (String segment : intervalTree.searchAll(interval)) {
+ if (segments.contains(segment)) {
+ selectedSegments.add(segment);
+ }
+ }
+ }
+ return selectedSegments;
+ }
+
+ /**
+ * @return Null if no time condition or cannot filter base on the condition (e.g. 'SELECT * from myTable where time < 50 OR firstName = Jason')
+ * @return Empty list if time condition is specified but invalid (e.g. 'SELECT * from myTable where time < 50 AND time > 100')
+ */
+ @Nullable
+ private List<Interval> getFilterTimeIntervals(FilterQueryTree filterQueryTree) {
+ switch (filterQueryTree.getOperator()) {
+ case AND:
+ List<List<Interval>> andIntervals = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childIntervals = getFilterTimeIntervals(child);
+ if (childIntervals != null) {
+ andIntervals.add(childIntervals);
+ }
+ }
+ return getIntersectionSortedIntervals(andIntervals);
+ case OR:
+ List<List<Interval>> orIntervals = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childIntervals = getFilterTimeIntervals(child);
+ if (childIntervals == null) {
+ return null;
+ } else {
+ orIntervals.add(childIntervals);
+ }
+ }
+ return getUnionSortedIntervals(orIntervals);
+ case EQUALITY:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ long timeStamp = _timeFormatSpec.fromFormatToMillis(filterQueryTree.getValue().get(0));
+ return Collections.singletonList(new Interval(timeStamp, timeStamp));
+ }
+ return null;
+ case RANGE:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ return parseInterval(filterQueryTree.getValue());
+ }
+ return null;
+ default:
+ return null;
+ }
+ }
+
+ private List<Interval> getIntersectionSortedIntervals(List<List<Interval>> intervals) {
+ // Requires input intervals are sorted, the return intervals will be sorted
+ if (intervals.isEmpty()) {
Review comment:
Moved the condition to caller.
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] siddharthteotia commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
siddharthteotia commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r521873672
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeRangeSegmentPruner.java
##########
@@ -0,0 +1,348 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeRangeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeRangeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeRangeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+
+ public TimeRangeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ updateTimeRangeMSToSegmentSearchTree(onlineSegments);
+ }
+
+ private void updateTimeRangeMSToSegmentSearchTree(Set<String> onlineSegments) {
+ List<String> segments = new ArrayList<>(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ List<String> segmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: segments) {
+ segmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(segmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ List<Long> startTimes = new ArrayList<>();
+ List<Long> endTimes = new ArrayList<>();
+
+ for (int i = 0; i < segments.size(); i++) {
+ String segment = segments.get(i);
+
+ long[] range = extractStartEndTimeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ startTimes.add(range[0]);
+ endTimes.add(range[1]);
+ }
+
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(startTimes, endTimes, segments);
+ }
+
+
+ private long[] extractStartEndTimeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ long[] range = {MIN_START_TIME, MAX_END_TIME};
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ range[0] = timeUnit.toMillis(startTime);
+ range[1] = timeUnit.toMillis(endTime);
+ return range;
+ }
+
+ @Override
+ public void refreshSegment(String segment) {
+ Set<String> segments;
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ segments = new HashSet<>();
+ } else {
+ segments = _timeRangeMSToSegmentSearchTree.getAllValues();
+ }
+ if (!segment.contains(segment)) {
+ segments.add(segment);
+ }
+
+ updateTimeRangeMSToSegmentSearchTree(segments);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ return segments;
+ }
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> ranges = getFilterTimeRange(filterQueryTree);
+ if (ranges == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (ranges.size() == 0) { // invalid query time range
+ return Collections.emptySet();
+ }
+
+ Set<String> prunedSegments = new HashSet<>();
+ for (Interval range : ranges) {
+ Interval rangeMS = convertRangeToMS(range);
+ for (Object segment : _timeRangeMSToSegmentSearchTree.searchAll(rangeMS)) {
+ if (segments.contains(segment)) {
Review comment:
Is this the reason for List to Set change in API across all the users? Let's see if we can handle it internally within this class (will require a copy?)
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] snleee merged pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
snleee merged pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] jtao15 commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
jtao15 commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r527264180
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeSegmentPruner.java
##########
@@ -0,0 +1,340 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+ private final Map _segmentToTimeRangeMSCache;
+
+ public TimeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ _segmentToTimeRangeMSCache = new HashMap<String, Interval>();
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ synchronized public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ List<String> newSegments = new ArrayList<>();
+ for (String onlineSegment : onlineSegments) {
+ if (!_segmentToTimeRangeMSCache.containsKey(onlineSegment)) {
Review comment:
Will the refresh call `refreshSegment()` on pruners? If yes, the cache will be updated.
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] siddharthteotia commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
siddharthteotia commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r522586667
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeRangeSegmentPruner.java
##########
@@ -0,0 +1,348 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeRangeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeRangeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeRangeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+
+ public TimeRangeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ updateTimeRangeMSToSegmentSearchTree(onlineSegments);
+ }
+
+ private void updateTimeRangeMSToSegmentSearchTree(Set<String> onlineSegments) {
+ List<String> segments = new ArrayList<>(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ List<String> segmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: segments) {
+ segmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(segmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ List<Long> startTimes = new ArrayList<>();
+ List<Long> endTimes = new ArrayList<>();
+
+ for (int i = 0; i < segments.size(); i++) {
+ String segment = segments.get(i);
+
+ long[] range = extractStartEndTimeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ startTimes.add(range[0]);
+ endTimes.add(range[1]);
+ }
+
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(startTimes, endTimes, segments);
+ }
+
+
+ private long[] extractStartEndTimeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ long[] range = {MIN_START_TIME, MAX_END_TIME};
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ range[0] = timeUnit.toMillis(startTime);
+ range[1] = timeUnit.toMillis(endTime);
+ return range;
+ }
+
+ @Override
+ public void refreshSegment(String segment) {
+ Set<String> segments;
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ segments = new HashSet<>();
+ } else {
+ segments = _timeRangeMSToSegmentSearchTree.getAllValues();
+ }
+ if (!segment.contains(segment)) {
+ segments.add(segment);
+ }
+
+ updateTimeRangeMSToSegmentSearchTree(segments);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ return segments;
+ }
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> ranges = getFilterTimeRange(filterQueryTree);
+ if (ranges == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (ranges.size() == 0) { // invalid query time range
+ return Collections.emptySet();
+ }
+
+ Set<String> prunedSegments = new HashSet<>();
+ for (Interval range : ranges) {
+ Interval rangeMS = convertRangeToMS(range);
+ for (Object segment : _timeRangeMSToSegmentSearchTree.searchAll(rangeMS)) {
+ if (segments.contains(segment)) {
+ prunedSegments.add((String) segment);
+ }
+ }
+ }
+ return new HashSet<String>(prunedSegments);
+ }
+
+ private List<Interval> getFilterTimeRange(FilterQueryTree filterQueryTree) {
+ // return NUll if no time range info or cannot filter base on the info (e.g. 'SELECT * from myTable where time < 50 OR firstName = Jason')
+ // return an empty list if filtering range is specified but invalid (e.g. 'SELECT * from myTable where time < 50 AND time > 100')
+ switch (filterQueryTree.getOperator()) {
+ case AND:
+ List<List<Interval>> andRanges = new ArrayList<>();
Review comment:
Sorted merge is an O(N) operation. So the algorithm will first sort { [1, 4], [8, 10], [3, 5], [7, 9]} on startTime to
{ [1, 4], [3, 5], [7, 9], [8, 10]} and then do a single pass through them to merge into disjoint intervals resulting in {[3, 4], [8, 9]}.
I don't think keeping track of which range came from which child is worth the code complexity. Time complexity is still O(N). Also, the time filters are usually not that deeply rooted in a complex filter tree. While, there could be multiple occurrences of time filter in a query (haven't seen many example so far though), they are generally not going to be part of every subtree filter expression.
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] Jackie-Jiang commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
Jackie-Jiang commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r523263869
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/intervalST/IntervalST.java
##########
@@ -0,0 +1,187 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner.intervalST;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+
+// A read-only interval search tree based on AVL Tree
+public class IntervalST<Value> {
+
+ private Node<Value> root;
+
+ public IntervalST(List<Long> mins, List<Long> maxs, List<Value> values) {
+ // read only once constructed
+ for (int i = 0; i < mins.size(); i++) {
+ insert(mins.get(i), maxs.get(i), values.get(i));
+ }
+ }
+
+ private void insert(long min, long max, Value value) {
+ root = insert(root, new Interval(min, max), value);
+ }
+
+ private Node insert(Node node, Interval interval, Value value) {
+ if (node == null) {
+ return new Node(interval, value);
+ }
+
+ int cmp = interval.compareTo(node.interval);
+ if (cmp == 0) {
+ node.valueList.add(value);
+ return node;
+ } else if (cmp < 0) {
+ node.left = insert(node.left, interval, value);
+ } else {
+ node.right = insert(node.right, interval, value);
+ }
+
+ fixAuxiliaryInfo(node);
+ int balance = getBalance(node);
+ // Balance current subtree
+ if (balance < -1) {
+ if (getBalance(node.right) > 0) {
+ node.right = rotateRight(node.right); // Right-left case
+ }
+ node = rotateLeft(node);
+ } else if (balance > 1) {
+ if (getBalance(node.left) < 0) {
+ node.left = rotateLeft(node.left); // Left-right case
+ }
+ node = rotateRight(node);
+ }
+ return node;
+ }
+
+ // Get all intervals which intersect with input range [min, max]
+ public List<Value> searchAll(long min, long max) {
+ return searchAll(new Interval(min, max));
+ }
+
+ public List<Value> searchAll(Interval interval) {
+ List<Value> list = new ArrayList<Value>();
+ searchAll(root, interval, list);
+ return list;
+ }
+
+ private boolean searchAll(Node<Value> node, Interval interval, List<Value> list) {
+ boolean foundRoot = false;
+ boolean foundLeft = false;
+ boolean foundRight = false;
+ if (node == null)
+ return false;
+ if (interval.intersects(node.interval)) {
+ list.addAll(node.valueList);
+ foundRoot = true;
+ }
+ if (node.left != null && node.left.max >= interval.min) {
+ foundLeft = searchAll(node.left, interval, list);
+ }
+
+ if (foundLeft || node.left == null || node.left.max < interval.min) {
+ // If node.left.max > interval.min but cannot find intersections on left subtree,
+ // then there won't be any intersections in right subtree, since the right most interval x
+ // in left subtree must have x.min > interval.max. All intervals in right subtree
+ // will have mins >= x.min, so there won't be any intersections.
+ foundRight = searchAll(node.right, interval, list);
+ }
+ return foundRoot || foundLeft || foundRight;
+ }
+
+ public Set<Value> getAllValues() {
+ Set<Value> values = new HashSet<>();
+ getAllValues(root, values);
+ return values;
+ }
+
+ private void getAllValues(Node<Value> node, Set<Value> values) {
+ if (node == null) {
+ return;
+ }
+ getAllValues(node.left, values);
+ values.addAll(node.valueList);
+ getAllValues(node.right, values);
+ }
+
+ private Node rotateRight(Node x) {
+ Node y = x.left;
+ x.left = y.right;
+ y.right = x;
+ fixAuxiliaryInfo(x);
+ fixAuxiliaryInfo(y);
+ return y;
+ }
+
+ private Node rotateLeft(Node x) {
+ Node y = x.right;
+ x.right = y.left;
+ y.left = x;
+ fixAuxiliaryInfo(x);
+ fixAuxiliaryInfo(y);
+ return y;
+ }
+
+ private int getBalance(Node node) {
+ if (node == null) {
+ return 0;
+ }
+ return height(node.left) - height(node.right);
+ }
+
+ private int height(Node node) {
+ if (node == null) {
+ return 0;
+ }
+ return node.height;
+ }
+
+ private long max(Node node) {
+ if (node == null) {
+ return Long.MIN_VALUE;
+ }
+ return node.max;
+ }
+
+ // fix auxiliary information
+ private void fixAuxiliaryInfo(Node node) {
+ if (node == null) return;
+ node.height = 1 + Math.max(height(node.left), height(node.right));
+ node.max = Math.max(max(node.left), max(node.right));
+ node.max = Math.max(node.max, node.interval.max);
+ }
+
+ private static class Node<Value> {
+ final Interval interval; // key
Review comment:
Prefix them with `_`
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] codecov-io edited a comment on pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
codecov-io edited a comment on pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#issuecomment-728650157
# [Codecov](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=h1) Report
> Merging [#6259](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=desc) (ff8f2fd) into [master](https://codecov.io/gh/apache/incubator-pinot/commit/1beaab59b73f26c4e35f3b9bc856b03806cddf5a?el=desc) (1beaab5) will **decrease** coverage by `1.10%`.
> The diff coverage is `56.70%`.
[](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=tree)
```diff
@@ Coverage Diff @@
## master #6259 +/- ##
==========================================
- Coverage 66.44% 65.34% -1.11%
==========================================
Files 1075 1255 +180
Lines 54773 61536 +6763
Branches 8168 8927 +759
==========================================
+ Hits 36396 40212 +3816
- Misses 15700 18469 +2769
- Partials 2677 2855 +178
```
| Flag | Coverage Δ | |
|---|---|---|
| unittests | `65.34% <56.70%> (?)` | |
Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags#carryforward-flags-in-the-pull-request-comment) to find out more.
| [Impacted Files](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [...e/pinot/broker/api/resources/PinotBrokerDebug.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvYXBpL3Jlc291cmNlcy9QaW5vdEJyb2tlckRlYnVnLmphdmE=) | `0.00% <0.00%> (-79.32%)` | :arrow_down: |
| [...ot/broker/broker/AllowAllAccessControlFactory.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvYnJva2VyL0FsbG93QWxsQWNjZXNzQ29udHJvbEZhY3RvcnkuamF2YQ==) | `71.42% <ø> (-28.58%)` | :arrow_down: |
| [.../helix/BrokerUserDefinedMessageHandlerFactory.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvYnJva2VyL2hlbGl4L0Jyb2tlclVzZXJEZWZpbmVkTWVzc2FnZUhhbmRsZXJGYWN0b3J5LmphdmE=) | `33.96% <0.00%> (-32.71%)` | :arrow_down: |
| [...ker/routing/instanceselector/InstanceSelector.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvcm91dGluZy9pbnN0YW5jZXNlbGVjdG9yL0luc3RhbmNlU2VsZWN0b3IuamF2YQ==) | `100.00% <ø> (ø)` | |
| [...ava/org/apache/pinot/client/AbstractResultSet.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY2xpZW50cy9waW5vdC1qYXZhLWNsaWVudC9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3QvY2xpZW50L0Fic3RyYWN0UmVzdWx0U2V0LmphdmE=) | `66.66% <0.00%> (+9.52%)` | :arrow_up: |
| [.../main/java/org/apache/pinot/client/Connection.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY2xpZW50cy9waW5vdC1qYXZhLWNsaWVudC9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3QvY2xpZW50L0Nvbm5lY3Rpb24uamF2YQ==) | `35.55% <0.00%> (-13.29%)` | :arrow_down: |
| [...inot/client/JsonAsyncHttpPinotClientTransport.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY2xpZW50cy9waW5vdC1qYXZhLWNsaWVudC9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3QvY2xpZW50L0pzb25Bc3luY0h0dHBQaW5vdENsaWVudFRyYW5zcG9ydC5qYXZh) | `10.90% <0.00%> (-51.10%)` | :arrow_down: |
| [...not/common/assignment/InstancePartitionsUtils.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9jb21tb24vYXNzaWdubWVudC9JbnN0YW5jZVBhcnRpdGlvbnNVdGlscy5qYXZh) | `73.80% <ø> (+0.63%)` | :arrow_up: |
| [.../apache/pinot/common/exception/QueryException.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9jb21tb24vZXhjZXB0aW9uL1F1ZXJ5RXhjZXB0aW9uLmphdmE=) | `90.27% <ø> (+5.55%)` | :arrow_up: |
| [...pinot/common/function/AggregationFunctionType.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9jb21tb24vZnVuY3Rpb24vQWdncmVnYXRpb25GdW5jdGlvblR5cGUuamF2YQ==) | `98.27% <ø> (-1.73%)` | :arrow_down: |
| ... and [1101 more](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree-more) | |
------
[Continue to review full report at Codecov](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=footer). Last update [0565f86...ff8f2fd](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] npawar commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
npawar commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r559842920
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeSegmentPruner.java
##########
@@ -0,0 +1,346 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.interval.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.interval.IntervalTree;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeSegmentPruner.class);
+ private static final long MIN_START_TIME = 0;
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final Interval DEFAULT_INTERVAL = new Interval(MIN_START_TIME, MAX_END_TIME);
+ private static final char DELIMITER = '\0';
+ private static final String LEGACY_DELIMITER = "\t\t";
+ private static final char START_INCLUSIVE = '(';
+ private static final char END_INCLUSIVE = ')';
+ private static final String UNBOUNDED = "*";
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore<ZNRecord> _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final DateTimeFormatSpec _timeFormatSpec;
+
+ private volatile IntervalTree<String> _intervalTree;
+ private final Map<String, Interval> _intervalMap = new HashMap<>();
+
+ public TimeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkNotNull(schema, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ _timeFormatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ // Bulk load time info for all online segments
+ int numSegments = onlineSegments.size();
+ List<String> segments = new ArrayList<>(numSegments);
+ List<String> segmentZKMetadataPaths = new ArrayList<>(numSegments);
+ for (String segment : segments) {
Review comment:
`segments` is always going to be empty here. Shouldn't this be `onlineSegments` ?
The call on line 104 will always result in index out of bounds.
Am I missing something here? Shouldn't the tests have caught this?
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] jtao15 commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
jtao15 commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r522523961
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/SegmentPrunerFactory.java
##########
@@ -97,4 +105,44 @@ private static PartitionSegmentPruner getPartitionSegmentPruner(TableConfig tabl
return new PartitionSegmentPruner(tableNameWithType, partitionColumn, propertyStore);
}
}
+
+ @Nullable
+ private static TimeRangeSegmentPruner getTimeRangeSegmentPruner(TableConfig tableConfig,
+ ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ String tableNameWithType = tableConfig.getTableName();
+ SegmentsValidationAndRetentionConfig validationConfig = tableConfig.getValidationConfig();
+ if (validationConfig == null) {
+ LOGGER.warn("Cannot enable time range pruning without validation config for table: {}",
+ tableNameWithType);
+ return null;
+ }
+ String timeColumn = validationConfig.getTimeColumnName();
+ if (timeColumn == null) {
+ LOGGER.warn("Cannot enable time range pruning without time column for table: {}",
+ tableNameWithType);
+ return null;
+ }
+
+ LOGGER.info("Using TimeRangePruner on time column: {} for table: {}", timeColumn,
+ tableNameWithType);
+ return new TimeRangeSegmentPruner(tableConfig, propertyStore);
+ }
+
+ private static List<SegmentPruner> sortSegmentPruners(List<SegmentPruner> pruners) {
+ // If there's multiple pruners, move time range pruners to the front。
+ // Partition pruner run time is proportional to input # of segments while time range pruner is not,
+ // Prune based on time range first will have a smaller input size for partition pruners, so have better performance.
+ List<SegmentPruner> sortedPruners = new ArrayList<>();
+ for (SegmentPruner pruner : pruners) {
+ if (pruner instanceof TimeRangeSegmentPruner) {
+ sortedPruners.add(pruner);
+ }
+ }
+ for (SegmentPruner pruner: pruners) {
+ if (!(pruner instanceof TimeRangeSegmentPruner)) {
Review comment:
The first for loop will add `TimeRangeSegmentPruner` to the sorted result, this loop are adding non-timeRange pruners. To avoid duplicated pruners, I think this is still needed.
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] Jackie-Jiang commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
Jackie-Jiang commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r523304247
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/intervalST/IntervalST.java
##########
@@ -0,0 +1,187 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner.intervalST;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+
+// A read-only interval search tree based on AVL Tree
+public class IntervalST<Value> {
+
+ private Node<Value> root;
+
+ public IntervalST(List<Long> mins, List<Long> maxs, List<Value> values) {
+ // read only once constructed
+ for (int i = 0; i < mins.size(); i++) {
+ insert(mins.get(i), maxs.get(i), values.get(i));
+ }
+ }
+
+ private void insert(long min, long max, Value value) {
+ root = insert(root, new Interval(min, max), value);
+ }
+
+ private Node insert(Node node, Interval interval, Value value) {
+ if (node == null) {
+ return new Node(interval, value);
+ }
+
+ int cmp = interval.compareTo(node.interval);
+ if (cmp == 0) {
+ node.valueList.add(value);
+ return node;
+ } else if (cmp < 0) {
+ node.left = insert(node.left, interval, value);
+ } else {
+ node.right = insert(node.right, interval, value);
+ }
+
+ fixAuxiliaryInfo(node);
+ int balance = getBalance(node);
+ // Balance current subtree
+ if (balance < -1) {
+ if (getBalance(node.right) > 0) {
+ node.right = rotateRight(node.right); // Right-left case
+ }
+ node = rotateLeft(node);
+ } else if (balance > 1) {
+ if (getBalance(node.left) < 0) {
+ node.left = rotateLeft(node.left); // Left-right case
+ }
+ node = rotateRight(node);
+ }
+ return node;
+ }
+
+ // Get all intervals which intersect with input range [min, max]
+ public List<Value> searchAll(long min, long max) {
+ return searchAll(new Interval(min, max));
+ }
+
+ public List<Value> searchAll(Interval interval) {
+ List<Value> list = new ArrayList<Value>();
+ searchAll(root, interval, list);
+ return list;
+ }
+
+ private boolean searchAll(Node<Value> node, Interval interval, List<Value> list) {
+ boolean foundRoot = false;
+ boolean foundLeft = false;
+ boolean foundRight = false;
+ if (node == null)
+ return false;
+ if (interval.intersects(node.interval)) {
+ list.addAll(node.valueList);
+ foundRoot = true;
+ }
+ if (node.left != null && node.left.max >= interval.min) {
Review comment:
With some offline discussion, the algorithm used here is the `Augmented tree` solution under this wiki: https://en.wikipedia.org/wiki/Interval_tree, where the max is the max of all the nodes under the current node
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] jtao15 commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
jtao15 commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r522555738
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeRangeSegmentPruner.java
##########
@@ -0,0 +1,348 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeRangeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeRangeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeRangeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+
+ public TimeRangeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ updateTimeRangeMSToSegmentSearchTree(onlineSegments);
+ }
+
+ private void updateTimeRangeMSToSegmentSearchTree(Set<String> onlineSegments) {
+ List<String> segments = new ArrayList<>(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ List<String> segmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: segments) {
+ segmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(segmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ List<Long> startTimes = new ArrayList<>();
+ List<Long> endTimes = new ArrayList<>();
+
+ for (int i = 0; i < segments.size(); i++) {
+ String segment = segments.get(i);
+
+ long[] range = extractStartEndTimeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ startTimes.add(range[0]);
+ endTimes.add(range[1]);
+ }
+
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(startTimes, endTimes, segments);
+ }
+
+
+ private long[] extractStartEndTimeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ long[] range = {MIN_START_TIME, MAX_END_TIME};
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ range[0] = timeUnit.toMillis(startTime);
+ range[1] = timeUnit.toMillis(endTime);
+ return range;
+ }
+
+ @Override
+ public void refreshSegment(String segment) {
+ Set<String> segments;
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ segments = new HashSet<>();
+ } else {
+ segments = _timeRangeMSToSegmentSearchTree.getAllValues();
+ }
+ if (!segment.contains(segment)) {
+ segments.add(segment);
+ }
+
+ updateTimeRangeMSToSegmentSearchTree(segments);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ return segments;
+ }
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> ranges = getFilterTimeRange(filterQueryTree);
+ if (ranges == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (ranges.size() == 0) { // invalid query time range
+ return Collections.emptySet();
+ }
+
+ Set<String> prunedSegments = new HashSet<>();
Review comment:
I'll rename this.
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] siddharthteotia commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
siddharthteotia commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r521869463
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeRangeSegmentPruner.java
##########
@@ -0,0 +1,348 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeRangeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeRangeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeRangeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+
+ public TimeRangeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ updateTimeRangeMSToSegmentSearchTree(onlineSegments);
+ }
+
+ private void updateTimeRangeMSToSegmentSearchTree(Set<String> onlineSegments) {
+ List<String> segments = new ArrayList<>(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ List<String> segmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: segments) {
+ segmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(segmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ List<Long> startTimes = new ArrayList<>();
+ List<Long> endTimes = new ArrayList<>();
+
+ for (int i = 0; i < segments.size(); i++) {
+ String segment = segments.get(i);
+
+ long[] range = extractStartEndTimeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ startTimes.add(range[0]);
+ endTimes.add(range[1]);
+ }
+
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(startTimes, endTimes, segments);
+ }
+
+
+ private long[] extractStartEndTimeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ long[] range = {MIN_START_TIME, MAX_END_TIME};
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ range[0] = timeUnit.toMillis(startTime);
+ range[1] = timeUnit.toMillis(endTime);
+ return range;
+ }
+
+ @Override
+ public void refreshSegment(String segment) {
+ Set<String> segments;
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ segments = new HashSet<>();
+ } else {
+ segments = _timeRangeMSToSegmentSearchTree.getAllValues();
+ }
+ if (!segment.contains(segment)) {
+ segments.add(segment);
+ }
+
+ updateTimeRangeMSToSegmentSearchTree(segments);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ return segments;
+ }
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> ranges = getFilterTimeRange(filterQueryTree);
+ if (ranges == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (ranges.size() == 0) { // invalid query time range
+ return Collections.emptySet();
+ }
+
+ Set<String> prunedSegments = new HashSet<>();
+ for (Interval range : ranges) {
+ Interval rangeMS = convertRangeToMS(range);
+ for (Object segment : _timeRangeMSToSegmentSearchTree.searchAll(rangeMS)) {
+ if (segments.contains(segment)) {
+ prunedSegments.add((String) segment);
+ }
+ }
+ }
+ return new HashSet<String>(prunedSegments);
+ }
+
+ private List<Interval> getFilterTimeRange(FilterQueryTree filterQueryTree) {
+ // return NUll if no time range info or cannot filter base on the info (e.g. 'SELECT * from myTable where time < 50 OR firstName = Jason')
+ // return an empty list if filtering range is specified but invalid (e.g. 'SELECT * from myTable where time < 50 AND time > 100')
+ switch (filterQueryTree.getOperator()) {
+ case AND:
+ List<List<Interval>> andRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges != null) {
+ andRanges.add(childRanges);
+ }
+ }
+ return getIntersectionSortedRanges(andRanges);
+ case OR:
+ List<List<Interval>> orRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges == null) {
+ return null;
+ } else {
+ orRanges.add(childRanges);
+ }
+ }
+ return getUnionSortedRanges(orRanges);
+ case EQUALITY:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ long timeStamp = Long.parseLong(filterQueryTree.getValue().get(0));
+ return Collections.singletonList(new Interval(timeStamp, timeStamp));
+ }
+ return null;
+ case RANGE:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ return parseRange(filterQueryTree.getValue());
+ }
+ return null;
+ default:
+ return null;
+ }
+ }
+
+ private Interval convertRangeToMS(Interval range) {
+ long min = range.min == MIN_START_TIME ? MIN_START_TIME : _timeUnit.toMillis(range.min);
+ long max = range.max == MAX_END_TIME ? MAX_END_TIME : _timeUnit.toMillis(range.max);
+ return new Interval(min, max);
+ }
+
+ private List<Interval> getIntersectionSortedRanges(List<List<Interval>> ranges) {
+ // Requires input ranges are sorted, the return ranges will be sorted
+ return getIntersectionSortedRanges(ranges, 0, ranges.size());
+ }
+
+ private List<Interval> getIntersectionSortedRanges(List<List<Interval>> ranges, int start, int end) {
+ if (start == end) {
+ return null;
+ }
+
+ if (start + 1 == end) {
+ return ranges.get(start);
+ }
+
+ int mid = start + (end - start) / 2;
+ List<Interval> ranges1 = getIntersectionSortedRanges(ranges, start, mid);
+ List<Interval> ranges2 = getIntersectionSortedRanges(ranges, mid, end);
+ return getIntersectionOfTwoSortedRanges(ranges1, ranges2);
+ }
+
+ private List<Interval> getIntersectionOfTwoSortedRanges(List<Interval> ranges1, List<Interval> ranges2) { // sorted non-overlapping ranges
+ List<Interval> res = new ArrayList<>();
+ int i = 0, j = 0;
+ while (i < ranges1.size() && j < ranges2.size()) {
+ Interval range1 = ranges1.get(i);
+ Interval range2 = ranges2.get(j);
+ if (range1.intersects(range2)) {
+ res.add(Interval.getIntersection(range1, range2));
+ }
+ if (range1.max < range2.max) {
+ i++;
+ } else {
+ j++;
+ }
+ }
+ return res;
+ }
+
+ private List<Interval> getUnionSortedRanges(List<List<Interval>> ranges) {
+ return getUnionSortedRanges(ranges, 0, ranges.size());
+ }
+
+ private List<Interval> getUnionSortedRanges(List<List<Interval>> ranges, int start, int end) {
Review comment:
I think List of list is complicating the algorithm slightly. We can combine these two methods into one method that does sorted merge of two `List<Interval> range1, List<Interval> range2`
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] siddharthteotia commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
siddharthteotia commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r522586667
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeRangeSegmentPruner.java
##########
@@ -0,0 +1,348 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeRangeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeRangeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeRangeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+
+ public TimeRangeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ updateTimeRangeMSToSegmentSearchTree(onlineSegments);
+ }
+
+ private void updateTimeRangeMSToSegmentSearchTree(Set<String> onlineSegments) {
+ List<String> segments = new ArrayList<>(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ List<String> segmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: segments) {
+ segmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(segmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ List<Long> startTimes = new ArrayList<>();
+ List<Long> endTimes = new ArrayList<>();
+
+ for (int i = 0; i < segments.size(); i++) {
+ String segment = segments.get(i);
+
+ long[] range = extractStartEndTimeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ startTimes.add(range[0]);
+ endTimes.add(range[1]);
+ }
+
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(startTimes, endTimes, segments);
+ }
+
+
+ private long[] extractStartEndTimeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ long[] range = {MIN_START_TIME, MAX_END_TIME};
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ range[0] = timeUnit.toMillis(startTime);
+ range[1] = timeUnit.toMillis(endTime);
+ return range;
+ }
+
+ @Override
+ public void refreshSegment(String segment) {
+ Set<String> segments;
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ segments = new HashSet<>();
+ } else {
+ segments = _timeRangeMSToSegmentSearchTree.getAllValues();
+ }
+ if (!segment.contains(segment)) {
+ segments.add(segment);
+ }
+
+ updateTimeRangeMSToSegmentSearchTree(segments);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ return segments;
+ }
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> ranges = getFilterTimeRange(filterQueryTree);
+ if (ranges == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (ranges.size() == 0) { // invalid query time range
+ return Collections.emptySet();
+ }
+
+ Set<String> prunedSegments = new HashSet<>();
+ for (Interval range : ranges) {
+ Interval rangeMS = convertRangeToMS(range);
+ for (Object segment : _timeRangeMSToSegmentSearchTree.searchAll(rangeMS)) {
+ if (segments.contains(segment)) {
+ prunedSegments.add((String) segment);
+ }
+ }
+ }
+ return new HashSet<String>(prunedSegments);
+ }
+
+ private List<Interval> getFilterTimeRange(FilterQueryTree filterQueryTree) {
+ // return NUll if no time range info or cannot filter base on the info (e.g. 'SELECT * from myTable where time < 50 OR firstName = Jason')
+ // return an empty list if filtering range is specified but invalid (e.g. 'SELECT * from myTable where time < 50 AND time > 100')
+ switch (filterQueryTree.getOperator()) {
+ case AND:
+ List<List<Interval>> andRanges = new ArrayList<>();
Review comment:
Sorted merge is an O(N) operation. So the algorithm will first sort { [1, 4], [8, 10], [3, 5], [7, 9]} on startTime to
{ [1, 4], [3, 5], [7, 9], [8, 10]} and then do a single pass through them to merge into disjoint intervals resulting in {[3, 4], [8, 9]}.
I don't think keeping track of which range came from which child is worth the code complexity. Time complexity is still O(N). Also, the time filters are usually not that deeply rooted in a complex filter tree. While, there could be multiple occurrences of time filter in a query (haven't seen many example so far though), they may not be going to be part of every subtree filter expression.
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeRangeSegmentPruner.java
##########
@@ -0,0 +1,348 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeRangeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeRangeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeRangeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+
+ public TimeRangeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ updateTimeRangeMSToSegmentSearchTree(onlineSegments);
+ }
+
+ private void updateTimeRangeMSToSegmentSearchTree(Set<String> onlineSegments) {
+ List<String> segments = new ArrayList<>(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ List<String> segmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: segments) {
+ segmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(segmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ List<Long> startTimes = new ArrayList<>();
+ List<Long> endTimes = new ArrayList<>();
+
+ for (int i = 0; i < segments.size(); i++) {
+ String segment = segments.get(i);
+
+ long[] range = extractStartEndTimeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ startTimes.add(range[0]);
+ endTimes.add(range[1]);
+ }
+
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(startTimes, endTimes, segments);
+ }
+
+
+ private long[] extractStartEndTimeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ long[] range = {MIN_START_TIME, MAX_END_TIME};
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ range[0] = timeUnit.toMillis(startTime);
+ range[1] = timeUnit.toMillis(endTime);
+ return range;
+ }
+
+ @Override
+ public void refreshSegment(String segment) {
+ Set<String> segments;
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ segments = new HashSet<>();
+ } else {
+ segments = _timeRangeMSToSegmentSearchTree.getAllValues();
+ }
+ if (!segment.contains(segment)) {
+ segments.add(segment);
+ }
+
+ updateTimeRangeMSToSegmentSearchTree(segments);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ return segments;
+ }
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> ranges = getFilterTimeRange(filterQueryTree);
+ if (ranges == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (ranges.size() == 0) { // invalid query time range
+ return Collections.emptySet();
+ }
+
+ Set<String> prunedSegments = new HashSet<>();
+ for (Interval range : ranges) {
+ Interval rangeMS = convertRangeToMS(range);
+ for (Object segment : _timeRangeMSToSegmentSearchTree.searchAll(rangeMS)) {
+ if (segments.contains(segment)) {
+ prunedSegments.add((String) segment);
+ }
+ }
+ }
+ return new HashSet<String>(prunedSegments);
+ }
+
+ private List<Interval> getFilterTimeRange(FilterQueryTree filterQueryTree) {
+ // return NUll if no time range info or cannot filter base on the info (e.g. 'SELECT * from myTable where time < 50 OR firstName = Jason')
+ // return an empty list if filtering range is specified but invalid (e.g. 'SELECT * from myTable where time < 50 AND time > 100')
+ switch (filterQueryTree.getOperator()) {
+ case AND:
+ List<List<Interval>> andRanges = new ArrayList<>();
Review comment:
Sorted merge is an O(N) operation. So the algorithm will first sort { [1, 4], [8, 10], [3, 5], [7, 9]} on startTime to
{ [1, 4], [3, 5], [7, 9], [8, 10]} and then do a single pass through them to merge into disjoint intervals resulting in {[3, 4], [8, 9]}.
I don't think keeping track of which range came from which child is worth the code complexity. Time complexity is still O(N). Also, the time filters are usually not that deeply rooted in a complex filter tree. While, there could be multiple occurrences of time filter in a query (haven't seen many example so far though), they may not be part of every subtree filter expression.
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] jtao15 commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
jtao15 commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r533973584
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeSegmentPruner.java
##########
@@ -0,0 +1,344 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.interval.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.interval.IntervalTree;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeSegmentPruner.class);
+ private static final long MIN_START_TIME = 0;
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final Interval DEFAULT_INTERVAL = new Interval(MIN_START_TIME, MAX_END_TIME);
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore<ZNRecord> _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final DateTimeFormatSpec _timeFormatSpec;
+
+ private volatile IntervalTree _intervalTree;
+ private final Map<String, Interval> _intervalMap = new HashMap<>();
+
+ public TimeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ _timeFormatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ Preconditions.checkNotNull(_timeFormatSpec.getColumnUnit(),
+ "Time unit must be configured in the field spec for time column: %s of table: %s", _timeColumn,
+ _tableNameWithType);
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ // Bulk load time info for all online segments
+ int numSegments = onlineSegments.size();
+ List<String> segments = new ArrayList<>(numSegments);
+ List<String> segmentZKMetadataPaths = new ArrayList<>(numSegments);
+ for (String segment : segments) {
+ segments.add(segment);
+ segmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+ List<ZNRecord> znRecords = _propertyStore.get(segmentZKMetadataPaths, null, AccessOption.PERSISTENT, false);
+ for (int i = 0; i < numSegments; i++) {
+ String segment = segments.get(i);
+ Interval interval = extractIntervalFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ _intervalMap.put(segment, interval);
+ }
+ _intervalTree = new IntervalTree<>(_intervalMap);
+ }
+
+ private Interval extractIntervalFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ // Segments without metadata or with invalid time interval will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return DEFAULT_INTERVAL;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid time interval for segment: {}, table: {}", segment, _tableNameWithType);
+ return DEFAULT_INTERVAL;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ return new Interval(timeUnit.toMillis(startTime), timeUnit.toMillis(endTime));
+ }
+
+ @Override
+ public synchronized void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ // NOTE: We don't update all the segment ZK metadata for every external view change, but only the new added/removed
+ // ones. The refreshed segment ZK metadata change won't be picked up.
+ for (String segment : onlineSegments) {
+ _intervalMap.computeIfAbsent(segment, k -> extractIntervalFromSegmentZKMetaZNRecord(k,
+ _propertyStore.get(_segmentZKMetadataPathPrefix + k, null, AccessOption.PERSISTENT)));
+ }
+ _intervalMap.keySet().retainAll(onlineSegments);
+ _intervalTree = new IntervalTree<>(_intervalMap);
+ }
+
+
+ @Override
+ public synchronized void refreshSegment(String segment) {
+ Interval interval = extractIntervalFromSegmentZKMetaZNRecord(segment, _propertyStore.get(_segmentZKMetadataPathPrefix + segment, null, AccessOption.PERSISTENT));
+ _intervalMap.put(segment, interval);
+ _intervalTree = new IntervalTree<>(_intervalMap);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _intervalTree based on request time interval and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N: # of all online segments,
+ * M: # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ IntervalTree<String> intervalTree = _intervalTree;
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> intervals = getFilterTimeIntervals(filterQueryTree);
+ if (intervals == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (intervals.isEmpty()) { // invalid query time interval
+ return Collections.emptySet();
+ }
+
+ Set<String> selectedSegments = new HashSet<>();
+ for (Interval interval : intervals) {
+ for (String segment : intervalTree.searchAll(interval)) {
+ if (segments.contains(segment)) {
+ selectedSegments.add(segment);
+ }
+ }
+ }
+ return selectedSegments;
+ }
+
+ /**
+ * @return Null if no time condition or cannot filter base on the condition (e.g. 'SELECT * from myTable where time < 50 OR firstName = Jason')
+ * @return Empty list if time condition is specified but invalid (e.g. 'SELECT * from myTable where time < 50 AND time > 100')
+ */
+ @Nullable
+ private List<Interval> getFilterTimeIntervals(FilterQueryTree filterQueryTree) {
+ switch (filterQueryTree.getOperator()) {
+ case AND:
+ List<List<Interval>> andIntervals = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childIntervals = getFilterTimeIntervals(child);
+ if (childIntervals != null) {
+ andIntervals.add(childIntervals);
+ }
+ }
+ return getIntersectionSortedIntervals(andIntervals);
+ case OR:
+ List<List<Interval>> orIntervals = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childIntervals = getFilterTimeIntervals(child);
+ if (childIntervals == null) {
+ return null;
+ } else {
+ orIntervals.add(childIntervals);
+ }
+ }
+ return getUnionSortedIntervals(orIntervals);
+ case EQUALITY:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ long timeStamp = _timeFormatSpec.fromFormatToMillis(filterQueryTree.getValue().get(0));
+ return Collections.singletonList(new Interval(timeStamp, timeStamp));
+ }
+ return null;
+ case RANGE:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ return parseInterval(filterQueryTree.getValue());
+ }
+ return null;
+ default:
+ return null;
+ }
+ }
+
+ private List<Interval> getIntersectionSortedIntervals(List<List<Interval>> intervals) {
+ // Requires input intervals are sorted, the return intervals will be sorted
+ if (intervals.isEmpty()) {
+ return null;
+ }
+ return getIntersectionSortedIntervals(intervals, 0, intervals.size());
+ }
+
+ private List<Interval> getIntersectionSortedIntervals(List<List<Interval>> intervals, int start, int end) {
+ if (start + 1 == end) {
+ return intervals.get(start);
+ }
+
+ int mid = start + (end - start) / 2;
+ List<Interval> interval1 = getIntersectionSortedIntervals(intervals, start, mid);
+ List<Interval> interval2 = getIntersectionSortedIntervals(intervals, mid, end);
+ return getIntersectionTwoSortedIntervals(interval1, interval2);
+ }
+
+ /**
+ * Intersect two list of non-overlapping sorted intervals.
+ * E.g. {[1, 3], [4, 6], [7, 8], [10, 10]} and {[2, 5], [7, 9]} are merged as {[2, 3], [4, 5], [7, 8]}
+ */
+ private List<Interval> getIntersectionTwoSortedIntervals(List<Interval> intervals1, List<Interval> intervals2) {
+ List<Interval> res = new ArrayList<>();
+ int size1 = intervals1.size();
+ int size2 = intervals2.size();
+ int i = 0;
+ int j = 0;
+ while (i < size1 && j < size2) {
+ Interval interval1 = intervals1.get(i);
+ Interval interval2 = intervals2.get(j);
+ if (interval1.intersects(interval2)) {
+ res.add(Interval.getIntersection(interval1, interval2));
+ }
+ if (interval1._max <= interval2._max) {
+ i++;
+ } else {
+ j++;
+ }
+ }
+ return res;
+ }
+
+ private List<Interval> getUnionSortedIntervals(List<List<Interval>> intervals) {
+ // Requires input intervals are sorted, the return intervals will be sorted
+ if (intervals.isEmpty()) {
+ return null;
+ }
+ return getUnionSortedIntervals(intervals, 0, intervals.size());
+ }
+
+ private List<Interval> getUnionSortedIntervals(List<List<Interval>> intervals, int start, int end) {
+ if (start + 1 == end) {
+ return intervals.get(start);
+ }
+
+ int mid = start + (end - start) / 2;
+ List<Interval> intervals1 = getUnionSortedIntervals(intervals, start, mid);
+ List<Interval> intervals2 = getUnionSortedIntervals(intervals, mid, end);
+ return getUnionTwoSortedIntervals(intervals1, intervals2);
+ }
+
+ /**
+ * Union two list of non-overlapping sorted intervals.
+ * E.g. {[1, 2], [5, 7], [9, 10]} and {[2, 3], [4, 8]} are merged as {[1, 3], [4, 8], [9, 10]}
+ */
+ private List<Interval> getUnionTwoSortedIntervals(List<Interval> intervals1, List<Interval> intervals2) {
+ List<Interval> res = new ArrayList<>();
+ int size1 = intervals1.size();
+ int size2 = intervals2.size();
+ int i = 0;
+ int j = 0;
+ while (i < size1 || j < size2) {
+ // Get the `smaller` interval
+ Interval interval = null;
+ if (j == size2 || i < size1 && intervals1.get(i).compareTo(intervals2.get(j)) <= 0) {
+ interval = intervals1.get(i++);
+ } else {
+ interval = intervals2.get(j++);
+ }
+ // If not overlapping with current result, add as a new interval
+ int resSize = res.size();
+ if (res.isEmpty() || !interval.intersects(res.get(resSize - 1))) {
+ res.add(interval);
+ } else {
+ // If overlaps with the result, union with current result
+ res.set(resSize - 1, Interval.getUnion(interval, res.get(resSize - 1)));
+ }
+ }
+ return res;
+ }
+
+ /**
+ * Parse interval to millisecond as [min, max] with both sides included.
+ * E.g. '(* 16311]' is parsed as [0, 16311], '(1455 16311)' is parsed as [1456, 16310]
+ */
+ private List<Interval> parseInterval(List<String> intervalExpressions) {
+ Preconditions.checkState(intervalExpressions != null && intervalExpressions.size() == 1,
+ "Cannot parse range expressions from query: %s", intervalExpressions);
+ long startTime = MIN_START_TIME;
+ long endTime = MAX_END_TIME;
+ String intervalExpression = intervalExpressions.get(0);
+ String[] s = intervalExpression.substring(1, intervalExpression.length() - 1).split("\\s+");
Review comment:
Fixed. Thank you for helping to review and improve the code, appreciate it!
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] Jackie-Jiang commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
Jackie-Jiang commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r527264292
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeSegmentPruner.java
##########
@@ -0,0 +1,340 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+ private final Map _segmentToTimeRangeMSCache;
+
+ public TimeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ _segmentToTimeRangeMSCache = new HashMap<String, Interval>();
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ synchronized public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ List<String> newSegments = new ArrayList<>();
+ for (String onlineSegment : onlineSegments) {
+ if (!_segmentToTimeRangeMSCache.containsKey(onlineSegment)) {
Review comment:
@snleee This is handled with the API `refreshSegment()`
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] siddharthteotia commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
siddharthteotia commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r521868727
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeRangeSegmentPruner.java
##########
@@ -0,0 +1,348 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeRangeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeRangeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeRangeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+
+ public TimeRangeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ updateTimeRangeMSToSegmentSearchTree(onlineSegments);
+ }
+
+ private void updateTimeRangeMSToSegmentSearchTree(Set<String> onlineSegments) {
+ List<String> segments = new ArrayList<>(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ List<String> segmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: segments) {
+ segmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(segmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ List<Long> startTimes = new ArrayList<>();
+ List<Long> endTimes = new ArrayList<>();
+
+ for (int i = 0; i < segments.size(); i++) {
+ String segment = segments.get(i);
+
+ long[] range = extractStartEndTimeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ startTimes.add(range[0]);
+ endTimes.add(range[1]);
+ }
+
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(startTimes, endTimes, segments);
+ }
+
+
+ private long[] extractStartEndTimeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ long[] range = {MIN_START_TIME, MAX_END_TIME};
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ range[0] = timeUnit.toMillis(startTime);
+ range[1] = timeUnit.toMillis(endTime);
+ return range;
+ }
+
+ @Override
+ public void refreshSegment(String segment) {
+ Set<String> segments;
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ segments = new HashSet<>();
+ } else {
+ segments = _timeRangeMSToSegmentSearchTree.getAllValues();
+ }
+ if (!segment.contains(segment)) {
+ segments.add(segment);
+ }
+
+ updateTimeRangeMSToSegmentSearchTree(segments);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ return segments;
+ }
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> ranges = getFilterTimeRange(filterQueryTree);
+ if (ranges == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (ranges.size() == 0) { // invalid query time range
+ return Collections.emptySet();
+ }
+
+ Set<String> prunedSegments = new HashSet<>();
+ for (Interval range : ranges) {
+ Interval rangeMS = convertRangeToMS(range);
+ for (Object segment : _timeRangeMSToSegmentSearchTree.searchAll(rangeMS)) {
+ if (segments.contains(segment)) {
+ prunedSegments.add((String) segment);
+ }
+ }
+ }
+ return new HashSet<String>(prunedSegments);
+ }
+
+ private List<Interval> getFilterTimeRange(FilterQueryTree filterQueryTree) {
+ // return NUll if no time range info or cannot filter base on the info (e.g. 'SELECT * from myTable where time < 50 OR firstName = Jason')
+ // return an empty list if filtering range is specified but invalid (e.g. 'SELECT * from myTable where time < 50 AND time > 100')
+ switch (filterQueryTree.getOperator()) {
+ case AND:
+ List<List<Interval>> andRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges != null) {
+ andRanges.add(childRanges);
+ }
+ }
+ return getIntersectionSortedRanges(andRanges);
+ case OR:
+ List<List<Interval>> orRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges == null) {
+ return null;
+ } else {
+ orRanges.add(childRanges);
+ }
+ }
+ return getUnionSortedRanges(orRanges);
+ case EQUALITY:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ long timeStamp = Long.parseLong(filterQueryTree.getValue().get(0));
+ return Collections.singletonList(new Interval(timeStamp, timeStamp));
+ }
+ return null;
+ case RANGE:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ return parseRange(filterQueryTree.getValue());
+ }
+ return null;
+ default:
+ return null;
+ }
+ }
+
+ private Interval convertRangeToMS(Interval range) {
+ long min = range.min == MIN_START_TIME ? MIN_START_TIME : _timeUnit.toMillis(range.min);
+ long max = range.max == MAX_END_TIME ? MAX_END_TIME : _timeUnit.toMillis(range.max);
+ return new Interval(min, max);
+ }
+
+ private List<Interval> getIntersectionSortedRanges(List<List<Interval>> ranges) {
+ // Requires input ranges are sorted, the return ranges will be sorted
+ return getIntersectionSortedRanges(ranges, 0, ranges.size());
+ }
+
+ private List<Interval> getIntersectionSortedRanges(List<List<Interval>> ranges, int start, int end) {
Review comment:
I think this and the next method can be simplified into one method that works on `List<Interval> ranges` and not `List<List<Interval>> ranges`
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] codecov-io commented on pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
codecov-io commented on pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#issuecomment-728650157
# [Codecov](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=h1) Report
> Merging [#6259](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=desc) (f1adcfa) into [master](https://codecov.io/gh/apache/incubator-pinot/commit/1beaab59b73f26c4e35f3b9bc856b03806cddf5a?el=desc) (1beaab5) will **decrease** coverage by `20.19%`.
> The diff coverage is `38.97%`.
[](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=tree)
```diff
@@ Coverage Diff @@
## master #6259 +/- ##
===========================================
- Coverage 66.44% 46.24% -20.20%
===========================================
Files 1075 1246 +171
Lines 54773 59240 +4467
Branches 8168 8797 +629
===========================================
- Hits 36396 27398 -8998
- Misses 15700 29586 +13886
+ Partials 2677 2256 -421
```
| Flag | Coverage Δ | |
|---|---|---|
| integration | `46.24% <38.97%> (?)` | |
Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags#carryforward-flags-in-the-pull-request-comment) to find out more.
| [Impacted Files](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [...ot/broker/broker/AllowAllAccessControlFactory.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvYnJva2VyL0FsbG93QWxsQWNjZXNzQ29udHJvbEZhY3RvcnkuamF2YQ==) | `100.00% <ø> (ø)` | |
| [.../helix/BrokerUserDefinedMessageHandlerFactory.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvYnJva2VyL2hlbGl4L0Jyb2tlclVzZXJEZWZpbmVkTWVzc2FnZUhhbmRsZXJGYWN0b3J5LmphdmE=) | `52.83% <0.00%> (-13.84%)` | :arrow_down: |
| [...org/apache/pinot/broker/queryquota/HitCounter.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvcXVlcnlxdW90YS9IaXRDb3VudGVyLmphdmE=) | `0.00% <0.00%> (-100.00%)` | :arrow_down: |
| [...che/pinot/broker/queryquota/MaxHitRateTracker.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvcXVlcnlxdW90YS9NYXhIaXRSYXRlVHJhY2tlci5qYXZh) | `0.00% <0.00%> (ø)` | |
| [...ache/pinot/broker/queryquota/QueryQuotaEntity.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvcXVlcnlxdW90YS9RdWVyeVF1b3RhRW50aXR5LmphdmE=) | `0.00% <0.00%> (-50.00%)` | :arrow_down: |
| [...ker/routing/instanceselector/InstanceSelector.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvcm91dGluZy9pbnN0YW5jZXNlbGVjdG9yL0luc3RhbmNlU2VsZWN0b3IuamF2YQ==) | `100.00% <ø> (ø)` | |
| [...ceselector/StrictReplicaGroupInstanceSelector.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvcm91dGluZy9pbnN0YW5jZXNlbGVjdG9yL1N0cmljdFJlcGxpY2FHcm91cEluc3RhbmNlU2VsZWN0b3IuamF2YQ==) | `0.00% <0.00%> (ø)` | |
| [...roker/routing/segmentpruner/TimeSegmentPruner.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvcm91dGluZy9zZWdtZW50cHJ1bmVyL1RpbWVTZWdtZW50UHJ1bmVyLmphdmE=) | `0.00% <0.00%> (ø)` | |
| [...ker/routing/segmentpruner/intervalST/Interval.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvcm91dGluZy9zZWdtZW50cHJ1bmVyL2ludGVydmFsU1QvSW50ZXJ2YWwuamF2YQ==) | `0.00% <0.00%> (ø)` | |
| [...r/routing/segmentpruner/intervalST/IntervalST.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvcm91dGluZy9zZWdtZW50cHJ1bmVyL2ludGVydmFsU1QvSW50ZXJ2YWxTVC5qYXZh) | `0.00% <0.00%> (ø)` | |
| ... and [1238 more](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree-more) | |
------
[Continue to review full report at Codecov](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=footer). Last update [5a53fbe...f1adcfa](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] jtao15 commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
jtao15 commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r527264427
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/intervalST/Interval.java
##########
@@ -0,0 +1,90 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner.intervalST;
+
+import com.google.common.base.Preconditions;
+import javax.validation.constraints.NotNull;
+
+
+/**
+ * The {@code Interval} class represents an one-dimensional closed interval which contains both ends.
+ */
+public class Interval implements Comparable<Interval> {
+ public final long _min;
+ public final long _max;
+
+ public Interval(long min, long max) {
+ Preconditions.checkState(min <= max, "invalid interval [{}, {}]", min, max);
+ _min = min;
+ _max = max;
+ }
+
+ public boolean intersects(@NotNull Interval that) {
+ return _max >= that._min && that._max >= _min;
+ }
+
+ @Override
+ public int compareTo(Interval that) {
+ Preconditions.checkNotNull(that, "Compare to invalid interval: null");
+ if (_min < that._min) {
+ return -1;
+ } else if (_min > that._min) {
+ return 1;
+ } else if (_max < that._max) {
+ return -1;
+ } else if (_max > that._max) {
+ return 1;
+ }
+ else return 0;
+ }
+
+ @Override
+ public int hashCode() {
+ return (int)(_min * 17 + _max);
+ }
+
+ @Override
+ public boolean equals(Object that) {
Review comment:
No, I'll use the auto generated one instead.
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] codecov-io edited a comment on pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
codecov-io edited a comment on pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#issuecomment-728650157
# [Codecov](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=h1) Report
> Merging [#6259](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=desc) (9102f32) into [master](https://codecov.io/gh/apache/incubator-pinot/commit/1beaab59b73f26c4e35f3b9bc856b03806cddf5a?el=desc) (1beaab5) will **increase** coverage by `7.59%`.
> The diff coverage is `73.16%`.
[](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=tree)
```diff
@@ Coverage Diff @@
## master #6259 +/- ##
==========================================
+ Coverage 66.44% 74.04% +7.59%
==========================================
Files 1075 1294 +219
Lines 54773 62461 +7688
Branches 8168 9074 +906
==========================================
+ Hits 36396 46249 +9853
+ Misses 15700 13219 -2481
- Partials 2677 2993 +316
```
| Flag | Coverage Δ | |
|---|---|---|
| integration | `45.17% <38.69%> (?)` | |
| unittests | `65.46% <56.80%> (?)` | |
Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags#carryforward-flags-in-the-pull-request-comment) to find out more.
| [Impacted Files](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [...ot/broker/broker/AllowAllAccessControlFactory.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvYnJva2VyL0FsbG93QWxsQWNjZXNzQ29udHJvbEZhY3RvcnkuamF2YQ==) | `100.00% <ø> (ø)` | |
| [.../helix/BrokerUserDefinedMessageHandlerFactory.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvYnJva2VyL2hlbGl4L0Jyb2tlclVzZXJEZWZpbmVkTWVzc2FnZUhhbmRsZXJGYWN0b3J5LmphdmE=) | `52.83% <0.00%> (-13.84%)` | :arrow_down: |
| [...ker/routing/instanceselector/InstanceSelector.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvcm91dGluZy9pbnN0YW5jZXNlbGVjdG9yL0luc3RhbmNlU2VsZWN0b3IuamF2YQ==) | `100.00% <ø> (ø)` | |
| [.../main/java/org/apache/pinot/client/Connection.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY2xpZW50cy9waW5vdC1qYXZhLWNsaWVudC9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3QvY2xpZW50L0Nvbm5lY3Rpb24uamF2YQ==) | `44.44% <0.00%> (-4.40%)` | :arrow_down: |
| [...not/common/assignment/InstancePartitionsUtils.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9jb21tb24vYXNzaWdubWVudC9JbnN0YW5jZVBhcnRpdGlvbnNVdGlscy5qYXZh) | `78.57% <ø> (+5.40%)` | :arrow_up: |
| [...common/config/tuner/NoOpTableTableConfigTuner.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9jb21tb24vY29uZmlnL3R1bmVyL05vT3BUYWJsZVRhYmxlQ29uZmlnVHVuZXIuamF2YQ==) | `100.00% <ø> (ø)` | |
| [...ot/common/config/tuner/RealTimeAutoIndexTuner.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9jb21tb24vY29uZmlnL3R1bmVyL1JlYWxUaW1lQXV0b0luZGV4VHVuZXIuamF2YQ==) | `100.00% <ø> (ø)` | |
| [.../common/config/tuner/TableConfigTunerRegistry.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9jb21tb24vY29uZmlnL3R1bmVyL1RhYmxlQ29uZmlnVHVuZXJSZWdpc3RyeS5qYXZh) | `72.00% <ø> (ø)` | |
| [.../apache/pinot/common/exception/QueryException.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9jb21tb24vZXhjZXB0aW9uL1F1ZXJ5RXhjZXB0aW9uLmphdmE=) | `90.27% <ø> (+5.55%)` | :arrow_up: |
| [...pinot/common/function/AggregationFunctionType.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9jb21tb24vZnVuY3Rpb24vQWdncmVnYXRpb25GdW5jdGlvblR5cGUuamF2YQ==) | `100.00% <ø> (ø)` | |
| ... and [1083 more](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree-more) | |
------
[Continue to review full report at Codecov](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=footer). Last update [fb42e72...9102f32](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] jtao15 commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
jtao15 commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r523164177
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeRangeSegmentPruner.java
##########
@@ -0,0 +1,348 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeRangeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeRangeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeRangeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+
+ public TimeRangeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ updateTimeRangeMSToSegmentSearchTree(onlineSegments);
+ }
+
+ private void updateTimeRangeMSToSegmentSearchTree(Set<String> onlineSegments) {
+ List<String> segments = new ArrayList<>(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ List<String> segmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: segments) {
+ segmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(segmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ List<Long> startTimes = new ArrayList<>();
+ List<Long> endTimes = new ArrayList<>();
+
+ for (int i = 0; i < segments.size(); i++) {
+ String segment = segments.get(i);
+
+ long[] range = extractStartEndTimeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ startTimes.add(range[0]);
+ endTimes.add(range[1]);
+ }
+
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(startTimes, endTimes, segments);
+ }
+
+
+ private long[] extractStartEndTimeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ long[] range = {MIN_START_TIME, MAX_END_TIME};
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ range[0] = timeUnit.toMillis(startTime);
+ range[1] = timeUnit.toMillis(endTime);
+ return range;
+ }
+
+ @Override
+ public void refreshSegment(String segment) {
+ Set<String> segments;
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ segments = new HashSet<>();
+ } else {
+ segments = _timeRangeMSToSegmentSearchTree.getAllValues();
+ }
+ if (!segment.contains(segment)) {
+ segments.add(segment);
+ }
+
+ updateTimeRangeMSToSegmentSearchTree(segments);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ return segments;
+ }
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> ranges = getFilterTimeRange(filterQueryTree);
+ if (ranges == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (ranges.size() == 0) { // invalid query time range
+ return Collections.emptySet();
+ }
+
+ Set<String> prunedSegments = new HashSet<>();
+ for (Interval range : ranges) {
+ Interval rangeMS = convertRangeToMS(range);
+ for (Object segment : _timeRangeMSToSegmentSearchTree.searchAll(rangeMS)) {
+ if (segments.contains(segment)) {
+ prunedSegments.add((String) segment);
+ }
+ }
+ }
+ return new HashSet<String>(prunedSegments);
+ }
+
+ private List<Interval> getFilterTimeRange(FilterQueryTree filterQueryTree) {
+ // return NUll if no time range info or cannot filter base on the info (e.g. 'SELECT * from myTable where time < 50 OR firstName = Jason')
+ // return an empty list if filtering range is specified but invalid (e.g. 'SELECT * from myTable where time < 50 AND time > 100')
+ switch (filterQueryTree.getOperator()) {
+ case AND:
+ List<List<Interval>> andRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges != null) {
+ andRanges.add(childRanges);
+ }
+ }
+ return getIntersectionSortedRanges(andRanges);
+ case OR:
+ List<List<Interval>> orRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges == null) {
+ return null;
+ } else {
+ orRanges.add(childRanges);
+ }
+ }
+ return getUnionSortedRanges(orRanges);
+ case EQUALITY:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ long timeStamp = Long.parseLong(filterQueryTree.getValue().get(0));
+ return Collections.singletonList(new Interval(timeStamp, timeStamp));
+ }
+ return null;
+ case RANGE:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ return parseRange(filterQueryTree.getValue());
+ }
+ return null;
+ default:
+ return null;
+ }
+ }
+
+ private Interval convertRangeToMS(Interval range) {
+ long min = range.min == MIN_START_TIME ? MIN_START_TIME : _timeUnit.toMillis(range.min);
+ long max = range.max == MAX_END_TIME ? MAX_END_TIME : _timeUnit.toMillis(range.max);
+ return new Interval(min, max);
+ }
+
+ private List<Interval> getIntersectionSortedRanges(List<List<Interval>> ranges) {
Review comment:
I was basically doing a merge sort, the input for `getIntersectionOfTwoSortedRanges()`(where merge happens) will be two sorted lists(both contains one single element) the merging process guarantees that the output will be sorted. And so will the returned list for `getIntersectionSortedRanges` be sorted.
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeRangeSegmentPruner.java
##########
@@ -0,0 +1,348 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeRangeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeRangeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeRangeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+
+ public TimeRangeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ updateTimeRangeMSToSegmentSearchTree(onlineSegments);
+ }
+
+ private void updateTimeRangeMSToSegmentSearchTree(Set<String> onlineSegments) {
+ List<String> segments = new ArrayList<>(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ List<String> segmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: segments) {
+ segmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(segmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ List<Long> startTimes = new ArrayList<>();
+ List<Long> endTimes = new ArrayList<>();
+
+ for (int i = 0; i < segments.size(); i++) {
+ String segment = segments.get(i);
+
+ long[] range = extractStartEndTimeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ startTimes.add(range[0]);
+ endTimes.add(range[1]);
+ }
+
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(startTimes, endTimes, segments);
+ }
+
+
+ private long[] extractStartEndTimeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ long[] range = {MIN_START_TIME, MAX_END_TIME};
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ range[0] = timeUnit.toMillis(startTime);
+ range[1] = timeUnit.toMillis(endTime);
+ return range;
+ }
+
+ @Override
+ public void refreshSegment(String segment) {
+ Set<String> segments;
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ segments = new HashSet<>();
+ } else {
+ segments = _timeRangeMSToSegmentSearchTree.getAllValues();
+ }
+ if (!segment.contains(segment)) {
+ segments.add(segment);
+ }
+
+ updateTimeRangeMSToSegmentSearchTree(segments);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ return segments;
+ }
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> ranges = getFilterTimeRange(filterQueryTree);
+ if (ranges == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (ranges.size() == 0) { // invalid query time range
+ return Collections.emptySet();
+ }
+
+ Set<String> prunedSegments = new HashSet<>();
+ for (Interval range : ranges) {
+ Interval rangeMS = convertRangeToMS(range);
+ for (Object segment : _timeRangeMSToSegmentSearchTree.searchAll(rangeMS)) {
+ if (segments.contains(segment)) {
+ prunedSegments.add((String) segment);
+ }
+ }
+ }
+ return new HashSet<String>(prunedSegments);
+ }
+
+ private List<Interval> getFilterTimeRange(FilterQueryTree filterQueryTree) {
+ // return NUll if no time range info or cannot filter base on the info (e.g. 'SELECT * from myTable where time < 50 OR firstName = Jason')
+ // return an empty list if filtering range is specified but invalid (e.g. 'SELECT * from myTable where time < 50 AND time > 100')
+ switch (filterQueryTree.getOperator()) {
+ case AND:
+ List<List<Interval>> andRanges = new ArrayList<>();
Review comment:
I see your points now, yes, this can be simplified to list by sorting in the function. The time complexity may not be big a concern since the FilterQuery tree should not be too complex. I'll refactor this.
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] jtao15 commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
jtao15 commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r559849452
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeSegmentPruner.java
##########
@@ -0,0 +1,346 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.interval.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.interval.IntervalTree;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeSegmentPruner.class);
+ private static final long MIN_START_TIME = 0;
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final Interval DEFAULT_INTERVAL = new Interval(MIN_START_TIME, MAX_END_TIME);
+ private static final char DELIMITER = '\0';
+ private static final String LEGACY_DELIMITER = "\t\t";
+ private static final char START_INCLUSIVE = '(';
+ private static final char END_INCLUSIVE = ')';
+ private static final String UNBOUNDED = "*";
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore<ZNRecord> _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final DateTimeFormatSpec _timeFormatSpec;
+
+ private volatile IntervalTree<String> _intervalTree;
+ private final Map<String, Interval> _intervalMap = new HashMap<>();
+
+ public TimeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkNotNull(schema, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ _timeFormatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ // Bulk load time info for all online segments
+ int numSegments = onlineSegments.size();
+ List<String> segments = new ArrayList<>(numSegments);
+ List<String> segmentZKMetadataPaths = new ArrayList<>(numSegments);
+ for (String segment : segments) {
Review comment:
Yes, this should be `onlineSegments`. The tests only covered cases that `onlineSegments` are empty. Let me send a pr to fix this and cover cases when `onlineSegments` are not empty.
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] jtao15 commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
jtao15 commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r527282883
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/RoutingManager.java
##########
@@ -570,14 +570,14 @@ void refreshSegment(String segment) {
}
InstanceSelector.SelectionResult calculateRouting(BrokerRequest brokerRequest) {
- List<String> selectedSegments = _segmentSelector.select(brokerRequest);
+ Set<String> selectedSegments = _segmentSelector.select(brokerRequest);
if (!selectedSegments.isEmpty()) {
for (SegmentPruner segmentPruner : _segmentPruners) {
selectedSegments = segmentPruner.prune(brokerRequest, selectedSegments);
}
}
if (!selectedSegments.isEmpty()) {
- return _instanceSelector.select(brokerRequest, selectedSegments);
+ return _instanceSelector.select(brokerRequest, new ArrayList<>(selectedSegments));
Review comment:
Current `BalancedInstanceSelector` logic relies on the order of the selected segments, maybe we can change that logic and change this api to be `Set`.
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] jtao15 commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
jtao15 commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r522533895
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeRangeSegmentPruner.java
##########
@@ -0,0 +1,348 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeRangeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeRangeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeRangeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+
+ public TimeRangeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ updateTimeRangeMSToSegmentSearchTree(onlineSegments);
+ }
+
+ private void updateTimeRangeMSToSegmentSearchTree(Set<String> onlineSegments) {
+ List<String> segments = new ArrayList<>(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ List<String> segmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: segments) {
+ segmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(segmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ List<Long> startTimes = new ArrayList<>();
+ List<Long> endTimes = new ArrayList<>();
+
+ for (int i = 0; i < segments.size(); i++) {
+ String segment = segments.get(i);
+
+ long[] range = extractStartEndTimeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ startTimes.add(range[0]);
+ endTimes.add(range[1]);
+ }
+
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(startTimes, endTimes, segments);
+ }
+
+
+ private long[] extractStartEndTimeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ long[] range = {MIN_START_TIME, MAX_END_TIME};
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ range[0] = timeUnit.toMillis(startTime);
+ range[1] = timeUnit.toMillis(endTime);
+ return range;
+ }
+
+ @Override
+ public void refreshSegment(String segment) {
+ Set<String> segments;
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ segments = new HashSet<>();
+ } else {
+ segments = _timeRangeMSToSegmentSearchTree.getAllValues();
+ }
+ if (!segment.contains(segment)) {
+ segments.add(segment);
+ }
+
+ updateTimeRangeMSToSegmentSearchTree(segments);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ return segments;
+ }
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> ranges = getFilterTimeRange(filterQueryTree);
+ if (ranges == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (ranges.size() == 0) { // invalid query time range
+ return Collections.emptySet();
+ }
+
+ Set<String> prunedSegments = new HashSet<>();
+ for (Interval range : ranges) {
+ Interval rangeMS = convertRangeToMS(range);
+ for (Object segment : _timeRangeMSToSegmentSearchTree.searchAll(rangeMS)) {
+ if (segments.contains(segment)) {
+ prunedSegments.add((String) segment);
+ }
+ }
+ }
+ return new HashSet<String>(prunedSegments);
+ }
+
+ private List<Interval> getFilterTimeRange(FilterQueryTree filterQueryTree) {
+ // return NUll if no time range info or cannot filter base on the info (e.g. 'SELECT * from myTable where time < 50 OR firstName = Jason')
+ // return an empty list if filtering range is specified but invalid (e.g. 'SELECT * from myTable where time < 50 AND time > 100')
+ switch (filterQueryTree.getOperator()) {
+ case AND:
+ List<List<Interval>> andRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges != null) {
+ andRanges.add(childRanges);
+ }
+ }
+ return getIntersectionSortedRanges(andRanges);
+ case OR:
+ List<List<Interval>> orRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges == null) {
+ return null;
+ } else {
+ orRanges.add(childRanges);
+ }
+ }
+ return getUnionSortedRanges(orRanges);
+ case EQUALITY:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ long timeStamp = Long.parseLong(filterQueryTree.getValue().get(0));
+ return Collections.singletonList(new Interval(timeStamp, timeStamp));
+ }
+ return null;
+ case RANGE:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ return parseRange(filterQueryTree.getValue());
+ }
+ return null;
+ default:
+ return null;
+ }
+ }
+
+ private Interval convertRangeToMS(Interval range) {
+ long min = range.min == MIN_START_TIME ? MIN_START_TIME : _timeUnit.toMillis(range.min);
+ long max = range.max == MAX_END_TIME ? MAX_END_TIME : _timeUnit.toMillis(range.max);
+ return new Interval(min, max);
+ }
+
+ private List<Interval> getIntersectionSortedRanges(List<List<Interval>> ranges) {
Review comment:
Yes, I was assuming the input ranges are sorted. I think in this case the leaf of the queryFilterTree will always contains only one range, and getting the intersection/union ranges from leaves will return a sorted result. So the input for this function and `getUnionSortedRange()` should always be sorted.
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] siddharthteotia commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
siddharthteotia commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r521868636
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeRangeSegmentPruner.java
##########
@@ -0,0 +1,348 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeRangeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeRangeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeRangeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+
+ public TimeRangeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ updateTimeRangeMSToSegmentSearchTree(onlineSegments);
+ }
+
+ private void updateTimeRangeMSToSegmentSearchTree(Set<String> onlineSegments) {
+ List<String> segments = new ArrayList<>(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ List<String> segmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: segments) {
+ segmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(segmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ List<Long> startTimes = new ArrayList<>();
+ List<Long> endTimes = new ArrayList<>();
+
+ for (int i = 0; i < segments.size(); i++) {
+ String segment = segments.get(i);
+
+ long[] range = extractStartEndTimeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ startTimes.add(range[0]);
+ endTimes.add(range[1]);
+ }
+
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(startTimes, endTimes, segments);
+ }
+
+
+ private long[] extractStartEndTimeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ long[] range = {MIN_START_TIME, MAX_END_TIME};
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ range[0] = timeUnit.toMillis(startTime);
+ range[1] = timeUnit.toMillis(endTime);
+ return range;
+ }
+
+ @Override
+ public void refreshSegment(String segment) {
+ Set<String> segments;
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ segments = new HashSet<>();
+ } else {
+ segments = _timeRangeMSToSegmentSearchTree.getAllValues();
+ }
+ if (!segment.contains(segment)) {
+ segments.add(segment);
+ }
+
+ updateTimeRangeMSToSegmentSearchTree(segments);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ return segments;
+ }
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> ranges = getFilterTimeRange(filterQueryTree);
+ if (ranges == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (ranges.size() == 0) { // invalid query time range
+ return Collections.emptySet();
+ }
+
+ Set<String> prunedSegments = new HashSet<>();
+ for (Interval range : ranges) {
+ Interval rangeMS = convertRangeToMS(range);
+ for (Object segment : _timeRangeMSToSegmentSearchTree.searchAll(rangeMS)) {
+ if (segments.contains(segment)) {
+ prunedSegments.add((String) segment);
+ }
+ }
+ }
+ return new HashSet<String>(prunedSegments);
+ }
+
+ private List<Interval> getFilterTimeRange(FilterQueryTree filterQueryTree) {
+ // return NUll if no time range info or cannot filter base on the info (e.g. 'SELECT * from myTable where time < 50 OR firstName = Jason')
+ // return an empty list if filtering range is specified but invalid (e.g. 'SELECT * from myTable where time < 50 AND time > 100')
+ switch (filterQueryTree.getOperator()) {
+ case AND:
+ List<List<Interval>> andRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges != null) {
+ andRanges.add(childRanges);
+ }
+ }
+ return getIntersectionSortedRanges(andRanges);
+ case OR:
+ List<List<Interval>> orRanges = new ArrayList<>();
Review comment:
The list of list comment above for AND is applicable here as well
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] siddharthteotia commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
siddharthteotia commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r521868457
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/SegmentPrunerFactory.java
##########
@@ -97,4 +105,44 @@ private static PartitionSegmentPruner getPartitionSegmentPruner(TableConfig tabl
return new PartitionSegmentPruner(tableNameWithType, partitionColumn, propertyStore);
}
}
+
+ @Nullable
+ private static TimeRangeSegmentPruner getTimeRangeSegmentPruner(TableConfig tableConfig,
+ ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ String tableNameWithType = tableConfig.getTableName();
+ SegmentsValidationAndRetentionConfig validationConfig = tableConfig.getValidationConfig();
+ if (validationConfig == null) {
+ LOGGER.warn("Cannot enable time range pruning without validation config for table: {}",
+ tableNameWithType);
+ return null;
+ }
+ String timeColumn = validationConfig.getTimeColumnName();
+ if (timeColumn == null) {
+ LOGGER.warn("Cannot enable time range pruning without time column for table: {}",
+ tableNameWithType);
+ return null;
+ }
+
+ LOGGER.info("Using TimeRangePruner on time column: {} for table: {}", timeColumn,
+ tableNameWithType);
+ return new TimeRangeSegmentPruner(tableConfig, propertyStore);
+ }
+
+ private static List<SegmentPruner> sortSegmentPruners(List<SegmentPruner> pruners) {
+ // If there's multiple pruners, move time range pruners to the front。
+ // Partition pruner run time is proportional to input # of segments while time range pruner is not,
+ // Prune based on time range first will have a smaller input size for partition pruners, so have better performance.
+ List<SegmentPruner> sortedPruners = new ArrayList<>();
+ for (SegmentPruner pruner : pruners) {
+ if (pruner instanceof TimeRangeSegmentPruner) {
+ sortedPruners.add(pruner);
+ }
+ }
+ for (SegmentPruner pruner: pruners) {
+ if (!(pruner instanceof TimeRangeSegmentPruner)) {
Review comment:
This check is not needed again right?
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] siddharthteotia commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
siddharthteotia commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r521869463
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeRangeSegmentPruner.java
##########
@@ -0,0 +1,348 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeRangeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeRangeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeRangeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+
+ public TimeRangeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ updateTimeRangeMSToSegmentSearchTree(onlineSegments);
+ }
+
+ private void updateTimeRangeMSToSegmentSearchTree(Set<String> onlineSegments) {
+ List<String> segments = new ArrayList<>(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ List<String> segmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: segments) {
+ segmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(segmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ List<Long> startTimes = new ArrayList<>();
+ List<Long> endTimes = new ArrayList<>();
+
+ for (int i = 0; i < segments.size(); i++) {
+ String segment = segments.get(i);
+
+ long[] range = extractStartEndTimeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ startTimes.add(range[0]);
+ endTimes.add(range[1]);
+ }
+
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(startTimes, endTimes, segments);
+ }
+
+
+ private long[] extractStartEndTimeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ long[] range = {MIN_START_TIME, MAX_END_TIME};
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ range[0] = timeUnit.toMillis(startTime);
+ range[1] = timeUnit.toMillis(endTime);
+ return range;
+ }
+
+ @Override
+ public void refreshSegment(String segment) {
+ Set<String> segments;
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ segments = new HashSet<>();
+ } else {
+ segments = _timeRangeMSToSegmentSearchTree.getAllValues();
+ }
+ if (!segment.contains(segment)) {
+ segments.add(segment);
+ }
+
+ updateTimeRangeMSToSegmentSearchTree(segments);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ return segments;
+ }
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> ranges = getFilterTimeRange(filterQueryTree);
+ if (ranges == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (ranges.size() == 0) { // invalid query time range
+ return Collections.emptySet();
+ }
+
+ Set<String> prunedSegments = new HashSet<>();
+ for (Interval range : ranges) {
+ Interval rangeMS = convertRangeToMS(range);
+ for (Object segment : _timeRangeMSToSegmentSearchTree.searchAll(rangeMS)) {
+ if (segments.contains(segment)) {
+ prunedSegments.add((String) segment);
+ }
+ }
+ }
+ return new HashSet<String>(prunedSegments);
+ }
+
+ private List<Interval> getFilterTimeRange(FilterQueryTree filterQueryTree) {
+ // return NUll if no time range info or cannot filter base on the info (e.g. 'SELECT * from myTable where time < 50 OR firstName = Jason')
+ // return an empty list if filtering range is specified but invalid (e.g. 'SELECT * from myTable where time < 50 AND time > 100')
+ switch (filterQueryTree.getOperator()) {
+ case AND:
+ List<List<Interval>> andRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges != null) {
+ andRanges.add(childRanges);
+ }
+ }
+ return getIntersectionSortedRanges(andRanges);
+ case OR:
+ List<List<Interval>> orRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges == null) {
+ return null;
+ } else {
+ orRanges.add(childRanges);
+ }
+ }
+ return getUnionSortedRanges(orRanges);
+ case EQUALITY:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ long timeStamp = Long.parseLong(filterQueryTree.getValue().get(0));
+ return Collections.singletonList(new Interval(timeStamp, timeStamp));
+ }
+ return null;
+ case RANGE:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ return parseRange(filterQueryTree.getValue());
+ }
+ return null;
+ default:
+ return null;
+ }
+ }
+
+ private Interval convertRangeToMS(Interval range) {
+ long min = range.min == MIN_START_TIME ? MIN_START_TIME : _timeUnit.toMillis(range.min);
+ long max = range.max == MAX_END_TIME ? MAX_END_TIME : _timeUnit.toMillis(range.max);
+ return new Interval(min, max);
+ }
+
+ private List<Interval> getIntersectionSortedRanges(List<List<Interval>> ranges) {
+ // Requires input ranges are sorted, the return ranges will be sorted
+ return getIntersectionSortedRanges(ranges, 0, ranges.size());
+ }
+
+ private List<Interval> getIntersectionSortedRanges(List<List<Interval>> ranges, int start, int end) {
+ if (start == end) {
+ return null;
+ }
+
+ if (start + 1 == end) {
+ return ranges.get(start);
+ }
+
+ int mid = start + (end - start) / 2;
+ List<Interval> ranges1 = getIntersectionSortedRanges(ranges, start, mid);
+ List<Interval> ranges2 = getIntersectionSortedRanges(ranges, mid, end);
+ return getIntersectionOfTwoSortedRanges(ranges1, ranges2);
+ }
+
+ private List<Interval> getIntersectionOfTwoSortedRanges(List<Interval> ranges1, List<Interval> ranges2) { // sorted non-overlapping ranges
+ List<Interval> res = new ArrayList<>();
+ int i = 0, j = 0;
+ while (i < ranges1.size() && j < ranges2.size()) {
+ Interval range1 = ranges1.get(i);
+ Interval range2 = ranges2.get(j);
+ if (range1.intersects(range2)) {
+ res.add(Interval.getIntersection(range1, range2));
+ }
+ if (range1.max < range2.max) {
+ i++;
+ } else {
+ j++;
+ }
+ }
+ return res;
+ }
+
+ private List<Interval> getUnionSortedRanges(List<List<Interval>> ranges) {
+ return getUnionSortedRanges(ranges, 0, ranges.size());
+ }
+
+ private List<Interval> getUnionSortedRanges(List<List<Interval>> ranges, int start, int end) {
Review comment:
I think List<List> is complicating the algorithm slightly. We can combine these two methods into one method that does sorted merge of two List<Interval>
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/intervalST/Interval.java
##########
@@ -0,0 +1,98 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner.intervalST;
+
+import com.google.common.base.Preconditions;
+
+
+public class Interval implements Comparable<Interval> {
Review comment:
Please add brief javadoc on the usage/purpose of this class
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/intervalST/Interval.java
##########
@@ -0,0 +1,98 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner.intervalST;
+
+import com.google.common.base.Preconditions;
+
+
+public class Interval implements Comparable<Interval> {
+ // interval with both ends inclusive [min, max]
+ public final long min;
+ public final long max;
+
+ public Interval(long min, long max) {
+ Preconditions.checkState(min <= max, "invalid interval [{}, {}]", min, max);
+ this.min = min;
+ this.max = max;
+ }
+
+ public boolean intersects(Interval that) {
+ Preconditions.checkNotNull(that, "Invalid interval: null");
Review comment:
I think checkNotNull is not needed.
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/intervalST/Interval.java
##########
@@ -0,0 +1,98 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner.intervalST;
+
+import com.google.common.base.Preconditions;
+
+
+public class Interval implements Comparable<Interval> {
+ // interval with both ends inclusive [min, max]
+ public final long min;
+ public final long max;
+
+ public Interval(long min, long max) {
+ Preconditions.checkState(min <= max, "invalid interval [{}, {}]", min, max);
+ this.min = min;
+ this.max = max;
+ }
+
+ public boolean intersects(Interval that) {
+ Preconditions.checkNotNull(that, "Invalid interval: null");
+ if (that.max < this.min) {
+ return false;
+ }
+ if (this.max < that.min) {
+ return false;
+ }
Review comment:
Can be simplified to one if condition
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/intervalST/Interval.java
##########
@@ -0,0 +1,98 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner.intervalST;
+
+import com.google.common.base.Preconditions;
+
+
+public class Interval implements Comparable<Interval> {
+ // interval with both ends inclusive [min, max]
+ public final long min;
+ public final long max;
+
+ public Interval(long min, long max) {
+ Preconditions.checkState(min <= max, "invalid interval [{}, {}]", min, max);
+ this.min = min;
+ this.max = max;
+ }
+
+ public boolean intersects(Interval that) {
+ Preconditions.checkNotNull(that, "Invalid interval: null");
+ if (that.max < this.min) {
+ return false;
+ }
+ if (this.max < that.min) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public int compareTo(Interval that) {
+ Preconditions.checkNotNull(that, "Compare to invalid interval: null");
+ if (this.min < that.min) {
+ return -1;
+ } else if (this.min > that.min) {
+ return 1;
+ } else if (this.max < that.max) {
+ return -1;
+ } else if (this.max > that.max) {
+ return 1;
+ }
+ else return 0;
+ }
+
+ @Override
+ public int hashCode() {
+ return (int)(min * 17 + max);
+ }
+
+ @Override
+ public boolean equals(Object that) {
+ if (that instanceof Interval && that != null
+ && this.min == ((Interval)that).min && this.max == ((Interval)that).max) {
+ return true;
+ }
+ return false;
+ }
+
+ public static Interval getIntersection(Interval a, Interval b) {
+ Preconditions.checkNotNull(a, "Invalid interval: null");
Review comment:
I don't think checkNotNull is needed. May be consider using @NotNull annotation
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/intervalST/IntervalST.java
##########
@@ -0,0 +1,187 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner.intervalST;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+
+// A read-only interval search tree based on AVL Tree
+public class IntervalST<Value> {
Review comment:
Doesn't java util or guava/fastutil library provide an implementation of balanced BST that can be used for intervals? Might just save effort of writing all the rotations correctly
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] jtao15 commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
jtao15 commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r524547919
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/intervalST/IntervalST.java
##########
@@ -0,0 +1,187 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner.intervalST;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+
+// A read-only interval search tree based on AVL Tree
+public class IntervalST<Value> {
+
+ private Node<Value> root;
+
+ public IntervalST(List<Long> mins, List<Long> maxs, List<Value> values) {
Review comment:
Cool idea! I think we can have a list representation of the bst (like array representation of heap). The root will be indexed as 0, left child 1, right child 2 and so on. The root of each subtree will be the one has median interval for that subtree.
```
A typical balanced tree
[10, 20]
/ \
[8, 15] [12, 20]
/ /
[5, 10] [10, 30]
will be represented as { [10, 20], [8, 15], [12, 20], [5, 10], null, [10, 30] }
```
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] codecov-io edited a comment on pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
codecov-io edited a comment on pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#issuecomment-728650157
# [Codecov](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=h1) Report
> Merging [#6259](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=desc) (787ee45) into [master](https://codecov.io/gh/apache/incubator-pinot/commit/1beaab59b73f26c4e35f3b9bc856b03806cddf5a?el=desc) (1beaab5) will **increase** coverage by `7.63%`.
> The diff coverage is `73.16%`.
[](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=tree)
```diff
@@ Coverage Diff @@
## master #6259 +/- ##
==========================================
+ Coverage 66.44% 74.08% +7.63%
==========================================
Files 1075 1255 +180
Lines 54773 61506 +6733
Branches 8168 8920 +752
==========================================
+ Hits 36396 45569 +9173
+ Misses 15700 13008 -2692
- Partials 2677 2929 +252
```
| Flag | Coverage Δ | |
|---|---|---|
| integration | `45.63% <38.78%> (?)` | |
| unittests | `65.29% <56.70%> (?)` | |
Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags#carryforward-flags-in-the-pull-request-comment) to find out more.
| [Impacted Files](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [...ot/broker/broker/AllowAllAccessControlFactory.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvYnJva2VyL0FsbG93QWxsQWNjZXNzQ29udHJvbEZhY3RvcnkuamF2YQ==) | `100.00% <ø> (ø)` | |
| [.../helix/BrokerUserDefinedMessageHandlerFactory.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvYnJva2VyL2hlbGl4L0Jyb2tlclVzZXJEZWZpbmVkTWVzc2FnZUhhbmRsZXJGYWN0b3J5LmphdmE=) | `52.83% <0.00%> (-13.84%)` | :arrow_down: |
| [...ker/routing/instanceselector/InstanceSelector.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvcm91dGluZy9pbnN0YW5jZXNlbGVjdG9yL0luc3RhbmNlU2VsZWN0b3IuamF2YQ==) | `100.00% <ø> (ø)` | |
| [.../main/java/org/apache/pinot/client/Connection.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY2xpZW50cy9waW5vdC1qYXZhLWNsaWVudC9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3QvY2xpZW50L0Nvbm5lY3Rpb24uamF2YQ==) | `44.44% <0.00%> (-4.40%)` | :arrow_down: |
| [...not/common/assignment/InstancePartitionsUtils.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9jb21tb24vYXNzaWdubWVudC9JbnN0YW5jZVBhcnRpdGlvbnNVdGlscy5qYXZh) | `78.57% <ø> (+5.40%)` | :arrow_up: |
| [.../apache/pinot/common/exception/QueryException.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9jb21tb24vZXhjZXB0aW9uL1F1ZXJ5RXhjZXB0aW9uLmphdmE=) | `90.27% <ø> (+5.55%)` | :arrow_up: |
| [...pinot/common/function/AggregationFunctionType.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9jb21tb24vZnVuY3Rpb24vQWdncmVnYXRpb25GdW5jdGlvblR5cGUuamF2YQ==) | `98.27% <ø> (-1.73%)` | :arrow_down: |
| [.../pinot/common/function/DateTimePatternHandler.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9jb21tb24vZnVuY3Rpb24vRGF0ZVRpbWVQYXR0ZXJuSGFuZGxlci5qYXZh) | `83.33% <ø> (ø)` | |
| [...ot/common/function/FunctionDefinitionRegistry.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9jb21tb24vZnVuY3Rpb24vRnVuY3Rpb25EZWZpbml0aW9uUmVnaXN0cnkuamF2YQ==) | `88.88% <ø> (+44.44%)` | :arrow_up: |
| [...org/apache/pinot/common/function/FunctionInfo.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9jb21tb24vZnVuY3Rpb24vRnVuY3Rpb25JbmZvLmphdmE=) | `100.00% <ø> (ø)` | |
| ... and [1037 more](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree-more) | |
------
[Continue to review full report at Codecov](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=footer). Last update [318c107...787ee45](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] snleee commented on pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
snleee commented on pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#issuecomment-727085039
@jtao15 is it true that `we need to store the segment name multiple times in different segments.`? My understanding was just to store a bit more extra information for each node (e.g. max value, pointers).
@Jackie-Jiang If storing segment name multiple times is the concern, we can optimize by using a hash map and use unique id instead of the segment name. I actually was also thinking of starting with the naive approach; however, @kishoreg and @noahprince22 had some concerns on the O(n) performance of the naive approach.
@kishoreg How do you think on this?
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] Jackie-Jiang commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
Jackie-Jiang commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r523308009
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/intervalST/IntervalST.java
##########
@@ -0,0 +1,187 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner.intervalST;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+
+// A read-only interval search tree based on AVL Tree
+public class IntervalST<Value> {
+
+ private Node<Value> root;
+
+ public IntervalST(List<Long> mins, List<Long> maxs, List<Value> values) {
+ // read only once constructed
+ for (int i = 0; i < mins.size(); i++) {
+ insert(mins.get(i), maxs.get(i), values.get(i));
+ }
+ }
+
+ private void insert(long min, long max, Value value) {
+ root = insert(root, new Interval(min, max), value);
+ }
+
+ private Node insert(Node node, Interval interval, Value value) {
+ if (node == null) {
+ return new Node(interval, value);
+ }
+
+ int cmp = interval.compareTo(node.interval);
+ if (cmp == 0) {
+ node.valueList.add(value);
+ return node;
+ } else if (cmp < 0) {
+ node.left = insert(node.left, interval, value);
+ } else {
+ node.right = insert(node.right, interval, value);
+ }
+
+ fixAuxiliaryInfo(node);
+ int balance = getBalance(node);
+ // Balance current subtree
+ if (balance < -1) {
+ if (getBalance(node.right) > 0) {
+ node.right = rotateRight(node.right); // Right-left case
+ }
+ node = rotateLeft(node);
+ } else if (balance > 1) {
+ if (getBalance(node.left) < 0) {
+ node.left = rotateLeft(node.left); // Left-right case
+ }
+ node = rotateRight(node);
+ }
+ return node;
+ }
+
+ // Get all intervals which intersect with input range [min, max]
+ public List<Value> searchAll(long min, long max) {
+ return searchAll(new Interval(min, max));
+ }
+
+ public List<Value> searchAll(Interval interval) {
+ List<Value> list = new ArrayList<Value>();
+ searchAll(root, interval, list);
+ return list;
+ }
+
+ private boolean searchAll(Node<Value> node, Interval interval, List<Value> list) {
+ boolean foundRoot = false;
+ boolean foundLeft = false;
+ boolean foundRight = false;
+ if (node == null)
+ return false;
+ if (interval.intersects(node.interval)) {
+ list.addAll(node.valueList);
+ foundRoot = true;
+ }
+ if (node.left != null && node.left.max >= interval.min) {
+ foundLeft = searchAll(node.left, interval, list);
+ }
+
+ if (foundLeft || node.left == null || node.left.max < interval.min) {
+ // If node.left.max > interval.min but cannot find intersections on left subtree,
+ // then there won't be any intersections in right subtree, since the right most interval x
+ // in left subtree must have x.min > interval.max. All intervals in right subtree
+ // will have mins >= x.min, so there won't be any intersections.
+ foundRight = searchAll(node.right, interval, list);
+ }
+ return foundRoot || foundLeft || foundRight;
+ }
+
+ public Set<Value> getAllValues() {
+ Set<Value> values = new HashSet<>();
+ getAllValues(root, values);
+ return values;
+ }
+
+ private void getAllValues(Node<Value> node, Set<Value> values) {
+ if (node == null) {
+ return;
+ }
+ getAllValues(node.left, values);
+ values.addAll(node.valueList);
+ getAllValues(node.right, values);
+ }
+
+ private Node rotateRight(Node x) {
+ Node y = x.left;
+ x.left = y.right;
+ y.right = x;
+ fixAuxiliaryInfo(x);
+ fixAuxiliaryInfo(y);
+ return y;
+ }
+
+ private Node rotateLeft(Node x) {
+ Node y = x.right;
+ x.right = y.left;
+ y.left = x;
+ fixAuxiliaryInfo(x);
+ fixAuxiliaryInfo(y);
+ return y;
+ }
+
+ private int getBalance(Node node) {
+ if (node == null) {
+ return 0;
+ }
+ return height(node.left) - height(node.right);
+ }
+
+ private int height(Node node) {
+ if (node == null) {
+ return 0;
+ }
+ return node.height;
+ }
+
+ private long max(Node node) {
+ if (node == null) {
+ return Long.MIN_VALUE;
+ }
+ return node.max;
+ }
+
+ // fix auxiliary information
+ private void fixAuxiliaryInfo(Node node) {
+ if (node == null) return;
Review comment:
(nit) Braces over the if block
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] codecov-io edited a comment on pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
codecov-io edited a comment on pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#issuecomment-728650157
# [Codecov](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=h1) Report
> Merging [#6259](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=desc) (9102f32) into [master](https://codecov.io/gh/apache/incubator-pinot/commit/1beaab59b73f26c4e35f3b9bc856b03806cddf5a?el=desc) (1beaab5) will **decrease** coverage by `0.98%`.
> The diff coverage is `56.80%`.
[](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=tree)
```diff
@@ Coverage Diff @@
## master #6259 +/- ##
==========================================
- Coverage 66.44% 65.46% -0.99%
==========================================
Files 1075 1294 +219
Lines 54773 62461 +7688
Branches 8168 9074 +906
==========================================
+ Hits 36396 40888 +4492
- Misses 15700 18662 +2962
- Partials 2677 2911 +234
```
| Flag | Coverage Δ | |
|---|---|---|
| unittests | `65.46% <56.80%> (?)` | |
Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags#carryforward-flags-in-the-pull-request-comment) to find out more.
| [Impacted Files](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [...e/pinot/broker/api/resources/PinotBrokerDebug.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvYXBpL3Jlc291cmNlcy9QaW5vdEJyb2tlckRlYnVnLmphdmE=) | `0.00% <0.00%> (-79.32%)` | :arrow_down: |
| [...ot/broker/broker/AllowAllAccessControlFactory.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvYnJva2VyL0FsbG93QWxsQWNjZXNzQ29udHJvbEZhY3RvcnkuamF2YQ==) | `71.42% <ø> (-28.58%)` | :arrow_down: |
| [.../helix/BrokerUserDefinedMessageHandlerFactory.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvYnJva2VyL2hlbGl4L0Jyb2tlclVzZXJEZWZpbmVkTWVzc2FnZUhhbmRsZXJGYWN0b3J5LmphdmE=) | `33.96% <0.00%> (-32.71%)` | :arrow_down: |
| [...ker/routing/instanceselector/InstanceSelector.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvcm91dGluZy9pbnN0YW5jZXNlbGVjdG9yL0luc3RhbmNlU2VsZWN0b3IuamF2YQ==) | `100.00% <ø> (ø)` | |
| [...ava/org/apache/pinot/client/AbstractResultSet.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY2xpZW50cy9waW5vdC1qYXZhLWNsaWVudC9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3QvY2xpZW50L0Fic3RyYWN0UmVzdWx0U2V0LmphdmE=) | `66.66% <0.00%> (+9.52%)` | :arrow_up: |
| [.../main/java/org/apache/pinot/client/Connection.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY2xpZW50cy9waW5vdC1qYXZhLWNsaWVudC9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3QvY2xpZW50L0Nvbm5lY3Rpb24uamF2YQ==) | `35.55% <0.00%> (-13.29%)` | :arrow_down: |
| [...inot/client/JsonAsyncHttpPinotClientTransport.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY2xpZW50cy9waW5vdC1qYXZhLWNsaWVudC9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3QvY2xpZW50L0pzb25Bc3luY0h0dHBQaW5vdENsaWVudFRyYW5zcG9ydC5qYXZh) | `10.90% <0.00%> (-51.10%)` | :arrow_down: |
| [...not/common/assignment/InstancePartitionsUtils.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9jb21tb24vYXNzaWdubWVudC9JbnN0YW5jZVBhcnRpdGlvbnNVdGlscy5qYXZh) | `73.80% <ø> (+0.63%)` | :arrow_up: |
| [...common/config/tuner/NoOpTableTableConfigTuner.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9jb21tb24vY29uZmlnL3R1bmVyL05vT3BUYWJsZVRhYmxlQ29uZmlnVHVuZXIuamF2YQ==) | `100.00% <ø> (ø)` | |
| [...ot/common/config/tuner/RealTimeAutoIndexTuner.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9jb21tb24vY29uZmlnL3R1bmVyL1JlYWxUaW1lQXV0b0luZGV4VHVuZXIuamF2YQ==) | `100.00% <ø> (ø)` | |
| ... and [1143 more](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree-more) | |
------
[Continue to review full report at Codecov](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=footer). Last update [fb42e72...9102f32](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] codecov-io edited a comment on pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
codecov-io edited a comment on pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#issuecomment-728650157
# [Codecov](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=h1) Report
> Merging [#6259](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=desc) (f20e4ed) into [master](https://codecov.io/gh/apache/incubator-pinot/commit/1beaab59b73f26c4e35f3b9bc856b03806cddf5a?el=desc) (1beaab5) will **decrease** coverage by `1.09%`.
> The diff coverage is `56.74%`.
[](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=tree)
```diff
@@ Coverage Diff @@
## master #6259 +/- ##
==========================================
- Coverage 66.44% 65.35% -1.10%
==========================================
Files 1075 1255 +180
Lines 54773 61537 +6764
Branches 8168 8927 +759
==========================================
+ Hits 36396 40219 +3823
- Misses 15700 18464 +2764
- Partials 2677 2854 +177
```
| Flag | Coverage Δ | |
|---|---|---|
| unittests | `65.35% <56.74%> (?)` | |
Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags#carryforward-flags-in-the-pull-request-comment) to find out more.
| [Impacted Files](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [...e/pinot/broker/api/resources/PinotBrokerDebug.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvYXBpL3Jlc291cmNlcy9QaW5vdEJyb2tlckRlYnVnLmphdmE=) | `0.00% <0.00%> (-79.32%)` | :arrow_down: |
| [...ot/broker/broker/AllowAllAccessControlFactory.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvYnJva2VyL0FsbG93QWxsQWNjZXNzQ29udHJvbEZhY3RvcnkuamF2YQ==) | `71.42% <ø> (-28.58%)` | :arrow_down: |
| [.../helix/BrokerUserDefinedMessageHandlerFactory.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvYnJva2VyL2hlbGl4L0Jyb2tlclVzZXJEZWZpbmVkTWVzc2FnZUhhbmRsZXJGYWN0b3J5LmphdmE=) | `33.96% <0.00%> (-32.71%)` | :arrow_down: |
| [...ker/routing/instanceselector/InstanceSelector.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvcm91dGluZy9pbnN0YW5jZXNlbGVjdG9yL0luc3RhbmNlU2VsZWN0b3IuamF2YQ==) | `100.00% <ø> (ø)` | |
| [...ava/org/apache/pinot/client/AbstractResultSet.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY2xpZW50cy9waW5vdC1qYXZhLWNsaWVudC9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3QvY2xpZW50L0Fic3RyYWN0UmVzdWx0U2V0LmphdmE=) | `66.66% <0.00%> (+9.52%)` | :arrow_up: |
| [.../main/java/org/apache/pinot/client/Connection.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY2xpZW50cy9waW5vdC1qYXZhLWNsaWVudC9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3QvY2xpZW50L0Nvbm5lY3Rpb24uamF2YQ==) | `35.55% <0.00%> (-13.29%)` | :arrow_down: |
| [...inot/client/JsonAsyncHttpPinotClientTransport.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY2xpZW50cy9waW5vdC1qYXZhLWNsaWVudC9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3QvY2xpZW50L0pzb25Bc3luY0h0dHBQaW5vdENsaWVudFRyYW5zcG9ydC5qYXZh) | `10.90% <0.00%> (-51.10%)` | :arrow_down: |
| [...not/common/assignment/InstancePartitionsUtils.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9jb21tb24vYXNzaWdubWVudC9JbnN0YW5jZVBhcnRpdGlvbnNVdGlscy5qYXZh) | `73.80% <ø> (+0.63%)` | :arrow_up: |
| [.../apache/pinot/common/exception/QueryException.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9jb21tb24vZXhjZXB0aW9uL1F1ZXJ5RXhjZXB0aW9uLmphdmE=) | `90.27% <ø> (+5.55%)` | :arrow_up: |
| [...pinot/common/function/AggregationFunctionType.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9jb21tb24vZnVuY3Rpb24vQWdncmVnYXRpb25GdW5jdGlvblR5cGUuamF2YQ==) | `98.27% <ø> (-1.73%)` | :arrow_down: |
| ... and [1101 more](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree-more) | |
------
[Continue to review full report at Codecov](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=footer). Last update [0565f86...ff8f2fd](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] jtao15 commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
jtao15 commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r522555104
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeRangeSegmentPruner.java
##########
@@ -0,0 +1,348 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeRangeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeRangeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeRangeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+
+ public TimeRangeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ updateTimeRangeMSToSegmentSearchTree(onlineSegments);
+ }
+
+ private void updateTimeRangeMSToSegmentSearchTree(Set<String> onlineSegments) {
+ List<String> segments = new ArrayList<>(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ List<String> segmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: segments) {
+ segmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(segmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ List<Long> startTimes = new ArrayList<>();
+ List<Long> endTimes = new ArrayList<>();
+
+ for (int i = 0; i < segments.size(); i++) {
+ String segment = segments.get(i);
+
+ long[] range = extractStartEndTimeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ startTimes.add(range[0]);
+ endTimes.add(range[1]);
+ }
+
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(startTimes, endTimes, segments);
+ }
+
+
+ private long[] extractStartEndTimeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ long[] range = {MIN_START_TIME, MAX_END_TIME};
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ range[0] = timeUnit.toMillis(startTime);
+ range[1] = timeUnit.toMillis(endTime);
+ return range;
+ }
+
+ @Override
+ public void refreshSegment(String segment) {
+ Set<String> segments;
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ segments = new HashSet<>();
+ } else {
+ segments = _timeRangeMSToSegmentSearchTree.getAllValues();
+ }
+ if (!segment.contains(segment)) {
+ segments.add(segment);
+ }
+
+ updateTimeRangeMSToSegmentSearchTree(segments);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ return segments;
+ }
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> ranges = getFilterTimeRange(filterQueryTree);
+ if (ranges == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (ranges.size() == 0) { // invalid query time range
+ return Collections.emptySet();
+ }
+
+ Set<String> prunedSegments = new HashSet<>();
+ for (Interval range : ranges) {
+ Interval rangeMS = convertRangeToMS(range);
+ for (Object segment : _timeRangeMSToSegmentSearchTree.searchAll(rangeMS)) {
+ if (segments.contains(segment)) {
Review comment:
Yes
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] Jackie-Jiang commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
Jackie-Jiang commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r523334416
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeRangeSegmentPruner.java
##########
@@ -0,0 +1,348 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeRangeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeRangeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeRangeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+
+ public TimeRangeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ updateTimeRangeMSToSegmentSearchTree(onlineSegments);
+ }
+
+ private void updateTimeRangeMSToSegmentSearchTree(Set<String> onlineSegments) {
+ List<String> segments = new ArrayList<>(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ List<String> segmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: segments) {
+ segmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(segmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
Review comment:
We don't want to read the ZK metadata for all segments for each callback. This is slow and could cause very heavy load on ZK, especially when the number of segments are high. We should cache the intervals and only read the ZK metadata for new segments. `refreshSegment()` is used for refreshing the cached interval for existing segments.
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] siddharthteotia commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
siddharthteotia commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r521870044
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeRangeSegmentPruner.java
##########
@@ -0,0 +1,348 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeRangeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeRangeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeRangeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+
+ public TimeRangeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ updateTimeRangeMSToSegmentSearchTree(onlineSegments);
+ }
+
+ private void updateTimeRangeMSToSegmentSearchTree(Set<String> onlineSegments) {
+ List<String> segments = new ArrayList<>(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ List<String> segmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: segments) {
+ segmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(segmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ List<Long> startTimes = new ArrayList<>();
+ List<Long> endTimes = new ArrayList<>();
+
+ for (int i = 0; i < segments.size(); i++) {
+ String segment = segments.get(i);
+
+ long[] range = extractStartEndTimeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ startTimes.add(range[0]);
+ endTimes.add(range[1]);
+ }
+
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(startTimes, endTimes, segments);
+ }
+
+
+ private long[] extractStartEndTimeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ long[] range = {MIN_START_TIME, MAX_END_TIME};
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ range[0] = timeUnit.toMillis(startTime);
+ range[1] = timeUnit.toMillis(endTime);
+ return range;
+ }
+
+ @Override
+ public void refreshSegment(String segment) {
+ Set<String> segments;
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ segments = new HashSet<>();
+ } else {
+ segments = _timeRangeMSToSegmentSearchTree.getAllValues();
+ }
+ if (!segment.contains(segment)) {
+ segments.add(segment);
+ }
+
+ updateTimeRangeMSToSegmentSearchTree(segments);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
Review comment:
The number of time ranges should also be part of Big O time complexity right?
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] Jackie-Jiang commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
Jackie-Jiang commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r523274601
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/intervalST/IntervalST.java
##########
@@ -0,0 +1,187 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner.intervalST;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+
+// A read-only interval search tree based on AVL Tree
+public class IntervalST<Value> {
+
+ private Node<Value> root;
+
+ public IntervalST(List<Long> mins, List<Long> maxs, List<Value> values) {
+ // read only once constructed
+ for (int i = 0; i < mins.size(); i++) {
+ insert(mins.get(i), maxs.get(i), values.get(i));
+ }
+ }
+
+ private void insert(long min, long max, Value value) {
+ root = insert(root, new Interval(min, max), value);
+ }
+
+ private Node insert(Node node, Interval interval, Value value) {
+ if (node == null) {
+ return new Node(interval, value);
+ }
+
+ int cmp = interval.compareTo(node.interval);
+ if (cmp == 0) {
+ node.valueList.add(value);
+ return node;
+ } else if (cmp < 0) {
+ node.left = insert(node.left, interval, value);
+ } else {
+ node.right = insert(node.right, interval, value);
+ }
+
+ fixAuxiliaryInfo(node);
+ int balance = getBalance(node);
+ // Balance current subtree
+ if (balance < -1) {
+ if (getBalance(node.right) > 0) {
+ node.right = rotateRight(node.right); // Right-left case
+ }
+ node = rotateLeft(node);
+ } else if (balance > 1) {
+ if (getBalance(node.left) < 0) {
+ node.left = rotateLeft(node.left); // Left-right case
+ }
+ node = rotateRight(node);
+ }
+ return node;
+ }
+
+ // Get all intervals which intersect with input range [min, max]
+ public List<Value> searchAll(long min, long max) {
+ return searchAll(new Interval(min, max));
+ }
+
+ public List<Value> searchAll(Interval interval) {
+ List<Value> list = new ArrayList<Value>();
+ searchAll(root, interval, list);
+ return list;
+ }
+
+ private boolean searchAll(Node<Value> node, Interval interval, List<Value> list) {
+ boolean foundRoot = false;
+ boolean foundLeft = false;
+ boolean foundRight = false;
+ if (node == null)
+ return false;
+ if (interval.intersects(node.interval)) {
+ list.addAll(node.valueList);
+ foundRoot = true;
+ }
+ if (node.left != null && node.left.max >= interval.min) {
Review comment:
(Critical) I don't think this will work.
E.g.
```
root [10, 20]
/
[0, 5]
\
[1, 10]
Interval: [6, 10]
```
This algorithm will miss the interval of `[1, 10]`
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] Jackie-Jiang commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
Jackie-Jiang commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r523330566
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/intervalST/IntervalST.java
##########
@@ -0,0 +1,187 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner.intervalST;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+
+// A read-only interval search tree based on AVL Tree
+public class IntervalST<Value> {
+
+ private Node<Value> root;
+
+ public IntervalST(List<Long> mins, List<Long> maxs, List<Value> values) {
Review comment:
Since this is a read-only interval search tree, we can simplify the tree construction with the following steps:
1. Sort the intervals
2. Construct a full BST from the sorted intervals
3. Use DFS to generate the auxiliary info
One step further, you can skip the step 2 and directly use the sorted intervals as the tree structure and use index to access the full BST (calculate the index is a little bit tricky though)
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] Jackie-Jiang commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
Jackie-Jiang commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r523337387
##########
File path: pinot-spi/src/main/java/org/apache/pinot/spi/config/table/RoutingConfig.java
##########
@@ -27,6 +27,7 @@
public class RoutingConfig extends BaseJsonConfig {
public static final String PARTITION_SEGMENT_PRUNER_TYPE = "partition";
+ public static final String TIME_RANGE_SEGMENT_PRUNER_TYPE = "timeRange";
Review comment:
Let's name it `time` to be consistent with `partition`. Also it works not only on time range, but also point time lookup
```suggestion
public static final String TIME_SEGMENT_PRUNER_TYPE = "time";
```
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] jtao15 commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
jtao15 commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r522527116
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeRangeSegmentPruner.java
##########
@@ -0,0 +1,348 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeRangeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeRangeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeRangeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+
+ public TimeRangeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ updateTimeRangeMSToSegmentSearchTree(onlineSegments);
+ }
+
+ private void updateTimeRangeMSToSegmentSearchTree(Set<String> onlineSegments) {
+ List<String> segments = new ArrayList<>(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ List<String> segmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: segments) {
+ segmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(segmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ List<Long> startTimes = new ArrayList<>();
+ List<Long> endTimes = new ArrayList<>();
+
+ for (int i = 0; i < segments.size(); i++) {
+ String segment = segments.get(i);
+
+ long[] range = extractStartEndTimeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ startTimes.add(range[0]);
+ endTimes.add(range[1]);
+ }
+
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(startTimes, endTimes, segments);
+ }
+
+
+ private long[] extractStartEndTimeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ long[] range = {MIN_START_TIME, MAX_END_TIME};
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ range[0] = timeUnit.toMillis(startTime);
+ range[1] = timeUnit.toMillis(endTime);
+ return range;
+ }
+
+ @Override
+ public void refreshSegment(String segment) {
+ Set<String> segments;
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ segments = new HashSet<>();
+ } else {
+ segments = _timeRangeMSToSegmentSearchTree.getAllValues();
+ }
+ if (!segment.contains(segment)) {
+ segments.add(segment);
+ }
+
+ updateTimeRangeMSToSegmentSearchTree(segments);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ return segments;
+ }
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> ranges = getFilterTimeRange(filterQueryTree);
+ if (ranges == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (ranges.size() == 0) { // invalid query time range
+ return Collections.emptySet();
+ }
+
+ Set<String> prunedSegments = new HashSet<>();
+ for (Interval range : ranges) {
+ Interval rangeMS = convertRangeToMS(range);
+ for (Object segment : _timeRangeMSToSegmentSearchTree.searchAll(rangeMS)) {
+ if (segments.contains(segment)) {
+ prunedSegments.add((String) segment);
+ }
+ }
+ }
+ return new HashSet<String>(prunedSegments);
+ }
+
+ private List<Interval> getFilterTimeRange(FilterQueryTree filterQueryTree) {
+ // return NUll if no time range info or cannot filter base on the info (e.g. 'SELECT * from myTable where time < 50 OR firstName = Jason')
+ // return an empty list if filtering range is specified but invalid (e.g. 'SELECT * from myTable where time < 50 AND time > 100')
+ switch (filterQueryTree.getOperator()) {
+ case AND:
+ List<List<Interval>> andRanges = new ArrayList<>();
Review comment:
Say I have one child ranges as { [1, 4], [8, 10]} (from OR operator), another as {[3, 5], [7, 9]}. The merged result should be {[3, 4], [8, 9]}. If I put all child ranges into one list as { [1, 4], [8, 10], [3, 5], [7, 9]}, some helper informations are needed to track which ranges are from the same child to avoid calculate the intersections between them. In this case I should not calculate the intersection between [1, 4] and [8, 10].
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] Jackie-Jiang commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
Jackie-Jiang commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r523263416
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/intervalST/Interval.java
##########
@@ -0,0 +1,98 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner.intervalST;
+
+import com.google.common.base.Preconditions;
+
+
+public class Interval implements Comparable<Interval> {
+ // interval with both ends inclusive [min, max]
+ public final long min;
+ public final long max;
+
+ public Interval(long min, long max) {
+ Preconditions.checkState(min <= max, "invalid interval [{}, {}]", min, max);
+ this.min = min;
+ this.max = max;
+ }
+
+ public boolean intersects(Interval that) {
+ Preconditions.checkNotNull(that, "Invalid interval: null");
+ if (that.max < this.min) {
+ return false;
+ }
+ if (this.max < that.min) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public int compareTo(Interval that) {
+ Preconditions.checkNotNull(that, "Compare to invalid interval: null");
+ if (this.min < that.min) {
+ return -1;
+ } else if (this.min > that.min) {
+ return 1;
+ } else if (this.max < that.max) {
+ return -1;
+ } else if (this.max > that.max) {
+ return 1;
+ }
+ else return 0;
+ }
+
+ @Override
+ public int hashCode() {
+ return (int)(min * 17 + max);
+ }
+
+ @Override
+ public boolean equals(Object that) {
+ if (that instanceof Interval && that != null
+ && this.min == ((Interval)that).min && this.max == ((Interval)that).max) {
+ return true;
+ }
+ return false;
+ }
+
+ public static Interval getIntersection(Interval a, Interval b) {
+ Preconditions.checkNotNull(a, "Invalid interval: null");
Review comment:
We don't usually use Nonnull annotation but only use Nullable because they look very similar. Arguments without an annotation should be non-null.
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] siddharthteotia commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
siddharthteotia commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r521869660
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentselector/RealtimeSegmentSelector.java
##########
@@ -52,8 +53,8 @@
public static final String FORCE_HLC = "FORCE_HLC";
private final AtomicLong _requestId = new AtomicLong();
- private volatile List<List<String>> _hlcSegments;
Review comment:
Is it possible to not have this interface change of List to Set by handling the logic inside the pruner. I believe the change of List to Set comes because otherwise you need a memcpy in the prune() method?
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] Jackie-Jiang commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
Jackie-Jiang commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r523262805
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/intervalST/Interval.java
##########
@@ -0,0 +1,98 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner.intervalST;
+
+import com.google.common.base.Preconditions;
+
+
+public class Interval implements Comparable<Interval> {
+ // interval with both ends inclusive [min, max]
+ public final long min;
Review comment:
Prefix the member variables with `_` and avoid using `this.`
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] siddharthteotia commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
siddharthteotia commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r521869463
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeRangeSegmentPruner.java
##########
@@ -0,0 +1,348 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeRangeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeRangeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeRangeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+
+ public TimeRangeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ updateTimeRangeMSToSegmentSearchTree(onlineSegments);
+ }
+
+ private void updateTimeRangeMSToSegmentSearchTree(Set<String> onlineSegments) {
+ List<String> segments = new ArrayList<>(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ List<String> segmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: segments) {
+ segmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(segmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ List<Long> startTimes = new ArrayList<>();
+ List<Long> endTimes = new ArrayList<>();
+
+ for (int i = 0; i < segments.size(); i++) {
+ String segment = segments.get(i);
+
+ long[] range = extractStartEndTimeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ startTimes.add(range[0]);
+ endTimes.add(range[1]);
+ }
+
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(startTimes, endTimes, segments);
+ }
+
+
+ private long[] extractStartEndTimeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ long[] range = {MIN_START_TIME, MAX_END_TIME};
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ range[0] = timeUnit.toMillis(startTime);
+ range[1] = timeUnit.toMillis(endTime);
+ return range;
+ }
+
+ @Override
+ public void refreshSegment(String segment) {
+ Set<String> segments;
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ segments = new HashSet<>();
+ } else {
+ segments = _timeRangeMSToSegmentSearchTree.getAllValues();
+ }
+ if (!segment.contains(segment)) {
+ segments.add(segment);
+ }
+
+ updateTimeRangeMSToSegmentSearchTree(segments);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ return segments;
+ }
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> ranges = getFilterTimeRange(filterQueryTree);
+ if (ranges == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (ranges.size() == 0) { // invalid query time range
+ return Collections.emptySet();
+ }
+
+ Set<String> prunedSegments = new HashSet<>();
+ for (Interval range : ranges) {
+ Interval rangeMS = convertRangeToMS(range);
+ for (Object segment : _timeRangeMSToSegmentSearchTree.searchAll(rangeMS)) {
+ if (segments.contains(segment)) {
+ prunedSegments.add((String) segment);
+ }
+ }
+ }
+ return new HashSet<String>(prunedSegments);
+ }
+
+ private List<Interval> getFilterTimeRange(FilterQueryTree filterQueryTree) {
+ // return NUll if no time range info or cannot filter base on the info (e.g. 'SELECT * from myTable where time < 50 OR firstName = Jason')
+ // return an empty list if filtering range is specified but invalid (e.g. 'SELECT * from myTable where time < 50 AND time > 100')
+ switch (filterQueryTree.getOperator()) {
+ case AND:
+ List<List<Interval>> andRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges != null) {
+ andRanges.add(childRanges);
+ }
+ }
+ return getIntersectionSortedRanges(andRanges);
+ case OR:
+ List<List<Interval>> orRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges == null) {
+ return null;
+ } else {
+ orRanges.add(childRanges);
+ }
+ }
+ return getUnionSortedRanges(orRanges);
+ case EQUALITY:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ long timeStamp = Long.parseLong(filterQueryTree.getValue().get(0));
+ return Collections.singletonList(new Interval(timeStamp, timeStamp));
+ }
+ return null;
+ case RANGE:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ return parseRange(filterQueryTree.getValue());
+ }
+ return null;
+ default:
+ return null;
+ }
+ }
+
+ private Interval convertRangeToMS(Interval range) {
+ long min = range.min == MIN_START_TIME ? MIN_START_TIME : _timeUnit.toMillis(range.min);
+ long max = range.max == MAX_END_TIME ? MAX_END_TIME : _timeUnit.toMillis(range.max);
+ return new Interval(min, max);
+ }
+
+ private List<Interval> getIntersectionSortedRanges(List<List<Interval>> ranges) {
+ // Requires input ranges are sorted, the return ranges will be sorted
+ return getIntersectionSortedRanges(ranges, 0, ranges.size());
+ }
+
+ private List<Interval> getIntersectionSortedRanges(List<List<Interval>> ranges, int start, int end) {
+ if (start == end) {
+ return null;
+ }
+
+ if (start + 1 == end) {
+ return ranges.get(start);
+ }
+
+ int mid = start + (end - start) / 2;
+ List<Interval> ranges1 = getIntersectionSortedRanges(ranges, start, mid);
+ List<Interval> ranges2 = getIntersectionSortedRanges(ranges, mid, end);
+ return getIntersectionOfTwoSortedRanges(ranges1, ranges2);
+ }
+
+ private List<Interval> getIntersectionOfTwoSortedRanges(List<Interval> ranges1, List<Interval> ranges2) { // sorted non-overlapping ranges
+ List<Interval> res = new ArrayList<>();
+ int i = 0, j = 0;
+ while (i < ranges1.size() && j < ranges2.size()) {
+ Interval range1 = ranges1.get(i);
+ Interval range2 = ranges2.get(j);
+ if (range1.intersects(range2)) {
+ res.add(Interval.getIntersection(range1, range2));
+ }
+ if (range1.max < range2.max) {
+ i++;
+ } else {
+ j++;
+ }
+ }
+ return res;
+ }
+
+ private List<Interval> getUnionSortedRanges(List<List<Interval>> ranges) {
+ return getUnionSortedRanges(ranges, 0, ranges.size());
+ }
+
+ private List<Interval> getUnionSortedRanges(List<List<Interval>> ranges, int start, int end) {
Review comment:
I think List<List> is complicating the algorithm slightly. We can combine these two methods into one method that sorted merge of two List<Interval>
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] Jackie-Jiang commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
Jackie-Jiang commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r527267036
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeSegmentPruner.java
##########
@@ -0,0 +1,340 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+ private final Map _segmentToTimeRangeMSCache;
+
+ public TimeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ _segmentToTimeRangeMSCache = new HashMap<String, Interval>();
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ synchronized public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
Review comment:
Put `synchronized` after `public` (actually `synchronized` is not needed here as it is already synchronized by the caller, but okay to have for readability), same for other signatures.
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeSegmentPruner.java
##########
@@ -0,0 +1,340 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+ private final Map _segmentToTimeRangeMSCache;
+
+ public TimeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ _segmentToTimeRangeMSCache = new HashMap<String, Interval>();
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ synchronized public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ List<String> newSegments = new ArrayList<>();
+ for (String onlineSegment : onlineSegments) {
+ if (!_segmentToTimeRangeMSCache.containsKey(onlineSegment)) {
+ newSegments.add(onlineSegment);
+ }
+ }
+
+ List<String> newSegmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: newSegments) {
+ newSegmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(newSegmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ for (int i = 0; i < newSegments.size(); i++) {
+ String segment = newSegments.get(i);
+ Interval range = extractTimeRangeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ _segmentToTimeRangeMSCache.put(segment, range);
+ }
+ _segmentToTimeRangeMSCache.keySet().retainAll(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(_segmentToTimeRangeMSCache);
+ }
+
+ private Interval extractTimeRangeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
Review comment:
We usually use `Ms` instead of `MS`. Also, suggest simplifying the name as `extractIntervalFromSegmentZKMetadataZNRecord`
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeSegmentPruner.java
##########
@@ -0,0 +1,340 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+ private final Map _segmentToTimeRangeMSCache;
+
+ public TimeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ _segmentToTimeRangeMSCache = new HashMap<String, Interval>();
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ synchronized public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ List<String> newSegments = new ArrayList<>();
+ for (String onlineSegment : onlineSegments) {
+ if (!_segmentToTimeRangeMSCache.containsKey(onlineSegment)) {
+ newSegments.add(onlineSegment);
+ }
+ }
+
+ List<String> newSegmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: newSegments) {
+ newSegmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(newSegmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ for (int i = 0; i < newSegments.size(); i++) {
+ String segment = newSegments.get(i);
+ Interval range = extractTimeRangeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ _segmentToTimeRangeMSCache.put(segment, range);
+ }
+ _segmentToTimeRangeMSCache.keySet().retainAll(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(_segmentToTimeRangeMSCache);
+ }
+
+ private Interval extractTimeRangeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ Interval defaultRange = new Interval(MIN_START_TIME, MAX_END_TIME);
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return defaultRange;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return defaultRange;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ return new Interval(timeUnit.toMillis(startTime), timeUnit.toMillis(endTime));
+ }
+
+ @Override
+ synchronized public void refreshSegment(String segment) {
+ List<ZNRecord> znRecords = _propertyStore.get(Collections.singletonList(_segmentZKMetadataPathPrefix + segment), null, AccessOption.PERSISTENT, true);
+ Interval range = extractTimeRangeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(0));
+ _segmentToTimeRangeMSCache.put(segment, range);
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(_segmentToTimeRangeMSCache);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ return segments;
+ }
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> ranges = getFilterTimeRange(filterQueryTree);
+ if (ranges == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (ranges.size() == 0) { // invalid query time range
+ return Collections.emptySet();
+ }
+
+ Set<String> selectedSegments = new HashSet<>();
+ for (Interval range : ranges) {
+ Interval rangeMS = convertRangeToMS(range);
+ for (Object segment : _timeRangeMSToSegmentSearchTree.searchAll(rangeMS)) {
+ if (segments.contains(segment)) {
+ selectedSegments.add((String) segment);
+ }
+ }
+ }
+ return selectedSegments;
+ }
+
+ private List<Interval> getFilterTimeRange(FilterQueryTree filterQueryTree) {
+ // return NUll if no time range info or cannot filter base on the info (e.g. 'SELECT * from myTable where time < 50 OR firstName = Jason')
+ // return an empty list if filtering range is specified but invalid (e.g. 'SELECT * from myTable where time < 50 AND time > 100')
+ switch (filterQueryTree.getOperator()) {
+ case AND:
+ List<List<Interval>> andRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges != null) {
+ andRanges.add(childRanges);
+ }
+ }
+ return getIntersectionSortedRanges(andRanges);
+ case OR:
+ List<List<Interval>> orRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges == null) {
+ return null;
+ } else {
+ orRanges.add(childRanges);
+ }
+ }
+ return getUnionSortedRanges(orRanges);
+ case EQUALITY:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ long timeStamp = Long.parseLong(filterQueryTree.getValue().get(0));
+ return Collections.singletonList(new Interval(timeStamp, timeStamp));
+ }
+ return null;
+ case RANGE:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ return parseRange(filterQueryTree.getValue());
+ }
+ return null;
+ default:
+ return null;
+ }
+ }
+
+ private Interval convertRangeToMS(Interval range) {
+ long min = range._min == MIN_START_TIME ? MIN_START_TIME : _timeUnit.toMillis(range._min);
+ long max = range._max == MAX_END_TIME ? MAX_END_TIME : _timeUnit.toMillis(range._max);
+ return new Interval(min, max);
+ }
+
+ private List<Interval> getIntersectionSortedRanges(List<List<Interval>> ranges) {
+ // Requires input ranges are sorted, the return ranges will be sorted
+ return getIntersectionSortedRanges(ranges, 0, ranges.size());
+ }
+
+ private List<Interval> getIntersectionSortedRanges(List<List<Interval>> ranges, int start, int end) {
+ if (start == end) {
+ return null;
+ }
+
+ if (start + 1 == end) {
+ return ranges.get(start);
+ }
+
+ int mid = start + (end - start) / 2;
+ List<Interval> ranges1 = getIntersectionSortedRanges(ranges, start, mid);
+ List<Interval> ranges2 = getIntersectionSortedRanges(ranges, mid, end);
+ return getIntersectionOfTwoSortedRanges(ranges1, ranges2);
+ }
+
+ private List<Interval> getIntersectionOfTwoSortedRanges(List<Interval> ranges1, List<Interval> ranges2) { // sorted non-overlapping ranges
+ List<Interval> res = new ArrayList<>();
+ int i = 0, j = 0;
Review comment:
Split into 2 lines
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeSegmentPruner.java
##########
@@ -0,0 +1,340 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+ private final Map _segmentToTimeRangeMSCache;
+
+ public TimeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ _segmentToTimeRangeMSCache = new HashMap<String, Interval>();
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
Review comment:
You may refer to `PartitionSegmentPruner` where we do batch read for `init()` and single read for `onExternalViewChange()` because usually external view change only involves change for one segment.
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeSegmentPruner.java
##########
@@ -0,0 +1,340 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+ private final Map _segmentToTimeRangeMSCache;
+
+ public TimeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ _segmentToTimeRangeMSCache = new HashMap<String, Interval>();
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ synchronized public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ List<String> newSegments = new ArrayList<>();
+ for (String onlineSegment : onlineSegments) {
+ if (!_segmentToTimeRangeMSCache.containsKey(onlineSegment)) {
+ newSegments.add(onlineSegment);
+ }
+ }
+
+ List<String> newSegmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: newSegments) {
+ newSegmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(newSegmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ for (int i = 0; i < newSegments.size(); i++) {
+ String segment = newSegments.get(i);
+ Interval range = extractTimeRangeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ _segmentToTimeRangeMSCache.put(segment, range);
+ }
+ _segmentToTimeRangeMSCache.keySet().retainAll(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(_segmentToTimeRangeMSCache);
+ }
+
+ private Interval extractTimeRangeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ Interval defaultRange = new Interval(MIN_START_TIME, MAX_END_TIME);
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return defaultRange;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return defaultRange;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ return new Interval(timeUnit.toMillis(startTime), timeUnit.toMillis(endTime));
+ }
+
+ @Override
+ synchronized public void refreshSegment(String segment) {
+ List<ZNRecord> znRecords = _propertyStore.get(Collections.singletonList(_segmentZKMetadataPathPrefix + segment), null, AccessOption.PERSISTENT, true);
+ Interval range = extractTimeRangeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(0));
+ _segmentToTimeRangeMSCache.put(segment, range);
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(_segmentToTimeRangeMSCache);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ return segments;
+ }
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> ranges = getFilterTimeRange(filterQueryTree);
+ if (ranges == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (ranges.size() == 0) { // invalid query time range
+ return Collections.emptySet();
+ }
+
+ Set<String> selectedSegments = new HashSet<>();
+ for (Interval range : ranges) {
+ Interval rangeMS = convertRangeToMS(range);
+ for (Object segment : _timeRangeMSToSegmentSearchTree.searchAll(rangeMS)) {
+ if (segments.contains(segment)) {
+ selectedSegments.add((String) segment);
+ }
+ }
+ }
+ return selectedSegments;
+ }
+
+ private List<Interval> getFilterTimeRange(FilterQueryTree filterQueryTree) {
+ // return NUll if no time range info or cannot filter base on the info (e.g. 'SELECT * from myTable where time < 50 OR firstName = Jason')
+ // return an empty list if filtering range is specified but invalid (e.g. 'SELECT * from myTable where time < 50 AND time > 100')
+ switch (filterQueryTree.getOperator()) {
+ case AND:
+ List<List<Interval>> andRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges != null) {
+ andRanges.add(childRanges);
+ }
+ }
+ return getIntersectionSortedRanges(andRanges);
+ case OR:
+ List<List<Interval>> orRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges == null) {
+ return null;
+ } else {
+ orRanges.add(childRanges);
+ }
+ }
+ return getUnionSortedRanges(orRanges);
+ case EQUALITY:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ long timeStamp = Long.parseLong(filterQueryTree.getValue().get(0));
+ return Collections.singletonList(new Interval(timeStamp, timeStamp));
+ }
+ return null;
+ case RANGE:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ return parseRange(filterQueryTree.getValue());
+ }
+ return null;
+ default:
+ return null;
+ }
+ }
+
+ private Interval convertRangeToMS(Interval range) {
+ long min = range._min == MIN_START_TIME ? MIN_START_TIME : _timeUnit.toMillis(range._min);
+ long max = range._max == MAX_END_TIME ? MAX_END_TIME : _timeUnit.toMillis(range._max);
+ return new Interval(min, max);
+ }
+
+ private List<Interval> getIntersectionSortedRanges(List<List<Interval>> ranges) {
+ // Requires input ranges are sorted, the return ranges will be sorted
+ return getIntersectionSortedRanges(ranges, 0, ranges.size());
+ }
+
+ private List<Interval> getIntersectionSortedRanges(List<List<Interval>> ranges, int start, int end) {
+ if (start == end) {
+ return null;
+ }
+
+ if (start + 1 == end) {
+ return ranges.get(start);
+ }
+
+ int mid = start + (end - start) / 2;
+ List<Interval> ranges1 = getIntersectionSortedRanges(ranges, start, mid);
+ List<Interval> ranges2 = getIntersectionSortedRanges(ranges, mid, end);
+ return getIntersectionOfTwoSortedRanges(ranges1, ranges2);
+ }
+
+ private List<Interval> getIntersectionOfTwoSortedRanges(List<Interval> ranges1, List<Interval> ranges2) { // sorted non-overlapping ranges
+ List<Interval> res = new ArrayList<>();
+ int i = 0, j = 0;
+ while (i < ranges1.size() && j < ranges2.size()) {
+ Interval range1 = ranges1.get(i);
+ Interval range2 = ranges2.get(j);
+ if (range1.intersects(range2)) {
+ res.add(Interval.getIntersection(range1, range2));
+ }
+ if (range1._max < range2._max) {
+ i++;
+ } else {
+ j++;
+ }
+ }
+ return res;
+ }
+
+ private List<Interval> getUnionSortedRanges(List<List<Interval>> ranges) {
+ return getUnionSortedRanges(ranges, 0, ranges.size());
+ }
+
+ private List<Interval> getUnionSortedRanges(List<List<Interval>> ranges, int start, int end) {
+ if (start == end) {
+ return null;
+ }
+
+ if (start + 1 == end) {
+ return ranges.get(start);
+ }
+
+ int mid = start + (end - start) / 2;
+ List<Interval> ranges1 = getUnionSortedRanges(ranges, start, mid);
+ List<Interval> ranges2 = getUnionSortedRanges(ranges, mid, end);
+ return getUnionOfTwoSortedRanges(ranges1, ranges2);
+ }
+
+ private List<Interval> getUnionOfTwoSortedRanges(List<Interval> ranges1, List<Interval> ranges2) { // sorted non-overlapping ranges
+ List<Interval> res = new ArrayList<>();
+ int i = 0, j = 0;
+
+ while (i < ranges1.size() || j < ranges2.size()) {
+ if (j == ranges2.size() || i < ranges1.size() && ranges1.get(i).compareTo(ranges2.get(j)) <= 0) {
+ if (res.size() == 0 || !ranges1.get(i).intersects(res.get(res.size()-1))) {
+ res.add(ranges1.get(i));
+ } else {
+ res.set(res.size()-1, Interval.getUnion(res.get(res.size()-1), (ranges1.get(i))));
+ }
+ i++;
+ } else {
+ if (res.size() == 0 || !ranges2.get(j).intersects(res.get(res.size()-1))) {
+ res.add(ranges2.get(j));
+ } else {
+ res.set(res.size()-1, Interval.getUnion(res.get(res.size()-1), (ranges2.get(j))));
+ }
+ j++;
+ }
+ }
+ return res;
+ }
+
+ private List<Interval> parseRange(List<String> rangeExpressions) {
Review comment:
Here you can handle SDF and directly parse the range into interval in millis
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeSegmentPruner.java
##########
@@ -0,0 +1,340 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+ private final Map _segmentToTimeRangeMSCache;
+
+ public TimeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ _segmentToTimeRangeMSCache = new HashMap<String, Interval>();
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ synchronized public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ List<String> newSegments = new ArrayList<>();
+ for (String onlineSegment : onlineSegments) {
+ if (!_segmentToTimeRangeMSCache.containsKey(onlineSegment)) {
+ newSegments.add(onlineSegment);
+ }
+ }
+
+ List<String> newSegmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: newSegments) {
+ newSegmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(newSegmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ for (int i = 0; i < newSegments.size(); i++) {
+ String segment = newSegments.get(i);
+ Interval range = extractTimeRangeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ _segmentToTimeRangeMSCache.put(segment, range);
+ }
+ _segmentToTimeRangeMSCache.keySet().retainAll(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(_segmentToTimeRangeMSCache);
+ }
+
+ private Interval extractTimeRangeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ Interval defaultRange = new Interval(MIN_START_TIME, MAX_END_TIME);
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return defaultRange;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return defaultRange;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ return new Interval(timeUnit.toMillis(startTime), timeUnit.toMillis(endTime));
+ }
+
+ @Override
+ synchronized public void refreshSegment(String segment) {
+ List<ZNRecord> znRecords = _propertyStore.get(Collections.singletonList(_segmentZKMetadataPathPrefix + segment), null, AccessOption.PERSISTENT, true);
+ Interval range = extractTimeRangeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(0));
+ _segmentToTimeRangeMSCache.put(segment, range);
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(_segmentToTimeRangeMSCache);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
Review comment:
Cache `_timeRangeMSToSegmentSearchTree` into a local variable in case it is swapped during this method
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeSegmentPruner.java
##########
@@ -0,0 +1,340 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+ private final Map _segmentToTimeRangeMSCache;
Review comment:
```suggestion
private volatile IntervalST<String> _intervalTree;
private final Map<String, Interval> _intervalMap;
```
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeSegmentPruner.java
##########
@@ -0,0 +1,340 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+ private final Map _segmentToTimeRangeMSCache;
+
+ public TimeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ _segmentToTimeRangeMSCache = new HashMap<String, Interval>();
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ synchronized public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ List<String> newSegments = new ArrayList<>();
+ for (String onlineSegment : onlineSegments) {
+ if (!_segmentToTimeRangeMSCache.containsKey(onlineSegment)) {
+ newSegments.add(onlineSegment);
+ }
+ }
+
+ List<String> newSegmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: newSegments) {
+ newSegmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(newSegmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ for (int i = 0; i < newSegments.size(); i++) {
+ String segment = newSegments.get(i);
+ Interval range = extractTimeRangeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ _segmentToTimeRangeMSCache.put(segment, range);
+ }
+ _segmentToTimeRangeMSCache.keySet().retainAll(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(_segmentToTimeRangeMSCache);
+ }
+
+ private Interval extractTimeRangeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ Interval defaultRange = new Interval(MIN_START_TIME, MAX_END_TIME);
Review comment:
Put `defaultRange` as a constant
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeSegmentPruner.java
##########
@@ -0,0 +1,340 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+ private final Map _segmentToTimeRangeMSCache;
+
+ public TimeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ _segmentToTimeRangeMSCache = new HashMap<String, Interval>();
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ synchronized public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ List<String> newSegments = new ArrayList<>();
+ for (String onlineSegment : onlineSegments) {
+ if (!_segmentToTimeRangeMSCache.containsKey(onlineSegment)) {
+ newSegments.add(onlineSegment);
+ }
+ }
+
+ List<String> newSegmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: newSegments) {
+ newSegmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(newSegmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ for (int i = 0; i < newSegments.size(); i++) {
+ String segment = newSegments.get(i);
+ Interval range = extractTimeRangeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ _segmentToTimeRangeMSCache.put(segment, range);
+ }
+ _segmentToTimeRangeMSCache.keySet().retainAll(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(_segmentToTimeRangeMSCache);
+ }
+
+ private Interval extractTimeRangeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ Interval defaultRange = new Interval(MIN_START_TIME, MAX_END_TIME);
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return defaultRange;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return defaultRange;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ return new Interval(timeUnit.toMillis(startTime), timeUnit.toMillis(endTime));
+ }
+
+ @Override
+ synchronized public void refreshSegment(String segment) {
+ List<ZNRecord> znRecords = _propertyStore.get(Collections.singletonList(_segmentZKMetadataPathPrefix + segment), null, AccessOption.PERSISTENT, true);
+ Interval range = extractTimeRangeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(0));
+ _segmentToTimeRangeMSCache.put(segment, range);
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(_segmentToTimeRangeMSCache);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ return segments;
+ }
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> ranges = getFilterTimeRange(filterQueryTree);
+ if (ranges == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (ranges.size() == 0) { // invalid query time range
+ return Collections.emptySet();
+ }
+
+ Set<String> selectedSegments = new HashSet<>();
+ for (Interval range : ranges) {
+ Interval rangeMS = convertRangeToMS(range);
+ for (Object segment : _timeRangeMSToSegmentSearchTree.searchAll(rangeMS)) {
+ if (segments.contains(segment)) {
+ selectedSegments.add((String) segment);
+ }
+ }
+ }
+ return selectedSegments;
+ }
+
+ private List<Interval> getFilterTimeRange(FilterQueryTree filterQueryTree) {
+ // return NUll if no time range info or cannot filter base on the info (e.g. 'SELECT * from myTable where time < 50 OR firstName = Jason')
Review comment:
Put these comments as the javadoc for this method
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeSegmentPruner.java
##########
@@ -0,0 +1,340 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+ private final Map _segmentToTimeRangeMSCache;
+
+ public TimeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ _segmentToTimeRangeMSCache = new HashMap<String, Interval>();
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ synchronized public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ List<String> newSegments = new ArrayList<>();
+ for (String onlineSegment : onlineSegments) {
+ if (!_segmentToTimeRangeMSCache.containsKey(onlineSegment)) {
+ newSegments.add(onlineSegment);
+ }
+ }
+
+ List<String> newSegmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: newSegments) {
+ newSegmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(newSegmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ for (int i = 0; i < newSegments.size(); i++) {
+ String segment = newSegments.get(i);
+ Interval range = extractTimeRangeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ _segmentToTimeRangeMSCache.put(segment, range);
+ }
+ _segmentToTimeRangeMSCache.keySet().retainAll(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(_segmentToTimeRangeMSCache);
+ }
+
+ private Interval extractTimeRangeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ Interval defaultRange = new Interval(MIN_START_TIME, MAX_END_TIME);
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return defaultRange;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return defaultRange;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ return new Interval(timeUnit.toMillis(startTime), timeUnit.toMillis(endTime));
+ }
+
+ @Override
+ synchronized public void refreshSegment(String segment) {
+ List<ZNRecord> znRecords = _propertyStore.get(Collections.singletonList(_segmentZKMetadataPathPrefix + segment), null, AccessOption.PERSISTENT, true);
+ Interval range = extractTimeRangeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(0));
+ _segmentToTimeRangeMSCache.put(segment, range);
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(_segmentToTimeRangeMSCache);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ return segments;
+ }
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> ranges = getFilterTimeRange(filterQueryTree);
+ if (ranges == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (ranges.size() == 0) { // invalid query time range
Review comment:
(nit)
```suggestion
if (ranges.isEmpty()) { // invalid query time range
```
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeSegmentPruner.java
##########
@@ -0,0 +1,340 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+ private final Map _segmentToTimeRangeMSCache;
+
+ public TimeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
Review comment:
Keeping `_timeUnit` is not enough, you need to keep the `formatSpec` in order to handle the simple data format (e.g. `"2020-11-19"`)
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeSegmentPruner.java
##########
@@ -0,0 +1,340 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
Review comment:
```suggestion
private final ZkHelixPropertyStore<ZNRecord> _propertyStore;
```
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeSegmentPruner.java
##########
@@ -0,0 +1,340 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+ private final Map _segmentToTimeRangeMSCache;
+
+ public TimeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ _segmentToTimeRangeMSCache = new HashMap<String, Interval>();
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ synchronized public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ List<String> newSegments = new ArrayList<>();
+ for (String onlineSegment : onlineSegments) {
+ if (!_segmentToTimeRangeMSCache.containsKey(onlineSegment)) {
+ newSegments.add(onlineSegment);
+ }
+ }
+
+ List<String> newSegmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: newSegments) {
+ newSegmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(newSegmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ for (int i = 0; i < newSegments.size(); i++) {
+ String segment = newSegments.get(i);
+ Interval range = extractTimeRangeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ _segmentToTimeRangeMSCache.put(segment, range);
+ }
+ _segmentToTimeRangeMSCache.keySet().retainAll(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(_segmentToTimeRangeMSCache);
+ }
+
+ private Interval extractTimeRangeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ Interval defaultRange = new Interval(MIN_START_TIME, MAX_END_TIME);
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return defaultRange;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return defaultRange;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ return new Interval(timeUnit.toMillis(startTime), timeUnit.toMillis(endTime));
+ }
+
+ @Override
+ synchronized public void refreshSegment(String segment) {
+ List<ZNRecord> znRecords = _propertyStore.get(Collections.singletonList(_segmentZKMetadataPathPrefix + segment), null, AccessOption.PERSISTENT, true);
+ Interval range = extractTimeRangeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(0));
+ _segmentToTimeRangeMSCache.put(segment, range);
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(_segmentToTimeRangeMSCache);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ return segments;
+ }
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> ranges = getFilterTimeRange(filterQueryTree);
+ if (ranges == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (ranges.size() == 0) { // invalid query time range
+ return Collections.emptySet();
+ }
+
+ Set<String> selectedSegments = new HashSet<>();
+ for (Interval range : ranges) {
+ Interval rangeMS = convertRangeToMS(range);
+ for (Object segment : _timeRangeMSToSegmentSearchTree.searchAll(rangeMS)) {
+ if (segments.contains(segment)) {
+ selectedSegments.add((String) segment);
+ }
+ }
+ }
+ return selectedSegments;
+ }
+
+ private List<Interval> getFilterTimeRange(FilterQueryTree filterQueryTree) {
Review comment:
Annotate the return as nullable
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeSegmentPruner.java
##########
@@ -0,0 +1,340 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+ private final Map _segmentToTimeRangeMSCache;
+
+ public TimeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ _segmentToTimeRangeMSCache = new HashMap<String, Interval>();
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ synchronized public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ List<String> newSegments = new ArrayList<>();
+ for (String onlineSegment : onlineSegments) {
+ if (!_segmentToTimeRangeMSCache.containsKey(onlineSegment)) {
+ newSegments.add(onlineSegment);
+ }
+ }
+
+ List<String> newSegmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: newSegments) {
+ newSegmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(newSegmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ for (int i = 0; i < newSegments.size(); i++) {
+ String segment = newSegments.get(i);
+ Interval range = extractTimeRangeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ _segmentToTimeRangeMSCache.put(segment, range);
+ }
+ _segmentToTimeRangeMSCache.keySet().retainAll(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(_segmentToTimeRangeMSCache);
+ }
+
+ private Interval extractTimeRangeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ Interval defaultRange = new Interval(MIN_START_TIME, MAX_END_TIME);
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return defaultRange;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return defaultRange;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ return new Interval(timeUnit.toMillis(startTime), timeUnit.toMillis(endTime));
+ }
+
+ @Override
+ synchronized public void refreshSegment(String segment) {
+ List<ZNRecord> znRecords = _propertyStore.get(Collections.singletonList(_segmentZKMetadataPathPrefix + segment), null, AccessOption.PERSISTENT, true);
+ Interval range = extractTimeRangeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(0));
+ _segmentToTimeRangeMSCache.put(segment, range);
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(_segmentToTimeRangeMSCache);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ return segments;
+ }
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> ranges = getFilterTimeRange(filterQueryTree);
+ if (ranges == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (ranges.size() == 0) { // invalid query time range
+ return Collections.emptySet();
+ }
+
+ Set<String> selectedSegments = new HashSet<>();
+ for (Interval range : ranges) {
+ Interval rangeMS = convertRangeToMS(range);
+ for (Object segment : _timeRangeMSToSegmentSearchTree.searchAll(rangeMS)) {
+ if (segments.contains(segment)) {
+ selectedSegments.add((String) segment);
+ }
+ }
+ }
+ return selectedSegments;
+ }
+
+ private List<Interval> getFilterTimeRange(FilterQueryTree filterQueryTree) {
+ // return NUll if no time range info or cannot filter base on the info (e.g. 'SELECT * from myTable where time < 50 OR firstName = Jason')
+ // return an empty list if filtering range is specified but invalid (e.g. 'SELECT * from myTable where time < 50 AND time > 100')
+ switch (filterQueryTree.getOperator()) {
+ case AND:
+ List<List<Interval>> andRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges != null) {
+ andRanges.add(childRanges);
+ }
+ }
+ return getIntersectionSortedRanges(andRanges);
+ case OR:
+ List<List<Interval>> orRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges == null) {
+ return null;
+ } else {
+ orRanges.add(childRanges);
+ }
+ }
+ return getUnionSortedRanges(orRanges);
+ case EQUALITY:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ long timeStamp = Long.parseLong(filterQueryTree.getValue().get(0));
Review comment:
the time value in the query might not be numeric for simple date format
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeSegmentPruner.java
##########
@@ -0,0 +1,340 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+ private final Map _segmentToTimeRangeMSCache;
+
+ public TimeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ _segmentToTimeRangeMSCache = new HashMap<String, Interval>();
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ synchronized public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ List<String> newSegments = new ArrayList<>();
+ for (String onlineSegment : onlineSegments) {
+ if (!_segmentToTimeRangeMSCache.containsKey(onlineSegment)) {
+ newSegments.add(onlineSegment);
+ }
+ }
+
+ List<String> newSegmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: newSegments) {
+ newSegmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(newSegmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ for (int i = 0; i < newSegments.size(); i++) {
+ String segment = newSegments.get(i);
+ Interval range = extractTimeRangeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ _segmentToTimeRangeMSCache.put(segment, range);
+ }
+ _segmentToTimeRangeMSCache.keySet().retainAll(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(_segmentToTimeRangeMSCache);
+ }
+
+ private Interval extractTimeRangeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ Interval defaultRange = new Interval(MIN_START_TIME, MAX_END_TIME);
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return defaultRange;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return defaultRange;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ return new Interval(timeUnit.toMillis(startTime), timeUnit.toMillis(endTime));
+ }
+
+ @Override
+ synchronized public void refreshSegment(String segment) {
+ List<ZNRecord> znRecords = _propertyStore.get(Collections.singletonList(_segmentZKMetadataPathPrefix + segment), null, AccessOption.PERSISTENT, true);
+ Interval range = extractTimeRangeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(0));
+ _segmentToTimeRangeMSCache.put(segment, range);
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(_segmentToTimeRangeMSCache);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ return segments;
+ }
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> ranges = getFilterTimeRange(filterQueryTree);
+ if (ranges == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (ranges.size() == 0) { // invalid query time range
+ return Collections.emptySet();
+ }
+
+ Set<String> selectedSegments = new HashSet<>();
+ for (Interval range : ranges) {
+ Interval rangeMS = convertRangeToMS(range);
+ for (Object segment : _timeRangeMSToSegmentSearchTree.searchAll(rangeMS)) {
+ if (segments.contains(segment)) {
+ selectedSegments.add((String) segment);
+ }
+ }
+ }
+ return selectedSegments;
+ }
+
+ private List<Interval> getFilterTimeRange(FilterQueryTree filterQueryTree) {
+ // return NUll if no time range info or cannot filter base on the info (e.g. 'SELECT * from myTable where time < 50 OR firstName = Jason')
+ // return an empty list if filtering range is specified but invalid (e.g. 'SELECT * from myTable where time < 50 AND time > 100')
+ switch (filterQueryTree.getOperator()) {
+ case AND:
+ List<List<Interval>> andRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges != null) {
+ andRanges.add(childRanges);
+ }
+ }
+ return getIntersectionSortedRanges(andRanges);
+ case OR:
+ List<List<Interval>> orRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges == null) {
+ return null;
+ } else {
+ orRanges.add(childRanges);
+ }
+ }
+ return getUnionSortedRanges(orRanges);
+ case EQUALITY:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ long timeStamp = Long.parseLong(filterQueryTree.getValue().get(0));
+ return Collections.singletonList(new Interval(timeStamp, timeStamp));
+ }
+ return null;
+ case RANGE:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ return parseRange(filterQueryTree.getValue());
+ }
+ return null;
+ default:
+ return null;
+ }
+ }
+
+ private Interval convertRangeToMS(Interval range) {
+ long min = range._min == MIN_START_TIME ? MIN_START_TIME : _timeUnit.toMillis(range._min);
+ long max = range._max == MAX_END_TIME ? MAX_END_TIME : _timeUnit.toMillis(range._max);
+ return new Interval(min, max);
+ }
+
+ private List<Interval> getIntersectionSortedRanges(List<List<Interval>> ranges) {
+ // Requires input ranges are sorted, the return ranges will be sorted
+ return getIntersectionSortedRanges(ranges, 0, ranges.size());
+ }
+
+ private List<Interval> getIntersectionSortedRanges(List<List<Interval>> ranges, int start, int end) {
+ if (start == end) {
+ return null;
+ }
+
+ if (start + 1 == end) {
+ return ranges.get(start);
+ }
+
+ int mid = start + (end - start) / 2;
+ List<Interval> ranges1 = getIntersectionSortedRanges(ranges, start, mid);
+ List<Interval> ranges2 = getIntersectionSortedRanges(ranges, mid, end);
+ return getIntersectionOfTwoSortedRanges(ranges1, ranges2);
+ }
+
+ private List<Interval> getIntersectionOfTwoSortedRanges(List<Interval> ranges1, List<Interval> ranges2) { // sorted non-overlapping ranges
+ List<Interval> res = new ArrayList<>();
+ int i = 0, j = 0;
+ while (i < ranges1.size() && j < ranges2.size()) {
Review comment:
Cache these 2 sizes in local variables
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeSegmentPruner.java
##########
@@ -0,0 +1,340 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+ private final Map _segmentToTimeRangeMSCache;
+
+ public TimeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ _segmentToTimeRangeMSCache = new HashMap<String, Interval>();
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ synchronized public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ List<String> newSegments = new ArrayList<>();
+ for (String onlineSegment : onlineSegments) {
+ if (!_segmentToTimeRangeMSCache.containsKey(onlineSegment)) {
+ newSegments.add(onlineSegment);
+ }
+ }
+
+ List<String> newSegmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: newSegments) {
+ newSegmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(newSegmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ for (int i = 0; i < newSegments.size(); i++) {
+ String segment = newSegments.get(i);
+ Interval range = extractTimeRangeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ _segmentToTimeRangeMSCache.put(segment, range);
+ }
+ _segmentToTimeRangeMSCache.keySet().retainAll(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(_segmentToTimeRangeMSCache);
+ }
+
+ private Interval extractTimeRangeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ Interval defaultRange = new Interval(MIN_START_TIME, MAX_END_TIME);
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return defaultRange;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return defaultRange;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ return new Interval(timeUnit.toMillis(startTime), timeUnit.toMillis(endTime));
+ }
+
+ @Override
+ synchronized public void refreshSegment(String segment) {
+ List<ZNRecord> znRecords = _propertyStore.get(Collections.singletonList(_segmentZKMetadataPathPrefix + segment), null, AccessOption.PERSISTENT, true);
+ Interval range = extractTimeRangeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(0));
+ _segmentToTimeRangeMSCache.put(segment, range);
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(_segmentToTimeRangeMSCache);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ return segments;
+ }
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> ranges = getFilterTimeRange(filterQueryTree);
+ if (ranges == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (ranges.size() == 0) { // invalid query time range
+ return Collections.emptySet();
+ }
+
+ Set<String> selectedSegments = new HashSet<>();
+ for (Interval range : ranges) {
+ Interval rangeMS = convertRangeToMS(range);
+ for (Object segment : _timeRangeMSToSegmentSearchTree.searchAll(rangeMS)) {
+ if (segments.contains(segment)) {
+ selectedSegments.add((String) segment);
+ }
+ }
+ }
+ return selectedSegments;
+ }
+
+ private List<Interval> getFilterTimeRange(FilterQueryTree filterQueryTree) {
+ // return NUll if no time range info or cannot filter base on the info (e.g. 'SELECT * from myTable where time < 50 OR firstName = Jason')
+ // return an empty list if filtering range is specified but invalid (e.g. 'SELECT * from myTable where time < 50 AND time > 100')
+ switch (filterQueryTree.getOperator()) {
+ case AND:
+ List<List<Interval>> andRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges != null) {
+ andRanges.add(childRanges);
+ }
+ }
+ return getIntersectionSortedRanges(andRanges);
+ case OR:
+ List<List<Interval>> orRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges == null) {
+ return null;
+ } else {
+ orRanges.add(childRanges);
+ }
+ }
+ return getUnionSortedRanges(orRanges);
+ case EQUALITY:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ long timeStamp = Long.parseLong(filterQueryTree.getValue().get(0));
+ return Collections.singletonList(new Interval(timeStamp, timeStamp));
+ }
+ return null;
+ case RANGE:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ return parseRange(filterQueryTree.getValue());
+ }
+ return null;
+ default:
+ return null;
+ }
+ }
+
+ private Interval convertRangeToMS(Interval range) {
Review comment:
Always use timestamp (in millis) for interval for both SDF handling and clarity
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeSegmentPruner.java
##########
@@ -0,0 +1,340 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+ private final Map _segmentToTimeRangeMSCache;
+
+ public TimeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ _segmentToTimeRangeMSCache = new HashMap<String, Interval>();
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ synchronized public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ List<String> newSegments = new ArrayList<>();
+ for (String onlineSegment : onlineSegments) {
+ if (!_segmentToTimeRangeMSCache.containsKey(onlineSegment)) {
+ newSegments.add(onlineSegment);
+ }
+ }
+
+ List<String> newSegmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: newSegments) {
+ newSegmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(newSegmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ for (int i = 0; i < newSegments.size(); i++) {
+ String segment = newSegments.get(i);
+ Interval range = extractTimeRangeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ _segmentToTimeRangeMSCache.put(segment, range);
+ }
+ _segmentToTimeRangeMSCache.keySet().retainAll(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(_segmentToTimeRangeMSCache);
+ }
+
+ private Interval extractTimeRangeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ Interval defaultRange = new Interval(MIN_START_TIME, MAX_END_TIME);
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return defaultRange;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return defaultRange;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ return new Interval(timeUnit.toMillis(startTime), timeUnit.toMillis(endTime));
+ }
+
+ @Override
+ synchronized public void refreshSegment(String segment) {
+ List<ZNRecord> znRecords = _propertyStore.get(Collections.singletonList(_segmentZKMetadataPathPrefix + segment), null, AccessOption.PERSISTENT, true);
+ Interval range = extractTimeRangeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(0));
+ _segmentToTimeRangeMSCache.put(segment, range);
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(_segmentToTimeRangeMSCache);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ return segments;
+ }
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> ranges = getFilterTimeRange(filterQueryTree);
+ if (ranges == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (ranges.size() == 0) { // invalid query time range
+ return Collections.emptySet();
+ }
+
+ Set<String> selectedSegments = new HashSet<>();
+ for (Interval range : ranges) {
+ Interval rangeMS = convertRangeToMS(range);
+ for (Object segment : _timeRangeMSToSegmentSearchTree.searchAll(rangeMS)) {
+ if (segments.contains(segment)) {
+ selectedSegments.add((String) segment);
+ }
+ }
+ }
+ return selectedSegments;
+ }
+
+ private List<Interval> getFilterTimeRange(FilterQueryTree filterQueryTree) {
+ // return NUll if no time range info or cannot filter base on the info (e.g. 'SELECT * from myTable where time < 50 OR firstName = Jason')
+ // return an empty list if filtering range is specified but invalid (e.g. 'SELECT * from myTable where time < 50 AND time > 100')
+ switch (filterQueryTree.getOperator()) {
+ case AND:
+ List<List<Interval>> andRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges != null) {
+ andRanges.add(childRanges);
+ }
+ }
+ return getIntersectionSortedRanges(andRanges);
+ case OR:
+ List<List<Interval>> orRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges == null) {
+ return null;
+ } else {
+ orRanges.add(childRanges);
+ }
+ }
+ return getUnionSortedRanges(orRanges);
+ case EQUALITY:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ long timeStamp = Long.parseLong(filterQueryTree.getValue().get(0));
+ return Collections.singletonList(new Interval(timeStamp, timeStamp));
+ }
+ return null;
+ case RANGE:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ return parseRange(filterQueryTree.getValue());
+ }
+ return null;
+ default:
+ return null;
+ }
+ }
+
+ private Interval convertRangeToMS(Interval range) {
+ long min = range._min == MIN_START_TIME ? MIN_START_TIME : _timeUnit.toMillis(range._min);
+ long max = range._max == MAX_END_TIME ? MAX_END_TIME : _timeUnit.toMillis(range._max);
+ return new Interval(min, max);
+ }
+
+ private List<Interval> getIntersectionSortedRanges(List<List<Interval>> ranges) {
+ // Requires input ranges are sorted, the return ranges will be sorted
+ return getIntersectionSortedRanges(ranges, 0, ranges.size());
+ }
+
+ private List<Interval> getIntersectionSortedRanges(List<List<Interval>> ranges, int start, int end) {
+ if (start == end) {
+ return null;
Review comment:
Should never reach here (or `getIntersectionOfTwoSortedRanges()` will throw NPE). Same for union
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/intervalST/Interval.java
##########
@@ -0,0 +1,90 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner.intervalST;
Review comment:
Change the directory name to `interval` (no capital in directories)
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/intervalST/IntervalST.java
##########
@@ -0,0 +1,197 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner.intervalST;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * The {@code IntervalST} class represents read-only balanced binary interval search tree map (from intervals to values)
+ */
+public class IntervalST<Value> {
+
+ // List representation of bst with root at index 0. For node with index x, it's left child index is (2x+1), right child index is (2x+2)
+ //
+ // A node with index x is represented as following structure
+ // {
+ // Interval _interval = _intervals[x];
+ // List<Value> _values = _values[x];
+ // long _max = _max[x]; // max interval right end of subtree rooted at this node
+ // }
+ private final List<Interval> _intervals;
+ private final List<List<Value>> _values;
+ private final List<Long> _maxs;
+
+ public IntervalST(Map<Value, Interval> valueToIntervalMap) {
+ HashMap<Interval, List<Value>> intervalToValuesMap = new HashMap<>();
+ for (Map.Entry<Value, Interval> entry : valueToIntervalMap.entrySet()) {
+ List<Value> vals = intervalToValuesMap.putIfAbsent(entry.getValue(), new ArrayList<>());
+ intervalToValuesMap.get(entry.getValue()).add(entry.getKey());
+ }
+
+ List<Interval> sortedIntervals = new ArrayList<>(intervalToValuesMap.keySet());
+ Collections.sort(sortedIntervals);
+
+ _intervals = new ArrayList<>(sortedIntervals.size());
+ buildIntervalTree(sortedIntervals, _intervals);
+
+ _values = new ArrayList<>(_intervals.size());
+ for (Interval interval: _intervals) {
+ if (interval == null) {
+ _values.add(null);
+ } else {
+ _values.add(intervalToValuesMap.get(interval));
+ }
+ }
+
+ _maxs = new ArrayList<>(_intervals.size());
+ buildAuxiliaryInfo();
+ }
+
+ private void buildIntervalTree(List<Interval> sortedIntervals, List<Interval> res) {
+ // Build interval bst by bfs, the root for each subtree will be the median interval.
+ // A typical balanced tree
+ // [10, 20]
+ // / \
+ // [8, 15] [12, 20]
+ // / /
+ // [5, 10] [10, 30]
+ //
+ // will be represented as { [10, 20], [8, 15], [12, 20], [5, 10], null, [10, 30] }
+ if (sortedIntervals.size() == 0) {
Review comment:
```suggestion
if (sortedIntervals.size() <= 1) {
```
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/intervalST/IntervalST.java
##########
@@ -0,0 +1,187 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner.intervalST;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+
+// A read-only interval search tree based on AVL Tree
+public class IntervalST<Value> {
Review comment:
Suggest renaming it to `IntervalTree` (seems this is the official name of this data structure)
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/intervalST/IntervalST.java
##########
@@ -0,0 +1,197 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner.intervalST;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * The {@code IntervalST} class represents read-only balanced binary interval search tree map (from intervals to values)
+ */
+public class IntervalST<Value> {
+
+ // List representation of bst with root at index 0. For node with index x, it's left child index is (2x+1), right child index is (2x+2)
+ //
+ // A node with index x is represented as following structure
+ // {
+ // Interval _interval = _intervals[x];
+ // List<Value> _values = _values[x];
+ // long _max = _max[x]; // max interval right end of subtree rooted at this node
+ // }
+ private final List<Interval> _intervals;
+ private final List<List<Value>> _values;
+ private final List<Long> _maxs;
+
+ public IntervalST(Map<Value, Interval> valueToIntervalMap) {
+ HashMap<Interval, List<Value>> intervalToValuesMap = new HashMap<>();
+ for (Map.Entry<Value, Interval> entry : valueToIntervalMap.entrySet()) {
+ List<Value> vals = intervalToValuesMap.putIfAbsent(entry.getValue(), new ArrayList<>());
+ intervalToValuesMap.get(entry.getValue()).add(entry.getKey());
+ }
+
+ List<Interval> sortedIntervals = new ArrayList<>(intervalToValuesMap.keySet());
+ Collections.sort(sortedIntervals);
+
+ _intervals = new ArrayList<>(sortedIntervals.size());
+ buildIntervalTree(sortedIntervals, _intervals);
+
+ _values = new ArrayList<>(_intervals.size());
+ for (Interval interval: _intervals) {
+ if (interval == null) {
+ _values.add(null);
+ } else {
+ _values.add(intervalToValuesMap.get(interval));
+ }
+ }
+
+ _maxs = new ArrayList<>(_intervals.size());
+ buildAuxiliaryInfo();
+ }
+
+ private void buildIntervalTree(List<Interval> sortedIntervals, List<Interval> res) {
+ // Build interval bst by bfs, the root for each subtree will be the median interval.
+ // A typical balanced tree
+ // [10, 20]
+ // / \
+ // [8, 15] [12, 20]
+ // / /
+ // [5, 10] [10, 30]
+ //
+ // will be represented as { [10, 20], [8, 15], [12, 20], [5, 10], null, [10, 30] }
+ if (sortedIntervals.size() == 0) {
+ return;
+ }
+
+ LinkedList<Integer> startIndexQueue = new LinkedList<>();
+ LinkedList<Integer> endIndexQueue = new LinkedList<>();
+ startIndexQueue.addLast(0);
+ endIndexQueue.addLast(sortedIntervals.size());
+ int count = 0;
+ while (!startIndexQueue.isEmpty() && count < sortedIntervals.size()) {
+ int start = startIndexQueue.pollFirst();
+ int end = endIndexQueue.pollFirst();
+ if (start < end) {
+ int mid = start + (end - start) / 2;
+ res.add(sortedIntervals.get(mid));
+ count++;
+ startIndexQueue.addLast(start);
+ endIndexQueue.addLast(mid);
+ startIndexQueue.addLast(mid + 1);
+ endIndexQueue.addLast(end);
+ } else {
+ res.add(null);
+ }
+ }
+ }
+
+ private void buildAuxiliaryInfo() {
+ // Initialize and build max info for the interval tree by dfs
+ for (int i = 0; i < _intervals.size(); i++) {
+ _maxs.add(Long.MIN_VALUE);
+ }
+ buildAuxiliaryInfo(0);
+ }
+
+ private void buildAuxiliaryInfo(int nodeIndex) {
+ if (!hasNode(nodeIndex)) {
+ return;
+ }
+
+ int leftChildIndex = getLeftChildIndex(nodeIndex);
+ int rightChildIndex = getRightChildIndex(nodeIndex);
+
+ buildAuxiliaryInfo(leftChildIndex);
+ buildAuxiliaryInfo(rightChildIndex);
+
+ long max = _intervals.get(nodeIndex)._max;
+ max = Math.max(getMax(rightChildIndex), Math.max(max, getMax(leftChildIndex)));
+ _maxs.set(nodeIndex, max);
+ }
+
+ private int getLeftChildIndex(int nodeIndex) {
+ return nodeIndex * 2 + 1;
+ }
+
+ private int getRightChildIndex(int nodeIndex) {
+ return nodeIndex * 2 + 2;
+ }
+
+ private long getMax(int index) {
+ if (!hasNode(index)) {
+ return Long.MIN_VALUE;
+ }
+ return _maxs.get(index);
+ }
+
+ /**
+ * Find all values whose intervals intersect with the input interval.
+ *
+ * @param searchInterval search interval
+ * @return list of all qualified values.
+ */
+ public List<Value> searchAll(Interval searchInterval) {
+ List<Value> list = new ArrayList<>();
+ if (searchInterval == null) {
+ return list;
+ }
+ searchAll(0, searchInterval, list);
+ return list;
+ }
+
+ private boolean searchAll(int nodeIndex, Interval searchInterval, List<Value> list) {
Review comment:
I think we can simplify the algorithm as followings:
```
- Check root
- If (left.max >= interval.min) search left
- If (root.min <= interval.max) search right
```
Then we don't need to maintain these extra flags, and it is actually more efficient because if `left.max >= interval.min` and you cannot find intersections on left subtree, then `root.min` is always larger than `interval.max`
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/intervalST/Interval.java
##########
@@ -0,0 +1,90 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner.intervalST;
+
+import com.google.common.base.Preconditions;
+import javax.validation.constraints.NotNull;
+
+
+/**
+ * The {@code Interval} class represents an one-dimensional closed interval which contains both ends.
+ */
+public class Interval implements Comparable<Interval> {
+ public final long _min;
+ public final long _max;
+
+ public Interval(long min, long max) {
+ Preconditions.checkState(min <= max, "invalid interval [{}, {}]", min, max);
+ _min = min;
+ _max = max;
+ }
+
+ public boolean intersects(@NotNull Interval that) {
+ return _max >= that._min && that._max >= _min;
+ }
+
+ @Override
+ public int compareTo(Interval that) {
+ Preconditions.checkNotNull(that, "Compare to invalid interval: null");
+ if (_min < that._min) {
+ return -1;
+ } else if (_min > that._min) {
+ return 1;
+ } else if (_max < that._max) {
+ return -1;
+ } else if (_max > that._max) {
+ return 1;
+ }
+ else return 0;
+ }
+
+ @Override
+ public int hashCode() {
+ return (int)(_min * 17 + _max);
+ }
+
+ @Override
+ public boolean equals(Object that) {
+ if (that instanceof Interval && that != null
+ && _min == ((Interval)that)._min && _max == ((Interval)that)._max) {
+ return true;
+ }
+ return false;
+ }
+
+ public static Interval getIntersection(@NotNull Interval a, @NotNull Interval b) {
+ if (!a.intersects(b)) {
Review comment:
Preconditions might be better? We don't want it to be null as the caller cannot handle the null values
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeSegmentPruner.java
##########
@@ -0,0 +1,340 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+ private final Map _segmentToTimeRangeMSCache;
+
+ public TimeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ _segmentToTimeRangeMSCache = new HashMap<String, Interval>();
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ synchronized public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ List<String> newSegments = new ArrayList<>();
+ for (String onlineSegment : onlineSegments) {
+ if (!_segmentToTimeRangeMSCache.containsKey(onlineSegment)) {
+ newSegments.add(onlineSegment);
+ }
+ }
+
+ List<String> newSegmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: newSegments) {
+ newSegmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(newSegmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ for (int i = 0; i < newSegments.size(); i++) {
+ String segment = newSegments.get(i);
+ Interval range = extractTimeRangeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ _segmentToTimeRangeMSCache.put(segment, range);
+ }
+ _segmentToTimeRangeMSCache.keySet().retainAll(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(_segmentToTimeRangeMSCache);
+ }
+
+ private Interval extractTimeRangeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ Interval defaultRange = new Interval(MIN_START_TIME, MAX_END_TIME);
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return defaultRange;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return defaultRange;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ return new Interval(timeUnit.toMillis(startTime), timeUnit.toMillis(endTime));
+ }
+
+ @Override
+ synchronized public void refreshSegment(String segment) {
+ List<ZNRecord> znRecords = _propertyStore.get(Collections.singletonList(_segmentZKMetadataPathPrefix + segment), null, AccessOption.PERSISTENT, true);
+ Interval range = extractTimeRangeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(0));
+ _segmentToTimeRangeMSCache.put(segment, range);
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(_segmentToTimeRangeMSCache);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
Review comment:
Also I think it can never be null here
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/intervalST/IntervalST.java
##########
@@ -0,0 +1,197 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner.intervalST;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * The {@code IntervalST} class represents read-only balanced binary interval search tree map (from intervals to values)
+ */
+public class IntervalST<Value> {
+
+ // List representation of bst with root at index 0. For node with index x, it's left child index is (2x+1), right child index is (2x+2)
+ //
+ // A node with index x is represented as following structure
+ // {
+ // Interval _interval = _intervals[x];
+ // List<Value> _values = _values[x];
+ // long _max = _max[x]; // max interval right end of subtree rooted at this node
+ // }
+ private final List<Interval> _intervals;
+ private final List<List<Value>> _values;
+ private final List<Long> _maxs;
+
+ public IntervalST(Map<Value, Interval> valueToIntervalMap) {
+ HashMap<Interval, List<Value>> intervalToValuesMap = new HashMap<>();
+ for (Map.Entry<Value, Interval> entry : valueToIntervalMap.entrySet()) {
+ List<Value> vals = intervalToValuesMap.putIfAbsent(entry.getValue(), new ArrayList<>());
+ intervalToValuesMap.get(entry.getValue()).add(entry.getKey());
+ }
+
+ List<Interval> sortedIntervals = new ArrayList<>(intervalToValuesMap.keySet());
+ Collections.sort(sortedIntervals);
+
+ _intervals = new ArrayList<>(sortedIntervals.size());
+ buildIntervalTree(sortedIntervals, _intervals);
+
+ _values = new ArrayList<>(_intervals.size());
+ for (Interval interval: _intervals) {
+ if (interval == null) {
+ _values.add(null);
+ } else {
+ _values.add(intervalToValuesMap.get(interval));
+ }
+ }
+
+ _maxs = new ArrayList<>(_intervals.size());
+ buildAuxiliaryInfo();
+ }
+
+ private void buildIntervalTree(List<Interval> sortedIntervals, List<Interval> res) {
+ // Build interval bst by bfs, the root for each subtree will be the median interval.
+ // A typical balanced tree
+ // [10, 20]
+ // / \
+ // [8, 15] [12, 20]
+ // / /
+ // [5, 10] [10, 30]
+ //
+ // will be represented as { [10, 20], [8, 15], [12, 20], [5, 10], null, [10, 30] }
+ if (sortedIntervals.size() == 0) {
+ return;
+ }
+
+ LinkedList<Integer> startIndexQueue = new LinkedList<>();
+ LinkedList<Integer> endIndexQueue = new LinkedList<>();
+ startIndexQueue.addLast(0);
+ endIndexQueue.addLast(sortedIntervals.size());
+ int count = 0;
+ while (!startIndexQueue.isEmpty() && count < sortedIntervals.size()) {
Review comment:
`!startIndexQueue.isEmpty()` is redundant
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/intervalST/Interval.java
##########
@@ -0,0 +1,90 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner.intervalST;
+
+import com.google.common.base.Preconditions;
+import javax.validation.constraints.NotNull;
Review comment:
Don't use NotNull annotation. We only use Nullable, variables without annotation are treated as non-null
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeSegmentPruner.java
##########
@@ -0,0 +1,340 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+ private final Map _segmentToTimeRangeMSCache;
+
+ public TimeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ _segmentToTimeRangeMSCache = new HashMap<String, Interval>();
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ synchronized public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ List<String> newSegments = new ArrayList<>();
+ for (String onlineSegment : onlineSegments) {
+ if (!_segmentToTimeRangeMSCache.containsKey(onlineSegment)) {
+ newSegments.add(onlineSegment);
+ }
+ }
+
+ List<String> newSegmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: newSegments) {
+ newSegmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(newSegmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ for (int i = 0; i < newSegments.size(); i++) {
+ String segment = newSegments.get(i);
+ Interval range = extractTimeRangeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ _segmentToTimeRangeMSCache.put(segment, range);
+ }
+ _segmentToTimeRangeMSCache.keySet().retainAll(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(_segmentToTimeRangeMSCache);
+ }
+
+ private Interval extractTimeRangeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ Interval defaultRange = new Interval(MIN_START_TIME, MAX_END_TIME);
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return defaultRange;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return defaultRange;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ return new Interval(timeUnit.toMillis(startTime), timeUnit.toMillis(endTime));
+ }
+
+ @Override
+ synchronized public void refreshSegment(String segment) {
+ List<ZNRecord> znRecords = _propertyStore.get(Collections.singletonList(_segmentZKMetadataPathPrefix + segment), null, AccessOption.PERSISTENT, true);
+ Interval range = extractTimeRangeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(0));
+ _segmentToTimeRangeMSCache.put(segment, range);
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(_segmentToTimeRangeMSCache);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ return segments;
+ }
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> ranges = getFilterTimeRange(filterQueryTree);
+ if (ranges == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (ranges.size() == 0) { // invalid query time range
+ return Collections.emptySet();
+ }
+
+ Set<String> selectedSegments = new HashSet<>();
+ for (Interval range : ranges) {
+ Interval rangeMS = convertRangeToMS(range);
+ for (Object segment : _timeRangeMSToSegmentSearchTree.searchAll(rangeMS)) {
+ if (segments.contains(segment)) {
+ selectedSegments.add((String) segment);
+ }
+ }
+ }
+ return selectedSegments;
+ }
+
+ private List<Interval> getFilterTimeRange(FilterQueryTree filterQueryTree) {
+ // return NUll if no time range info or cannot filter base on the info (e.g. 'SELECT * from myTable where time < 50 OR firstName = Jason')
+ // return an empty list if filtering range is specified but invalid (e.g. 'SELECT * from myTable where time < 50 AND time > 100')
+ switch (filterQueryTree.getOperator()) {
+ case AND:
+ List<List<Interval>> andRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges != null) {
+ andRanges.add(childRanges);
+ }
+ }
+ return getIntersectionSortedRanges(andRanges);
+ case OR:
+ List<List<Interval>> orRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges == null) {
+ return null;
+ } else {
+ orRanges.add(childRanges);
+ }
+ }
+ return getUnionSortedRanges(orRanges);
+ case EQUALITY:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ long timeStamp = Long.parseLong(filterQueryTree.getValue().get(0));
+ return Collections.singletonList(new Interval(timeStamp, timeStamp));
+ }
+ return null;
+ case RANGE:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ return parseRange(filterQueryTree.getValue());
+ }
+ return null;
+ default:
+ return null;
+ }
+ }
+
+ private Interval convertRangeToMS(Interval range) {
+ long min = range._min == MIN_START_TIME ? MIN_START_TIME : _timeUnit.toMillis(range._min);
+ long max = range._max == MAX_END_TIME ? MAX_END_TIME : _timeUnit.toMillis(range._max);
+ return new Interval(min, max);
+ }
+
+ private List<Interval> getIntersectionSortedRanges(List<List<Interval>> ranges) {
+ // Requires input ranges are sorted, the return ranges will be sorted
+ return getIntersectionSortedRanges(ranges, 0, ranges.size());
+ }
+
+ private List<Interval> getIntersectionSortedRanges(List<List<Interval>> ranges, int start, int end) {
+ if (start == end) {
+ return null;
+ }
+
+ if (start + 1 == end) {
+ return ranges.get(start);
+ }
+
+ int mid = start + (end - start) / 2;
+ List<Interval> ranges1 = getIntersectionSortedRanges(ranges, start, mid);
+ List<Interval> ranges2 = getIntersectionSortedRanges(ranges, mid, end);
+ return getIntersectionOfTwoSortedRanges(ranges1, ranges2);
+ }
+
+ private List<Interval> getIntersectionOfTwoSortedRanges(List<Interval> ranges1, List<Interval> ranges2) { // sorted non-overlapping ranges
+ List<Interval> res = new ArrayList<>();
+ int i = 0, j = 0;
+ while (i < ranges1.size() && j < ranges2.size()) {
+ Interval range1 = ranges1.get(i);
+ Interval range2 = ranges2.get(j);
+ if (range1.intersects(range2)) {
+ res.add(Interval.getIntersection(range1, range2));
+ }
+ if (range1._max < range2._max) {
+ i++;
+ } else {
+ j++;
+ }
+ }
+ return res;
+ }
+
+ private List<Interval> getUnionSortedRanges(List<List<Interval>> ranges) {
+ return getUnionSortedRanges(ranges, 0, ranges.size());
+ }
+
+ private List<Interval> getUnionSortedRanges(List<List<Interval>> ranges, int start, int end) {
+ if (start == end) {
+ return null;
+ }
+
+ if (start + 1 == end) {
+ return ranges.get(start);
+ }
+
+ int mid = start + (end - start) / 2;
+ List<Interval> ranges1 = getUnionSortedRanges(ranges, start, mid);
+ List<Interval> ranges2 = getUnionSortedRanges(ranges, mid, end);
+ return getUnionOfTwoSortedRanges(ranges1, ranges2);
+ }
+
+ private List<Interval> getUnionOfTwoSortedRanges(List<Interval> ranges1, List<Interval> ranges2) { // sorted non-overlapping ranges
+ List<Interval> res = new ArrayList<>();
+ int i = 0, j = 0;
+
+ while (i < ranges1.size() || j < ranges2.size()) {
+ if (j == ranges2.size() || i < ranges1.size() && ranges1.get(i).compareTo(ranges2.get(j)) <= 0) {
+ if (res.size() == 0 || !ranges1.get(i).intersects(res.get(res.size()-1))) {
Review comment:
Reformat this part
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/intervalST/IntervalST.java
##########
@@ -0,0 +1,197 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner.intervalST;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * The {@code IntervalST} class represents read-only balanced binary interval search tree map (from intervals to values)
+ */
+public class IntervalST<Value> {
+
+ // List representation of bst with root at index 0. For node with index x, it's left child index is (2x+1), right child index is (2x+2)
+ //
+ // A node with index x is represented as following structure
+ // {
+ // Interval _interval = _intervals[x];
+ // List<Value> _values = _values[x];
+ // long _max = _max[x]; // max interval right end of subtree rooted at this node
+ // }
+ private final List<Interval> _intervals;
+ private final List<List<Value>> _values;
+ private final List<Long> _maxs;
+
+ public IntervalST(Map<Value, Interval> valueToIntervalMap) {
+ HashMap<Interval, List<Value>> intervalToValuesMap = new HashMap<>();
+ for (Map.Entry<Value, Interval> entry : valueToIntervalMap.entrySet()) {
+ List<Value> vals = intervalToValuesMap.putIfAbsent(entry.getValue(), new ArrayList<>());
+ intervalToValuesMap.get(entry.getValue()).add(entry.getKey());
+ }
+
+ List<Interval> sortedIntervals = new ArrayList<>(intervalToValuesMap.keySet());
+ Collections.sort(sortedIntervals);
+
+ _intervals = new ArrayList<>(sortedIntervals.size());
+ buildIntervalTree(sortedIntervals, _intervals);
+
+ _values = new ArrayList<>(_intervals.size());
+ for (Interval interval: _intervals) {
+ if (interval == null) {
+ _values.add(null);
+ } else {
+ _values.add(intervalToValuesMap.get(interval));
+ }
+ }
+
+ _maxs = new ArrayList<>(_intervals.size());
+ buildAuxiliaryInfo();
+ }
+
+ private void buildIntervalTree(List<Interval> sortedIntervals, List<Interval> res) {
+ // Build interval bst by bfs, the root for each subtree will be the median interval.
+ // A typical balanced tree
+ // [10, 20]
+ // / \
+ // [8, 15] [12, 20]
+ // / /
+ // [5, 10] [10, 30]
+ //
+ // will be represented as { [10, 20], [8, 15], [12, 20], [5, 10], null, [10, 30] }
+ if (sortedIntervals.size() == 0) {
+ return;
+ }
+
+ LinkedList<Integer> startIndexQueue = new LinkedList<>();
Review comment:
Keep one list of `IntPair`
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/intervalST/IntervalST.java
##########
@@ -0,0 +1,197 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner.intervalST;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * The {@code IntervalST} class represents read-only balanced binary interval search tree map (from intervals to values)
+ */
+public class IntervalST<Value> {
+
+ // List representation of bst with root at index 0. For node with index x, it's left child index is (2x+1), right child index is (2x+2)
+ //
+ // A node with index x is represented as following structure
+ // {
+ // Interval _interval = _intervals[x];
+ // List<Value> _values = _values[x];
+ // long _max = _max[x]; // max interval right end of subtree rooted at this node
+ // }
+ private final List<Interval> _intervals;
Review comment:
Have a separate class for these info and keep one list
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/intervalST/Interval.java
##########
@@ -0,0 +1,90 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner.intervalST;
+
+import com.google.common.base.Preconditions;
+import javax.validation.constraints.NotNull;
+
+
+/**
+ * The {@code Interval} class represents an one-dimensional closed interval which contains both ends.
+ */
+public class Interval implements Comparable<Interval> {
+ public final long _min;
+ public final long _max;
+
+ public Interval(long min, long max) {
+ Preconditions.checkState(min <= max, "invalid interval [{}, {}]", min, max);
+ _min = min;
+ _max = max;
+ }
+
+ public boolean intersects(@NotNull Interval that) {
+ return _max >= that._min && that._max >= _min;
+ }
+
+ @Override
+ public int compareTo(Interval that) {
+ Preconditions.checkNotNull(that, "Compare to invalid interval: null");
+ if (_min < that._min) {
+ return -1;
+ } else if (_min > that._min) {
+ return 1;
+ } else if (_max < that._max) {
+ return -1;
+ } else if (_max > that._max) {
+ return 1;
+ }
+ else return 0;
+ }
+
+ @Override
+ public int hashCode() {
Review comment:
Yeah, please use the one auto-generated
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeSegmentPruner.java
##########
@@ -0,0 +1,340 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+ private final Map _segmentToTimeRangeMSCache;
+
+ public TimeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ _segmentToTimeRangeMSCache = new HashMap<String, Interval>();
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ synchronized public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ List<String> newSegments = new ArrayList<>();
+ for (String onlineSegment : onlineSegments) {
+ if (!_segmentToTimeRangeMSCache.containsKey(onlineSegment)) {
+ newSegments.add(onlineSegment);
+ }
+ }
+
+ List<String> newSegmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: newSegments) {
+ newSegmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(newSegmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ for (int i = 0; i < newSegments.size(); i++) {
+ String segment = newSegments.get(i);
+ Interval range = extractTimeRangeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ _segmentToTimeRangeMSCache.put(segment, range);
+ }
+ _segmentToTimeRangeMSCache.keySet().retainAll(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(_segmentToTimeRangeMSCache);
+ }
+
+ private Interval extractTimeRangeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ Interval defaultRange = new Interval(MIN_START_TIME, MAX_END_TIME);
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return defaultRange;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return defaultRange;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ return new Interval(timeUnit.toMillis(startTime), timeUnit.toMillis(endTime));
+ }
+
+ @Override
+ synchronized public void refreshSegment(String segment) {
+ List<ZNRecord> znRecords = _propertyStore.get(Collections.singletonList(_segmentZKMetadataPathPrefix + segment), null, AccessOption.PERSISTENT, true);
+ Interval range = extractTimeRangeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(0));
+ _segmentToTimeRangeMSCache.put(segment, range);
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(_segmentToTimeRangeMSCache);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ return segments;
+ }
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> ranges = getFilterTimeRange(filterQueryTree);
+ if (ranges == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (ranges.size() == 0) { // invalid query time range
+ return Collections.emptySet();
+ }
+
+ Set<String> selectedSegments = new HashSet<>();
+ for (Interval range : ranges) {
+ Interval rangeMS = convertRangeToMS(range);
+ for (Object segment : _timeRangeMSToSegmentSearchTree.searchAll(rangeMS)) {
+ if (segments.contains(segment)) {
+ selectedSegments.add((String) segment);
+ }
+ }
+ }
+ return selectedSegments;
+ }
+
+ private List<Interval> getFilterTimeRange(FilterQueryTree filterQueryTree) {
+ // return NUll if no time range info or cannot filter base on the info (e.g. 'SELECT * from myTable where time < 50 OR firstName = Jason')
+ // return an empty list if filtering range is specified but invalid (e.g. 'SELECT * from myTable where time < 50 AND time > 100')
+ switch (filterQueryTree.getOperator()) {
+ case AND:
+ List<List<Interval>> andRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges != null) {
+ andRanges.add(childRanges);
+ }
+ }
+ return getIntersectionSortedRanges(andRanges);
+ case OR:
+ List<List<Interval>> orRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges == null) {
+ return null;
+ } else {
+ orRanges.add(childRanges);
+ }
+ }
+ return getUnionSortedRanges(orRanges);
+ case EQUALITY:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ long timeStamp = Long.parseLong(filterQueryTree.getValue().get(0));
+ return Collections.singletonList(new Interval(timeStamp, timeStamp));
+ }
+ return null;
+ case RANGE:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ return parseRange(filterQueryTree.getValue());
+ }
+ return null;
+ default:
+ return null;
+ }
+ }
+
+ private Interval convertRangeToMS(Interval range) {
+ long min = range._min == MIN_START_TIME ? MIN_START_TIME : _timeUnit.toMillis(range._min);
+ long max = range._max == MAX_END_TIME ? MAX_END_TIME : _timeUnit.toMillis(range._max);
+ return new Interval(min, max);
+ }
+
+ private List<Interval> getIntersectionSortedRanges(List<List<Interval>> ranges) {
+ // Requires input ranges are sorted, the return ranges will be sorted
+ return getIntersectionSortedRanges(ranges, 0, ranges.size());
+ }
+
+ private List<Interval> getIntersectionSortedRanges(List<List<Interval>> ranges, int start, int end) {
+ if (start == end) {
+ return null;
+ }
+
+ if (start + 1 == end) {
+ return ranges.get(start);
+ }
+
+ int mid = start + (end - start) / 2;
+ List<Interval> ranges1 = getIntersectionSortedRanges(ranges, start, mid);
+ List<Interval> ranges2 = getIntersectionSortedRanges(ranges, mid, end);
+ return getIntersectionOfTwoSortedRanges(ranges1, ranges2);
+ }
+
+ private List<Interval> getIntersectionOfTwoSortedRanges(List<Interval> ranges1, List<Interval> ranges2) { // sorted non-overlapping ranges
+ List<Interval> res = new ArrayList<>();
+ int i = 0, j = 0;
+ while (i < ranges1.size() && j < ranges2.size()) {
+ Interval range1 = ranges1.get(i);
+ Interval range2 = ranges2.get(j);
+ if (range1.intersects(range2)) {
+ res.add(Interval.getIntersection(range1, range2));
+ }
+ if (range1._max < range2._max) {
+ i++;
+ } else {
+ j++;
+ }
+ }
+ return res;
+ }
+
+ private List<Interval> getUnionSortedRanges(List<List<Interval>> ranges) {
+ return getUnionSortedRanges(ranges, 0, ranges.size());
+ }
+
+ private List<Interval> getUnionSortedRanges(List<List<Interval>> ranges, int start, int end) {
+ if (start == end) {
+ return null;
+ }
+
+ if (start + 1 == end) {
+ return ranges.get(start);
+ }
+
+ int mid = start + (end - start) / 2;
+ List<Interval> ranges1 = getUnionSortedRanges(ranges, start, mid);
+ List<Interval> ranges2 = getUnionSortedRanges(ranges, mid, end);
+ return getUnionOfTwoSortedRanges(ranges1, ranges2);
+ }
+
+ private List<Interval> getUnionOfTwoSortedRanges(List<Interval> ranges1, List<Interval> ranges2) { // sorted non-overlapping ranges
+ List<Interval> res = new ArrayList<>();
+ int i = 0, j = 0;
+
+ while (i < ranges1.size() || j < ranges2.size()) {
Review comment:
Put some comments explaining the algorithm
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] codecov-io edited a comment on pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
codecov-io edited a comment on pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#issuecomment-728650157
# [Codecov](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=h1) Report
> Merging [#6259](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=desc) (f20e4ed) into [master](https://codecov.io/gh/apache/incubator-pinot/commit/1beaab59b73f26c4e35f3b9bc856b03806cddf5a?el=desc) (1beaab5) will **increase** coverage by `7.67%`.
> The diff coverage is `73.09%`.
[](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=tree)
```diff
@@ Coverage Diff @@
## master #6259 +/- ##
==========================================
+ Coverage 66.44% 74.11% +7.67%
==========================================
Files 1075 1255 +180
Lines 54773 61537 +6764
Branches 8168 8927 +759
==========================================
+ Hits 36396 45611 +9215
+ Misses 15700 12994 -2706
- Partials 2677 2932 +255
```
| Flag | Coverage Δ | |
|---|---|---|
| integration | `45.62% <38.65%> (?)` | |
| unittests | `65.35% <56.74%> (?)` | |
Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags#carryforward-flags-in-the-pull-request-comment) to find out more.
| [Impacted Files](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [...ot/broker/broker/AllowAllAccessControlFactory.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvYnJva2VyL0FsbG93QWxsQWNjZXNzQ29udHJvbEZhY3RvcnkuamF2YQ==) | `100.00% <ø> (ø)` | |
| [.../helix/BrokerUserDefinedMessageHandlerFactory.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvYnJva2VyL2hlbGl4L0Jyb2tlclVzZXJEZWZpbmVkTWVzc2FnZUhhbmRsZXJGYWN0b3J5LmphdmE=) | `52.83% <0.00%> (-13.84%)` | :arrow_down: |
| [...ker/routing/instanceselector/InstanceSelector.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvcm91dGluZy9pbnN0YW5jZXNlbGVjdG9yL0luc3RhbmNlU2VsZWN0b3IuamF2YQ==) | `100.00% <ø> (ø)` | |
| [.../main/java/org/apache/pinot/client/Connection.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY2xpZW50cy9waW5vdC1qYXZhLWNsaWVudC9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3QvY2xpZW50L0Nvbm5lY3Rpb24uamF2YQ==) | `44.44% <0.00%> (-4.40%)` | :arrow_down: |
| [...not/common/assignment/InstancePartitionsUtils.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9jb21tb24vYXNzaWdubWVudC9JbnN0YW5jZVBhcnRpdGlvbnNVdGlscy5qYXZh) | `78.57% <ø> (+5.40%)` | :arrow_up: |
| [.../apache/pinot/common/exception/QueryException.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9jb21tb24vZXhjZXB0aW9uL1F1ZXJ5RXhjZXB0aW9uLmphdmE=) | `90.27% <ø> (+5.55%)` | :arrow_up: |
| [...pinot/common/function/AggregationFunctionType.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9jb21tb24vZnVuY3Rpb24vQWdncmVnYXRpb25GdW5jdGlvblR5cGUuamF2YQ==) | `98.27% <ø> (-1.73%)` | :arrow_down: |
| [.../pinot/common/function/DateTimePatternHandler.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9jb21tb24vZnVuY3Rpb24vRGF0ZVRpbWVQYXR0ZXJuSGFuZGxlci5qYXZh) | `83.33% <ø> (ø)` | |
| [...ot/common/function/FunctionDefinitionRegistry.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9jb21tb24vZnVuY3Rpb24vRnVuY3Rpb25EZWZpbml0aW9uUmVnaXN0cnkuamF2YQ==) | `88.88% <ø> (+44.44%)` | :arrow_up: |
| [...org/apache/pinot/common/function/FunctionInfo.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9jb21tb24vZnVuY3Rpb24vRnVuY3Rpb25JbmZvLmphdmE=) | `100.00% <ø> (ø)` | |
| ... and [1037 more](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree-more) | |
------
[Continue to review full report at Codecov](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=footer). Last update [0565f86...ff8f2fd](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] jtao15 commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
jtao15 commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r522552946
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentselector/RealtimeSegmentSelector.java
##########
@@ -52,8 +53,8 @@
public static final String FORCE_HLC = "FORCE_HLC";
private final AtomicLong _requestId = new AtomicLong();
- private volatile List<List<String>> _hlcSegments;
Review comment:
Yes, I made this change to avoid making a HashSet of input segments in `prune()`. Is there any considerations to keep this as list? The time range pruner keeps a search treemap from time ranges to segments. Pruning is done by search intersected segments based on query and check if they are in input segments of `prune()`. Ideally the input segments are in a HashSet, so the checking process would be efficient.
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] codecov-io edited a comment on pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
codecov-io edited a comment on pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#issuecomment-728650157
# [Codecov](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=h1) Report
> Merging [#6259](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=desc) (787ee45) into [master](https://codecov.io/gh/apache/incubator-pinot/commit/1beaab59b73f26c4e35f3b9bc856b03806cddf5a?el=desc) (1beaab5) will **decrease** coverage by `1.15%`.
> The diff coverage is `56.70%`.
[](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=tree)
```diff
@@ Coverage Diff @@
## master #6259 +/- ##
==========================================
- Coverage 66.44% 65.29% -1.16%
==========================================
Files 1075 1255 +180
Lines 54773 61506 +6733
Branches 8168 8920 +752
==========================================
+ Hits 36396 40161 +3765
- Misses 15700 18486 +2786
- Partials 2677 2859 +182
```
| Flag | Coverage Δ | |
|---|---|---|
| unittests | `65.29% <56.70%> (?)` | |
Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags#carryforward-flags-in-the-pull-request-comment) to find out more.
| [Impacted Files](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [...e/pinot/broker/api/resources/PinotBrokerDebug.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvYXBpL3Jlc291cmNlcy9QaW5vdEJyb2tlckRlYnVnLmphdmE=) | `0.00% <0.00%> (-79.32%)` | :arrow_down: |
| [...ot/broker/broker/AllowAllAccessControlFactory.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvYnJva2VyL0FsbG93QWxsQWNjZXNzQ29udHJvbEZhY3RvcnkuamF2YQ==) | `71.42% <ø> (-28.58%)` | :arrow_down: |
| [.../helix/BrokerUserDefinedMessageHandlerFactory.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvYnJva2VyL2hlbGl4L0Jyb2tlclVzZXJEZWZpbmVkTWVzc2FnZUhhbmRsZXJGYWN0b3J5LmphdmE=) | `33.96% <0.00%> (-32.71%)` | :arrow_down: |
| [...ker/routing/instanceselector/InstanceSelector.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtYnJva2VyL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9icm9rZXIvcm91dGluZy9pbnN0YW5jZXNlbGVjdG9yL0luc3RhbmNlU2VsZWN0b3IuamF2YQ==) | `100.00% <ø> (ø)` | |
| [...ava/org/apache/pinot/client/AbstractResultSet.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY2xpZW50cy9waW5vdC1qYXZhLWNsaWVudC9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3QvY2xpZW50L0Fic3RyYWN0UmVzdWx0U2V0LmphdmE=) | `66.66% <0.00%> (+9.52%)` | :arrow_up: |
| [.../main/java/org/apache/pinot/client/Connection.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY2xpZW50cy9waW5vdC1qYXZhLWNsaWVudC9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3QvY2xpZW50L0Nvbm5lY3Rpb24uamF2YQ==) | `35.55% <0.00%> (-13.29%)` | :arrow_down: |
| [...inot/client/JsonAsyncHttpPinotClientTransport.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY2xpZW50cy9waW5vdC1qYXZhLWNsaWVudC9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3QvY2xpZW50L0pzb25Bc3luY0h0dHBQaW5vdENsaWVudFRyYW5zcG9ydC5qYXZh) | `10.90% <0.00%> (-51.10%)` | :arrow_down: |
| [...not/common/assignment/InstancePartitionsUtils.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9jb21tb24vYXNzaWdubWVudC9JbnN0YW5jZVBhcnRpdGlvbnNVdGlscy5qYXZh) | `73.80% <ø> (+0.63%)` | :arrow_up: |
| [.../apache/pinot/common/exception/QueryException.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9jb21tb24vZXhjZXB0aW9uL1F1ZXJ5RXhjZXB0aW9uLmphdmE=) | `90.27% <ø> (+5.55%)` | :arrow_up: |
| [...pinot/common/function/AggregationFunctionType.java](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree#diff-cGlub3QtY29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS9waW5vdC9jb21tb24vZnVuY3Rpb24vQWdncmVnYXRpb25GdW5jdGlvblR5cGUuamF2YQ==) | `98.27% <ø> (-1.73%)` | :arrow_down: |
| ... and [1099 more](https://codecov.io/gh/apache/incubator-pinot/pull/6259/diff?src=pr&el=tree-more) | |
------
[Continue to review full report at Codecov](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=footer). Last update [318c107...787ee45](https://codecov.io/gh/apache/incubator-pinot/pull/6259?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] jtao15 commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
jtao15 commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r529759262
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/intervalST/IntervalST.java
##########
@@ -0,0 +1,197 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner.intervalST;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * The {@code IntervalST} class represents read-only balanced binary interval search tree map (from intervals to values)
+ */
+public class IntervalST<Value> {
+
+ // List representation of bst with root at index 0. For node with index x, it's left child index is (2x+1), right child index is (2x+2)
+ //
+ // A node with index x is represented as following structure
+ // {
+ // Interval _interval = _intervals[x];
+ // List<Value> _values = _values[x];
+ // long _max = _max[x]; // max interval right end of subtree rooted at this node
+ // }
+ private final List<Interval> _intervals;
+ private final List<List<Value>> _values;
+ private final List<Long> _maxs;
+
+ public IntervalST(Map<Value, Interval> valueToIntervalMap) {
+ HashMap<Interval, List<Value>> intervalToValuesMap = new HashMap<>();
+ for (Map.Entry<Value, Interval> entry : valueToIntervalMap.entrySet()) {
+ List<Value> vals = intervalToValuesMap.putIfAbsent(entry.getValue(), new ArrayList<>());
+ intervalToValuesMap.get(entry.getValue()).add(entry.getKey());
+ }
+
+ List<Interval> sortedIntervals = new ArrayList<>(intervalToValuesMap.keySet());
+ Collections.sort(sortedIntervals);
+
+ _intervals = new ArrayList<>(sortedIntervals.size());
+ buildIntervalTree(sortedIntervals, _intervals);
+
+ _values = new ArrayList<>(_intervals.size());
+ for (Interval interval: _intervals) {
+ if (interval == null) {
+ _values.add(null);
+ } else {
+ _values.add(intervalToValuesMap.get(interval));
+ }
+ }
+
+ _maxs = new ArrayList<>(_intervals.size());
+ buildAuxiliaryInfo();
+ }
+
+ private void buildIntervalTree(List<Interval> sortedIntervals, List<Interval> res) {
+ // Build interval bst by bfs, the root for each subtree will be the median interval.
+ // A typical balanced tree
+ // [10, 20]
+ // / \
+ // [8, 15] [12, 20]
+ // / /
+ // [5, 10] [10, 30]
+ //
+ // will be represented as { [10, 20], [8, 15], [12, 20], [5, 10], null, [10, 30] }
+ if (sortedIntervals.size() == 0) {
+ return;
+ }
+
+ LinkedList<Integer> startIndexQueue = new LinkedList<>();
+ LinkedList<Integer> endIndexQueue = new LinkedList<>();
+ startIndexQueue.addLast(0);
+ endIndexQueue.addLast(sortedIntervals.size());
+ int count = 0;
+ while (!startIndexQueue.isEmpty() && count < sortedIntervals.size()) {
+ int start = startIndexQueue.pollFirst();
+ int end = endIndexQueue.pollFirst();
+ if (start < end) {
+ int mid = start + (end - start) / 2;
+ res.add(sortedIntervals.get(mid));
+ count++;
+ startIndexQueue.addLast(start);
+ endIndexQueue.addLast(mid);
+ startIndexQueue.addLast(mid + 1);
+ endIndexQueue.addLast(end);
+ } else {
+ res.add(null);
+ }
+ }
+ }
+
+ private void buildAuxiliaryInfo() {
+ // Initialize and build max info for the interval tree by dfs
+ for (int i = 0; i < _intervals.size(); i++) {
+ _maxs.add(Long.MIN_VALUE);
+ }
+ buildAuxiliaryInfo(0);
+ }
+
+ private void buildAuxiliaryInfo(int nodeIndex) {
+ if (!hasNode(nodeIndex)) {
+ return;
+ }
+
+ int leftChildIndex = getLeftChildIndex(nodeIndex);
+ int rightChildIndex = getRightChildIndex(nodeIndex);
+
+ buildAuxiliaryInfo(leftChildIndex);
+ buildAuxiliaryInfo(rightChildIndex);
+
+ long max = _intervals.get(nodeIndex)._max;
+ max = Math.max(getMax(rightChildIndex), Math.max(max, getMax(leftChildIndex)));
+ _maxs.set(nodeIndex, max);
+ }
+
+ private int getLeftChildIndex(int nodeIndex) {
+ return nodeIndex * 2 + 1;
+ }
+
+ private int getRightChildIndex(int nodeIndex) {
+ return nodeIndex * 2 + 2;
+ }
+
+ private long getMax(int index) {
+ if (!hasNode(index)) {
+ return Long.MIN_VALUE;
+ }
+ return _maxs.get(index);
+ }
+
+ /**
+ * Find all values whose intervals intersect with the input interval.
+ *
+ * @param searchInterval search interval
+ * @return list of all qualified values.
+ */
+ public List<Value> searchAll(Interval searchInterval) {
+ List<Value> list = new ArrayList<>();
+ if (searchInterval == null) {
+ return list;
+ }
+ searchAll(0, searchInterval, list);
+ return list;
+ }
+
+ private boolean searchAll(int nodeIndex, Interval searchInterval, List<Value> list) {
Review comment:
Yes, I agree. `root.min <= interval.max` should be a tighter condition.
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] jtao15 commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
jtao15 commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r529759262
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/intervalST/IntervalST.java
##########
@@ -0,0 +1,197 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner.intervalST;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * The {@code IntervalST} class represents read-only balanced binary interval search tree map (from intervals to values)
+ */
+public class IntervalST<Value> {
+
+ // List representation of bst with root at index 0. For node with index x, it's left child index is (2x+1), right child index is (2x+2)
+ //
+ // A node with index x is represented as following structure
+ // {
+ // Interval _interval = _intervals[x];
+ // List<Value> _values = _values[x];
+ // long _max = _max[x]; // max interval right end of subtree rooted at this node
+ // }
+ private final List<Interval> _intervals;
+ private final List<List<Value>> _values;
+ private final List<Long> _maxs;
+
+ public IntervalST(Map<Value, Interval> valueToIntervalMap) {
+ HashMap<Interval, List<Value>> intervalToValuesMap = new HashMap<>();
+ for (Map.Entry<Value, Interval> entry : valueToIntervalMap.entrySet()) {
+ List<Value> vals = intervalToValuesMap.putIfAbsent(entry.getValue(), new ArrayList<>());
+ intervalToValuesMap.get(entry.getValue()).add(entry.getKey());
+ }
+
+ List<Interval> sortedIntervals = new ArrayList<>(intervalToValuesMap.keySet());
+ Collections.sort(sortedIntervals);
+
+ _intervals = new ArrayList<>(sortedIntervals.size());
+ buildIntervalTree(sortedIntervals, _intervals);
+
+ _values = new ArrayList<>(_intervals.size());
+ for (Interval interval: _intervals) {
+ if (interval == null) {
+ _values.add(null);
+ } else {
+ _values.add(intervalToValuesMap.get(interval));
+ }
+ }
+
+ _maxs = new ArrayList<>(_intervals.size());
+ buildAuxiliaryInfo();
+ }
+
+ private void buildIntervalTree(List<Interval> sortedIntervals, List<Interval> res) {
+ // Build interval bst by bfs, the root for each subtree will be the median interval.
+ // A typical balanced tree
+ // [10, 20]
+ // / \
+ // [8, 15] [12, 20]
+ // / /
+ // [5, 10] [10, 30]
+ //
+ // will be represented as { [10, 20], [8, 15], [12, 20], [5, 10], null, [10, 30] }
+ if (sortedIntervals.size() == 0) {
+ return;
+ }
+
+ LinkedList<Integer> startIndexQueue = new LinkedList<>();
+ LinkedList<Integer> endIndexQueue = new LinkedList<>();
+ startIndexQueue.addLast(0);
+ endIndexQueue.addLast(sortedIntervals.size());
+ int count = 0;
+ while (!startIndexQueue.isEmpty() && count < sortedIntervals.size()) {
+ int start = startIndexQueue.pollFirst();
+ int end = endIndexQueue.pollFirst();
+ if (start < end) {
+ int mid = start + (end - start) / 2;
+ res.add(sortedIntervals.get(mid));
+ count++;
+ startIndexQueue.addLast(start);
+ endIndexQueue.addLast(mid);
+ startIndexQueue.addLast(mid + 1);
+ endIndexQueue.addLast(end);
+ } else {
+ res.add(null);
+ }
+ }
+ }
+
+ private void buildAuxiliaryInfo() {
+ // Initialize and build max info for the interval tree by dfs
+ for (int i = 0; i < _intervals.size(); i++) {
+ _maxs.add(Long.MIN_VALUE);
+ }
+ buildAuxiliaryInfo(0);
+ }
+
+ private void buildAuxiliaryInfo(int nodeIndex) {
+ if (!hasNode(nodeIndex)) {
+ return;
+ }
+
+ int leftChildIndex = getLeftChildIndex(nodeIndex);
+ int rightChildIndex = getRightChildIndex(nodeIndex);
+
+ buildAuxiliaryInfo(leftChildIndex);
+ buildAuxiliaryInfo(rightChildIndex);
+
+ long max = _intervals.get(nodeIndex)._max;
+ max = Math.max(getMax(rightChildIndex), Math.max(max, getMax(leftChildIndex)));
+ _maxs.set(nodeIndex, max);
+ }
+
+ private int getLeftChildIndex(int nodeIndex) {
+ return nodeIndex * 2 + 1;
+ }
+
+ private int getRightChildIndex(int nodeIndex) {
+ return nodeIndex * 2 + 2;
+ }
+
+ private long getMax(int index) {
+ if (!hasNode(index)) {
+ return Long.MIN_VALUE;
+ }
+ return _maxs.get(index);
+ }
+
+ /**
+ * Find all values whose intervals intersect with the input interval.
+ *
+ * @param searchInterval search interval
+ * @return list of all qualified values.
+ */
+ public List<Value> searchAll(Interval searchInterval) {
+ List<Value> list = new ArrayList<>();
+ if (searchInterval == null) {
+ return list;
+ }
+ searchAll(0, searchInterval, list);
+ return list;
+ }
+
+ private boolean searchAll(int nodeIndex, Interval searchInterval, List<Value> list) {
Review comment:
Yes, I agree.
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] jtao15 commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
jtao15 commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r522547863
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/intervalST/IntervalST.java
##########
@@ -0,0 +1,187 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner.intervalST;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+
+// A read-only interval search tree based on AVL Tree
+public class IntervalST<Value> {
Review comment:
For the Interval search tree, auxiliary info - `max` (max end point for subtree) are kept for each node. And searching decisions are made based on this info. Correct me if I'm wrong, but I couldn't find any bst implementation supports customized searching.
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] siddharthteotia commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
siddharthteotia commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r521869463
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeRangeSegmentPruner.java
##########
@@ -0,0 +1,348 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeRangeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeRangeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeRangeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+
+ public TimeRangeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ updateTimeRangeMSToSegmentSearchTree(onlineSegments);
+ }
+
+ private void updateTimeRangeMSToSegmentSearchTree(Set<String> onlineSegments) {
+ List<String> segments = new ArrayList<>(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ List<String> segmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: segments) {
+ segmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(segmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ List<Long> startTimes = new ArrayList<>();
+ List<Long> endTimes = new ArrayList<>();
+
+ for (int i = 0; i < segments.size(); i++) {
+ String segment = segments.get(i);
+
+ long[] range = extractStartEndTimeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ startTimes.add(range[0]);
+ endTimes.add(range[1]);
+ }
+
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(startTimes, endTimes, segments);
+ }
+
+
+ private long[] extractStartEndTimeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ long[] range = {MIN_START_TIME, MAX_END_TIME};
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ range[0] = timeUnit.toMillis(startTime);
+ range[1] = timeUnit.toMillis(endTime);
+ return range;
+ }
+
+ @Override
+ public void refreshSegment(String segment) {
+ Set<String> segments;
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ segments = new HashSet<>();
+ } else {
+ segments = _timeRangeMSToSegmentSearchTree.getAllValues();
+ }
+ if (!segment.contains(segment)) {
+ segments.add(segment);
+ }
+
+ updateTimeRangeMSToSegmentSearchTree(segments);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ return segments;
+ }
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> ranges = getFilterTimeRange(filterQueryTree);
+ if (ranges == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (ranges.size() == 0) { // invalid query time range
+ return Collections.emptySet();
+ }
+
+ Set<String> prunedSegments = new HashSet<>();
+ for (Interval range : ranges) {
+ Interval rangeMS = convertRangeToMS(range);
+ for (Object segment : _timeRangeMSToSegmentSearchTree.searchAll(rangeMS)) {
+ if (segments.contains(segment)) {
+ prunedSegments.add((String) segment);
+ }
+ }
+ }
+ return new HashSet<String>(prunedSegments);
+ }
+
+ private List<Interval> getFilterTimeRange(FilterQueryTree filterQueryTree) {
+ // return NUll if no time range info or cannot filter base on the info (e.g. 'SELECT * from myTable where time < 50 OR firstName = Jason')
+ // return an empty list if filtering range is specified but invalid (e.g. 'SELECT * from myTable where time < 50 AND time > 100')
+ switch (filterQueryTree.getOperator()) {
+ case AND:
+ List<List<Interval>> andRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges != null) {
+ andRanges.add(childRanges);
+ }
+ }
+ return getIntersectionSortedRanges(andRanges);
+ case OR:
+ List<List<Interval>> orRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges == null) {
+ return null;
+ } else {
+ orRanges.add(childRanges);
+ }
+ }
+ return getUnionSortedRanges(orRanges);
+ case EQUALITY:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ long timeStamp = Long.parseLong(filterQueryTree.getValue().get(0));
+ return Collections.singletonList(new Interval(timeStamp, timeStamp));
+ }
+ return null;
+ case RANGE:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ return parseRange(filterQueryTree.getValue());
+ }
+ return null;
+ default:
+ return null;
+ }
+ }
+
+ private Interval convertRangeToMS(Interval range) {
+ long min = range.min == MIN_START_TIME ? MIN_START_TIME : _timeUnit.toMillis(range.min);
+ long max = range.max == MAX_END_TIME ? MAX_END_TIME : _timeUnit.toMillis(range.max);
+ return new Interval(min, max);
+ }
+
+ private List<Interval> getIntersectionSortedRanges(List<List<Interval>> ranges) {
+ // Requires input ranges are sorted, the return ranges will be sorted
+ return getIntersectionSortedRanges(ranges, 0, ranges.size());
+ }
+
+ private List<Interval> getIntersectionSortedRanges(List<List<Interval>> ranges, int start, int end) {
+ if (start == end) {
+ return null;
+ }
+
+ if (start + 1 == end) {
+ return ranges.get(start);
+ }
+
+ int mid = start + (end - start) / 2;
+ List<Interval> ranges1 = getIntersectionSortedRanges(ranges, start, mid);
+ List<Interval> ranges2 = getIntersectionSortedRanges(ranges, mid, end);
+ return getIntersectionOfTwoSortedRanges(ranges1, ranges2);
+ }
+
+ private List<Interval> getIntersectionOfTwoSortedRanges(List<Interval> ranges1, List<Interval> ranges2) { // sorted non-overlapping ranges
+ List<Interval> res = new ArrayList<>();
+ int i = 0, j = 0;
+ while (i < ranges1.size() && j < ranges2.size()) {
+ Interval range1 = ranges1.get(i);
+ Interval range2 = ranges2.get(j);
+ if (range1.intersects(range2)) {
+ res.add(Interval.getIntersection(range1, range2));
+ }
+ if (range1.max < range2.max) {
+ i++;
+ } else {
+ j++;
+ }
+ }
+ return res;
+ }
+
+ private List<Interval> getUnionSortedRanges(List<List<Interval>> ranges) {
+ return getUnionSortedRanges(ranges, 0, ranges.size());
+ }
+
+ private List<Interval> getUnionSortedRanges(List<List<Interval>> ranges, int start, int end) {
Review comment:
I think List of list is complicating the algorithm slightly. We can combine these two methods into one method that does sorted merge of two List<Interval>
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] Jackie-Jiang commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
Jackie-Jiang commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r532999473
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeSegmentPruner.java
##########
@@ -0,0 +1,344 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.interval.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.interval.IntervalTree;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeSegmentPruner.class);
+ private static final long MIN_START_TIME = 0;
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final Interval DEFAULT_INTERVAL = new Interval(MIN_START_TIME, MAX_END_TIME);
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore<ZNRecord> _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final DateTimeFormatSpec _timeFormatSpec;
+
+ private volatile IntervalTree _intervalTree;
+ private final Map<String, Interval> _intervalMap = new HashMap<>();
+
+ public TimeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ _timeFormatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ Preconditions.checkNotNull(_timeFormatSpec.getColumnUnit(),
Review comment:
Why do we need this check? We should not need the time unit information
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeSegmentPruner.java
##########
@@ -0,0 +1,344 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.interval.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.interval.IntervalTree;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeSegmentPruner.class);
+ private static final long MIN_START_TIME = 0;
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final Interval DEFAULT_INTERVAL = new Interval(MIN_START_TIME, MAX_END_TIME);
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore<ZNRecord> _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final DateTimeFormatSpec _timeFormatSpec;
+
+ private volatile IntervalTree _intervalTree;
+ private final Map<String, Interval> _intervalMap = new HashMap<>();
+
+ public TimeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ _timeFormatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ Preconditions.checkNotNull(_timeFormatSpec.getColumnUnit(),
+ "Time unit must be configured in the field spec for time column: %s of table: %s", _timeColumn,
+ _tableNameWithType);
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ // Bulk load time info for all online segments
+ int numSegments = onlineSegments.size();
+ List<String> segments = new ArrayList<>(numSegments);
+ List<String> segmentZKMetadataPaths = new ArrayList<>(numSegments);
+ for (String segment : segments) {
+ segments.add(segment);
+ segmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+ List<ZNRecord> znRecords = _propertyStore.get(segmentZKMetadataPaths, null, AccessOption.PERSISTENT, false);
+ for (int i = 0; i < numSegments; i++) {
+ String segment = segments.get(i);
+ Interval interval = extractIntervalFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ _intervalMap.put(segment, interval);
+ }
+ _intervalTree = new IntervalTree<>(_intervalMap);
+ }
+
+ private Interval extractIntervalFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ // Segments without metadata or with invalid time interval will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return DEFAULT_INTERVAL;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid time interval for segment: {}, table: {}", segment, _tableNameWithType);
+ return DEFAULT_INTERVAL;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ return new Interval(timeUnit.toMillis(startTime), timeUnit.toMillis(endTime));
+ }
+
+ @Override
+ public synchronized void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ // NOTE: We don't update all the segment ZK metadata for every external view change, but only the new added/removed
+ // ones. The refreshed segment ZK metadata change won't be picked up.
+ for (String segment : onlineSegments) {
+ _intervalMap.computeIfAbsent(segment, k -> extractIntervalFromSegmentZKMetaZNRecord(k,
+ _propertyStore.get(_segmentZKMetadataPathPrefix + k, null, AccessOption.PERSISTENT)));
+ }
+ _intervalMap.keySet().retainAll(onlineSegments);
+ _intervalTree = new IntervalTree<>(_intervalMap);
+ }
+
+
+ @Override
+ public synchronized void refreshSegment(String segment) {
+ Interval interval = extractIntervalFromSegmentZKMetaZNRecord(segment, _propertyStore.get(_segmentZKMetadataPathPrefix + segment, null, AccessOption.PERSISTENT));
+ _intervalMap.put(segment, interval);
+ _intervalTree = new IntervalTree<>(_intervalMap);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _intervalTree based on request time interval and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N: # of all online segments,
+ * M: # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ IntervalTree<String> intervalTree = _intervalTree;
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> intervals = getFilterTimeIntervals(filterQueryTree);
+ if (intervals == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (intervals.isEmpty()) { // invalid query time interval
+ return Collections.emptySet();
+ }
+
+ Set<String> selectedSegments = new HashSet<>();
+ for (Interval interval : intervals) {
+ for (String segment : intervalTree.searchAll(interval)) {
+ if (segments.contains(segment)) {
+ selectedSegments.add(segment);
+ }
+ }
+ }
+ return selectedSegments;
+ }
+
+ /**
+ * @return Null if no time condition or cannot filter base on the condition (e.g. 'SELECT * from myTable where time < 50 OR firstName = Jason')
+ * @return Empty list if time condition is specified but invalid (e.g. 'SELECT * from myTable where time < 50 AND time > 100')
+ */
+ @Nullable
+ private List<Interval> getFilterTimeIntervals(FilterQueryTree filterQueryTree) {
+ switch (filterQueryTree.getOperator()) {
+ case AND:
+ List<List<Interval>> andIntervals = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childIntervals = getFilterTimeIntervals(child);
+ if (childIntervals != null) {
Review comment:
We can check for empty intervals and directly return empty list
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeSegmentPruner.java
##########
@@ -0,0 +1,344 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.interval.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.interval.IntervalTree;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeSegmentPruner.class);
+ private static final long MIN_START_TIME = 0;
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final Interval DEFAULT_INTERVAL = new Interval(MIN_START_TIME, MAX_END_TIME);
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore<ZNRecord> _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final DateTimeFormatSpec _timeFormatSpec;
+
+ private volatile IntervalTree _intervalTree;
Review comment:
```suggestion
private volatile IntervalTree<String> _intervalTree;
```
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeSegmentPruner.java
##########
@@ -0,0 +1,344 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.interval.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.interval.IntervalTree;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeSegmentPruner.class);
+ private static final long MIN_START_TIME = 0;
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final Interval DEFAULT_INTERVAL = new Interval(MIN_START_TIME, MAX_END_TIME);
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore<ZNRecord> _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final DateTimeFormatSpec _timeFormatSpec;
+
+ private volatile IntervalTree _intervalTree;
+ private final Map<String, Interval> _intervalMap = new HashMap<>();
+
+ public TimeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ _timeFormatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ Preconditions.checkNotNull(_timeFormatSpec.getColumnUnit(),
+ "Time unit must be configured in the field spec for time column: %s of table: %s", _timeColumn,
+ _tableNameWithType);
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ // Bulk load time info for all online segments
+ int numSegments = onlineSegments.size();
+ List<String> segments = new ArrayList<>(numSegments);
+ List<String> segmentZKMetadataPaths = new ArrayList<>(numSegments);
+ for (String segment : segments) {
+ segments.add(segment);
+ segmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+ List<ZNRecord> znRecords = _propertyStore.get(segmentZKMetadataPaths, null, AccessOption.PERSISTENT, false);
+ for (int i = 0; i < numSegments; i++) {
+ String segment = segments.get(i);
+ Interval interval = extractIntervalFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ _intervalMap.put(segment, interval);
+ }
+ _intervalTree = new IntervalTree<>(_intervalMap);
+ }
+
+ private Interval extractIntervalFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ // Segments without metadata or with invalid time interval will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return DEFAULT_INTERVAL;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid time interval for segment: {}, table: {}", segment, _tableNameWithType);
+ return DEFAULT_INTERVAL;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ return new Interval(timeUnit.toMillis(startTime), timeUnit.toMillis(endTime));
+ }
+
+ @Override
+ public synchronized void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ // NOTE: We don't update all the segment ZK metadata for every external view change, but only the new added/removed
+ // ones. The refreshed segment ZK metadata change won't be picked up.
+ for (String segment : onlineSegments) {
+ _intervalMap.computeIfAbsent(segment, k -> extractIntervalFromSegmentZKMetaZNRecord(k,
+ _propertyStore.get(_segmentZKMetadataPathPrefix + k, null, AccessOption.PERSISTENT)));
+ }
+ _intervalMap.keySet().retainAll(onlineSegments);
+ _intervalTree = new IntervalTree<>(_intervalMap);
+ }
+
+
+ @Override
+ public synchronized void refreshSegment(String segment) {
+ Interval interval = extractIntervalFromSegmentZKMetaZNRecord(segment, _propertyStore.get(_segmentZKMetadataPathPrefix + segment, null, AccessOption.PERSISTENT));
+ _intervalMap.put(segment, interval);
+ _intervalTree = new IntervalTree<>(_intervalMap);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _intervalTree based on request time interval and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N: # of all online segments,
+ * M: # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ IntervalTree<String> intervalTree = _intervalTree;
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> intervals = getFilterTimeIntervals(filterQueryTree);
+ if (intervals == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (intervals.isEmpty()) { // invalid query time interval
+ return Collections.emptySet();
+ }
+
+ Set<String> selectedSegments = new HashSet<>();
+ for (Interval interval : intervals) {
+ for (String segment : intervalTree.searchAll(interval)) {
+ if (segments.contains(segment)) {
+ selectedSegments.add(segment);
+ }
+ }
+ }
+ return selectedSegments;
+ }
+
+ /**
+ * @return Null if no time condition or cannot filter base on the condition (e.g. 'SELECT * from myTable where time < 50 OR firstName = Jason')
+ * @return Empty list if time condition is specified but invalid (e.g. 'SELECT * from myTable where time < 50 AND time > 100')
+ */
+ @Nullable
+ private List<Interval> getFilterTimeIntervals(FilterQueryTree filterQueryTree) {
+ switch (filterQueryTree.getOperator()) {
+ case AND:
+ List<List<Interval>> andIntervals = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childIntervals = getFilterTimeIntervals(child);
+ if (childIntervals != null) {
+ andIntervals.add(childIntervals);
+ }
+ }
+ return getIntersectionSortedIntervals(andIntervals);
+ case OR:
+ List<List<Interval>> orIntervals = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childIntervals = getFilterTimeIntervals(child);
+ if (childIntervals == null) {
+ return null;
+ } else {
+ orIntervals.add(childIntervals);
+ }
+ }
+ return getUnionSortedIntervals(orIntervals);
+ case EQUALITY:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ long timeStamp = _timeFormatSpec.fromFormatToMillis(filterQueryTree.getValue().get(0));
+ return Collections.singletonList(new Interval(timeStamp, timeStamp));
+ }
+ return null;
+ case RANGE:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ return parseInterval(filterQueryTree.getValue());
+ }
+ return null;
+ default:
+ return null;
+ }
+ }
+
+ private List<Interval> getIntersectionSortedIntervals(List<List<Interval>> intervals) {
+ // Requires input intervals are sorted, the return intervals will be sorted
+ if (intervals.isEmpty()) {
+ return null;
+ }
+ return getIntersectionSortedIntervals(intervals, 0, intervals.size());
+ }
+
+ private List<Interval> getIntersectionSortedIntervals(List<List<Interval>> intervals, int start, int end) {
+ if (start + 1 == end) {
+ return intervals.get(start);
+ }
+
+ int mid = start + (end - start) / 2;
+ List<Interval> interval1 = getIntersectionSortedIntervals(intervals, start, mid);
+ List<Interval> interval2 = getIntersectionSortedIntervals(intervals, mid, end);
+ return getIntersectionTwoSortedIntervals(interval1, interval2);
+ }
+
+ /**
+ * Intersect two list of non-overlapping sorted intervals.
+ * E.g. {[1, 3], [4, 6], [7, 8], [10, 10]} and {[2, 5], [7, 9]} are merged as {[2, 3], [4, 5], [7, 8]}
+ */
+ private List<Interval> getIntersectionTwoSortedIntervals(List<Interval> intervals1, List<Interval> intervals2) {
+ List<Interval> res = new ArrayList<>();
+ int size1 = intervals1.size();
+ int size2 = intervals2.size();
+ int i = 0;
+ int j = 0;
+ while (i < size1 && j < size2) {
+ Interval interval1 = intervals1.get(i);
+ Interval interval2 = intervals2.get(j);
+ if (interval1.intersects(interval2)) {
+ res.add(Interval.getIntersection(interval1, interval2));
+ }
+ if (interval1._max <= interval2._max) {
+ i++;
+ } else {
+ j++;
+ }
+ }
+ return res;
+ }
+
+ private List<Interval> getUnionSortedIntervals(List<List<Interval>> intervals) {
+ // Requires input intervals are sorted, the return intervals will be sorted
+ if (intervals.isEmpty()) {
Review comment:
Not really possible, or it should already return `null` under the `OR` case
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeSegmentPruner.java
##########
@@ -0,0 +1,344 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.interval.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.interval.IntervalTree;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeSegmentPruner.class);
+ private static final long MIN_START_TIME = 0;
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final Interval DEFAULT_INTERVAL = new Interval(MIN_START_TIME, MAX_END_TIME);
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore<ZNRecord> _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final DateTimeFormatSpec _timeFormatSpec;
+
+ private volatile IntervalTree _intervalTree;
+ private final Map<String, Interval> _intervalMap = new HashMap<>();
+
+ public TimeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ _timeFormatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ Preconditions.checkNotNull(_timeFormatSpec.getColumnUnit(),
+ "Time unit must be configured in the field spec for time column: %s of table: %s", _timeColumn,
+ _tableNameWithType);
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ // Bulk load time info for all online segments
+ int numSegments = onlineSegments.size();
+ List<String> segments = new ArrayList<>(numSegments);
+ List<String> segmentZKMetadataPaths = new ArrayList<>(numSegments);
+ for (String segment : segments) {
+ segments.add(segment);
+ segmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+ List<ZNRecord> znRecords = _propertyStore.get(segmentZKMetadataPaths, null, AccessOption.PERSISTENT, false);
+ for (int i = 0; i < numSegments; i++) {
+ String segment = segments.get(i);
+ Interval interval = extractIntervalFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ _intervalMap.put(segment, interval);
+ }
+ _intervalTree = new IntervalTree<>(_intervalMap);
+ }
+
+ private Interval extractIntervalFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ // Segments without metadata or with invalid time interval will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return DEFAULT_INTERVAL;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid time interval for segment: {}, table: {}", segment, _tableNameWithType);
+ return DEFAULT_INTERVAL;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ return new Interval(timeUnit.toMillis(startTime), timeUnit.toMillis(endTime));
+ }
+
+ @Override
+ public synchronized void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ // NOTE: We don't update all the segment ZK metadata for every external view change, but only the new added/removed
+ // ones. The refreshed segment ZK metadata change won't be picked up.
+ for (String segment : onlineSegments) {
+ _intervalMap.computeIfAbsent(segment, k -> extractIntervalFromSegmentZKMetaZNRecord(k,
+ _propertyStore.get(_segmentZKMetadataPathPrefix + k, null, AccessOption.PERSISTENT)));
+ }
+ _intervalMap.keySet().retainAll(onlineSegments);
+ _intervalTree = new IntervalTree<>(_intervalMap);
+ }
+
+
+ @Override
+ public synchronized void refreshSegment(String segment) {
+ Interval interval = extractIntervalFromSegmentZKMetaZNRecord(segment, _propertyStore.get(_segmentZKMetadataPathPrefix + segment, null, AccessOption.PERSISTENT));
+ _intervalMap.put(segment, interval);
+ _intervalTree = new IntervalTree<>(_intervalMap);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _intervalTree based on request time interval and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N: # of all online segments,
+ * M: # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ IntervalTree<String> intervalTree = _intervalTree;
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> intervals = getFilterTimeIntervals(filterQueryTree);
+ if (intervals == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (intervals.isEmpty()) { // invalid query time interval
+ return Collections.emptySet();
+ }
+
+ Set<String> selectedSegments = new HashSet<>();
+ for (Interval interval : intervals) {
+ for (String segment : intervalTree.searchAll(interval)) {
+ if (segments.contains(segment)) {
+ selectedSegments.add(segment);
+ }
+ }
+ }
+ return selectedSegments;
+ }
+
+ /**
+ * @return Null if no time condition or cannot filter base on the condition (e.g. 'SELECT * from myTable where time < 50 OR firstName = Jason')
+ * @return Empty list if time condition is specified but invalid (e.g. 'SELECT * from myTable where time < 50 AND time > 100')
+ */
+ @Nullable
+ private List<Interval> getFilterTimeIntervals(FilterQueryTree filterQueryTree) {
+ switch (filterQueryTree.getOperator()) {
+ case AND:
+ List<List<Interval>> andIntervals = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childIntervals = getFilterTimeIntervals(child);
+ if (childIntervals != null) {
+ andIntervals.add(childIntervals);
+ }
+ }
+ return getIntersectionSortedIntervals(andIntervals);
+ case OR:
+ List<List<Interval>> orIntervals = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childIntervals = getFilterTimeIntervals(child);
+ if (childIntervals == null) {
+ return null;
+ } else {
+ orIntervals.add(childIntervals);
+ }
+ }
+ return getUnionSortedIntervals(orIntervals);
+ case EQUALITY:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ long timeStamp = _timeFormatSpec.fromFormatToMillis(filterQueryTree.getValue().get(0));
+ return Collections.singletonList(new Interval(timeStamp, timeStamp));
+ }
+ return null;
+ case RANGE:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ return parseInterval(filterQueryTree.getValue());
+ }
+ return null;
+ default:
+ return null;
+ }
+ }
+
+ private List<Interval> getIntersectionSortedIntervals(List<List<Interval>> intervals) {
+ // Requires input intervals are sorted, the return intervals will be sorted
+ if (intervals.isEmpty()) {
Review comment:
Please add some comments here on why it should return `null` for empty intervals list. IMO handle it in the `case AND:` is more clear, up to you
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeSegmentPruner.java
##########
@@ -0,0 +1,344 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.interval.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.interval.IntervalTree;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeSegmentPruner.class);
+ private static final long MIN_START_TIME = 0;
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final Interval DEFAULT_INTERVAL = new Interval(MIN_START_TIME, MAX_END_TIME);
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore<ZNRecord> _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final DateTimeFormatSpec _timeFormatSpec;
+
+ private volatile IntervalTree _intervalTree;
+ private final Map<String, Interval> _intervalMap = new HashMap<>();
+
+ public TimeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ _timeFormatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ Preconditions.checkNotNull(_timeFormatSpec.getColumnUnit(),
+ "Time unit must be configured in the field spec for time column: %s of table: %s", _timeColumn,
+ _tableNameWithType);
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ // Bulk load time info for all online segments
+ int numSegments = onlineSegments.size();
+ List<String> segments = new ArrayList<>(numSegments);
+ List<String> segmentZKMetadataPaths = new ArrayList<>(numSegments);
+ for (String segment : segments) {
+ segments.add(segment);
+ segmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+ List<ZNRecord> znRecords = _propertyStore.get(segmentZKMetadataPaths, null, AccessOption.PERSISTENT, false);
+ for (int i = 0; i < numSegments; i++) {
+ String segment = segments.get(i);
+ Interval interval = extractIntervalFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ _intervalMap.put(segment, interval);
+ }
+ _intervalTree = new IntervalTree<>(_intervalMap);
+ }
+
+ private Interval extractIntervalFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ // Segments without metadata or with invalid time interval will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return DEFAULT_INTERVAL;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid time interval for segment: {}, table: {}", segment, _tableNameWithType);
+ return DEFAULT_INTERVAL;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ return new Interval(timeUnit.toMillis(startTime), timeUnit.toMillis(endTime));
+ }
+
+ @Override
+ public synchronized void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ // NOTE: We don't update all the segment ZK metadata for every external view change, but only the new added/removed
+ // ones. The refreshed segment ZK metadata change won't be picked up.
+ for (String segment : onlineSegments) {
+ _intervalMap.computeIfAbsent(segment, k -> extractIntervalFromSegmentZKMetaZNRecord(k,
+ _propertyStore.get(_segmentZKMetadataPathPrefix + k, null, AccessOption.PERSISTENT)));
+ }
+ _intervalMap.keySet().retainAll(onlineSegments);
+ _intervalTree = new IntervalTree<>(_intervalMap);
+ }
+
+
+ @Override
+ public synchronized void refreshSegment(String segment) {
+ Interval interval = extractIntervalFromSegmentZKMetaZNRecord(segment, _propertyStore.get(_segmentZKMetadataPathPrefix + segment, null, AccessOption.PERSISTENT));
+ _intervalMap.put(segment, interval);
+ _intervalTree = new IntervalTree<>(_intervalMap);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _intervalTree based on request time interval and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N: # of all online segments,
+ * M: # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ IntervalTree<String> intervalTree = _intervalTree;
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> intervals = getFilterTimeIntervals(filterQueryTree);
+ if (intervals == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (intervals.isEmpty()) { // invalid query time interval
+ return Collections.emptySet();
+ }
+
+ Set<String> selectedSegments = new HashSet<>();
+ for (Interval interval : intervals) {
+ for (String segment : intervalTree.searchAll(interval)) {
+ if (segments.contains(segment)) {
+ selectedSegments.add(segment);
+ }
+ }
+ }
+ return selectedSegments;
+ }
+
+ /**
+ * @return Null if no time condition or cannot filter base on the condition (e.g. 'SELECT * from myTable where time < 50 OR firstName = Jason')
+ * @return Empty list if time condition is specified but invalid (e.g. 'SELECT * from myTable where time < 50 AND time > 100')
+ */
+ @Nullable
+ private List<Interval> getFilterTimeIntervals(FilterQueryTree filterQueryTree) {
+ switch (filterQueryTree.getOperator()) {
+ case AND:
+ List<List<Interval>> andIntervals = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childIntervals = getFilterTimeIntervals(child);
+ if (childIntervals != null) {
+ andIntervals.add(childIntervals);
+ }
+ }
+ return getIntersectionSortedIntervals(andIntervals);
+ case OR:
+ List<List<Interval>> orIntervals = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childIntervals = getFilterTimeIntervals(child);
+ if (childIntervals == null) {
+ return null;
+ } else {
+ orIntervals.add(childIntervals);
+ }
+ }
+ return getUnionSortedIntervals(orIntervals);
+ case EQUALITY:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ long timeStamp = _timeFormatSpec.fromFormatToMillis(filterQueryTree.getValue().get(0));
+ return Collections.singletonList(new Interval(timeStamp, timeStamp));
+ }
+ return null;
+ case RANGE:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ return parseInterval(filterQueryTree.getValue());
+ }
+ return null;
+ default:
+ return null;
+ }
+ }
+
+ private List<Interval> getIntersectionSortedIntervals(List<List<Interval>> intervals) {
+ // Requires input intervals are sorted, the return intervals will be sorted
+ if (intervals.isEmpty()) {
+ return null;
+ }
+ return getIntersectionSortedIntervals(intervals, 0, intervals.size());
+ }
+
+ private List<Interval> getIntersectionSortedIntervals(List<List<Interval>> intervals, int start, int end) {
+ if (start + 1 == end) {
+ return intervals.get(start);
+ }
+
+ int mid = start + (end - start) / 2;
+ List<Interval> interval1 = getIntersectionSortedIntervals(intervals, start, mid);
+ List<Interval> interval2 = getIntersectionSortedIntervals(intervals, mid, end);
+ return getIntersectionTwoSortedIntervals(interval1, interval2);
+ }
+
+ /**
+ * Intersect two list of non-overlapping sorted intervals.
+ * E.g. {[1, 3], [4, 6], [7, 8], [10, 10]} and {[2, 5], [7, 9]} are merged as {[2, 3], [4, 5], [7, 8]}
+ */
+ private List<Interval> getIntersectionTwoSortedIntervals(List<Interval> intervals1, List<Interval> intervals2) {
+ List<Interval> res = new ArrayList<>();
+ int size1 = intervals1.size();
+ int size2 = intervals2.size();
+ int i = 0;
+ int j = 0;
+ while (i < size1 && j < size2) {
+ Interval interval1 = intervals1.get(i);
+ Interval interval2 = intervals2.get(j);
+ if (interval1.intersects(interval2)) {
+ res.add(Interval.getIntersection(interval1, interval2));
+ }
+ if (interval1._max <= interval2._max) {
+ i++;
+ } else {
+ j++;
+ }
+ }
+ return res;
+ }
+
+ private List<Interval> getUnionSortedIntervals(List<List<Interval>> intervals) {
+ // Requires input intervals are sorted, the return intervals will be sorted
+ if (intervals.isEmpty()) {
+ return null;
+ }
+ return getUnionSortedIntervals(intervals, 0, intervals.size());
+ }
+
+ private List<Interval> getUnionSortedIntervals(List<List<Interval>> intervals, int start, int end) {
+ if (start + 1 == end) {
+ return intervals.get(start);
+ }
+
+ int mid = start + (end - start) / 2;
+ List<Interval> intervals1 = getUnionSortedIntervals(intervals, start, mid);
+ List<Interval> intervals2 = getUnionSortedIntervals(intervals, mid, end);
+ return getUnionTwoSortedIntervals(intervals1, intervals2);
+ }
+
+ /**
+ * Union two list of non-overlapping sorted intervals.
+ * E.g. {[1, 2], [5, 7], [9, 10]} and {[2, 3], [4, 8]} are merged as {[1, 3], [4, 8], [9, 10]}
+ */
+ private List<Interval> getUnionTwoSortedIntervals(List<Interval> intervals1, List<Interval> intervals2) {
+ List<Interval> res = new ArrayList<>();
+ int size1 = intervals1.size();
+ int size2 = intervals2.size();
+ int i = 0;
+ int j = 0;
+ while (i < size1 || j < size2) {
+ // Get the `smaller` interval
+ Interval interval = null;
+ if (j == size2 || i < size1 && intervals1.get(i).compareTo(intervals2.get(j)) <= 0) {
+ interval = intervals1.get(i++);
+ } else {
+ interval = intervals2.get(j++);
+ }
+ // If not overlapping with current result, add as a new interval
+ int resSize = res.size();
+ if (res.isEmpty() || !interval.intersects(res.get(resSize - 1))) {
+ res.add(interval);
+ } else {
+ // If overlaps with the result, union with current result
+ res.set(resSize - 1, Interval.getUnion(interval, res.get(resSize - 1)));
+ }
+ }
+ return res;
+ }
+
+ /**
+ * Parse interval to millisecond as [min, max] with both sides included.
+ * E.g. '(* 16311]' is parsed as [0, 16311], '(1455 16311)' is parsed as [1456, 16310]
+ */
+ private List<Interval> parseInterval(List<String> intervalExpressions) {
+ Preconditions.checkState(intervalExpressions != null && intervalExpressions.size() == 1,
+ "Cannot parse range expressions from query: %s", intervalExpressions);
+ long startTime = MIN_START_TIME;
+ long endTime = MAX_END_TIME;
+ String intervalExpression = intervalExpressions.get(0);
+ String[] s = intervalExpression.substring(1, intervalExpression.length() - 1).split("\\s+");
Review comment:
(Critical) Don't use arbitrary whitespace as the delimiter (they might be valid as the value, also I don't think '\0` is a whitespace). You may refer to `RangePredicate.java` on how to parse the range string
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] siddharthteotia commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
siddharthteotia commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r521872921
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/intervalST/IntervalST.java
##########
@@ -0,0 +1,187 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner.intervalST;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+
+// A read-only interval search tree based on AVL Tree
+public class IntervalST<Value> {
+
+ private Node<Value> root;
+
+ public IntervalST(List<Long> mins, List<Long> maxs, List<Value> values) {
+ // read only once constructed
+ for (int i = 0; i < mins.size(); i++) {
+ insert(mins.get(i), maxs.get(i), values.get(i));
+ }
+ }
+
+ private void insert(long min, long max, Value value) {
+ root = insert(root, new Interval(min, max), value);
+ }
+
+ private Node insert(Node node, Interval interval, Value value) {
+ if (node == null) {
+ return new Node(interval, value);
+ }
+
+ int cmp = interval.compareTo(node.interval);
+ if (cmp == 0) {
+ node.valueList.add(value);
+ return node;
+ } else if (cmp < 0) {
+ node.left = insert(node.left, interval, value);
+ } else {
+ node.right = insert(node.right, interval, value);
+ }
+
+ fixAuxiliaryInfo(node);
+ int balance = getBalance(node);
+ // Balance current subtree
+ if (balance < -1) {
+ if (getBalance(node.right) > 0) {
+ node.right = rotateRight(node.right); // Right-left case
+ }
+ node = rotateLeft(node);
+ } else if (balance > 1) {
+ if (getBalance(node.left) < 0) {
+ node.left = rotateLeft(node.left); // Left-right case
+ }
+ node = rotateRight(node);
+ }
+ return node;
+ }
+
+ // Get all intervals which intersect with input range [min, max]
+ public List<Value> searchAll(long min, long max) {
+ return searchAll(new Interval(min, max));
+ }
+
+ public List<Value> searchAll(Interval interval) {
Review comment:
This API is a bit non-intuitive. Essentially what it is doing is given an interval, it looks for all overlapping intervals in the BST and for all those overlapping intervals, returns the corresponding list of segments? At least a javadoc with details on semantics is definitely needed
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] siddharthteotia commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
siddharthteotia commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r521873946
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeRangeSegmentPruner.java
##########
@@ -0,0 +1,348 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeRangeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeRangeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeRangeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+
+ public TimeRangeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ updateTimeRangeMSToSegmentSearchTree(onlineSegments);
+ }
+
+ private void updateTimeRangeMSToSegmentSearchTree(Set<String> onlineSegments) {
+ List<String> segments = new ArrayList<>(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ List<String> segmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: segments) {
+ segmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(segmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ List<Long> startTimes = new ArrayList<>();
+ List<Long> endTimes = new ArrayList<>();
+
+ for (int i = 0; i < segments.size(); i++) {
+ String segment = segments.get(i);
+
+ long[] range = extractStartEndTimeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ startTimes.add(range[0]);
+ endTimes.add(range[1]);
+ }
+
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(startTimes, endTimes, segments);
+ }
+
+
+ private long[] extractStartEndTimeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ long[] range = {MIN_START_TIME, MAX_END_TIME};
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ range[0] = timeUnit.toMillis(startTime);
+ range[1] = timeUnit.toMillis(endTime);
+ return range;
+ }
+
+ @Override
+ public void refreshSegment(String segment) {
+ Set<String> segments;
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ segments = new HashSet<>();
+ } else {
+ segments = _timeRangeMSToSegmentSearchTree.getAllValues();
+ }
+ if (!segment.contains(segment)) {
+ segments.add(segment);
+ }
+
+ updateTimeRangeMSToSegmentSearchTree(segments);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ return segments;
+ }
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> ranges = getFilterTimeRange(filterQueryTree);
+ if (ranges == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (ranges.size() == 0) { // invalid query time range
+ return Collections.emptySet();
+ }
+
+ Set<String> prunedSegments = new HashSet<>();
Review comment:
Actually the reverse is true right? The segment list retrieved from BST is the one that will be used. Consider changing the name to selectedSegments or something else
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] snleee commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
snleee commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r544573213
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeSegmentPruner.java
##########
@@ -0,0 +1,346 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.interval.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.interval.IntervalTree;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeSegmentPruner.class);
+ private static final long MIN_START_TIME = 0;
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final Interval DEFAULT_INTERVAL = new Interval(MIN_START_TIME, MAX_END_TIME);
+ private static final char DELIMITER = '\0';
+ private static final String LEGACY_DELIMITER = "\t\t";
+ private static final char START_INCLUSIVE = '(';
+ private static final char END_INCLUSIVE = ')';
+ private static final String UNBOUNDED = "*";
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore<ZNRecord> _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final DateTimeFormatSpec _timeFormatSpec;
+
+ private volatile IntervalTree<String> _intervalTree;
+ private final Map<String, Interval> _intervalMap = new HashMap<>();
+
+ public TimeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
Review comment:
`Preconditions.checkNotNull()`
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] snleee commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
snleee commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r526637778
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/RoutingManager.java
##########
@@ -570,14 +570,14 @@ void refreshSegment(String segment) {
}
InstanceSelector.SelectionResult calculateRouting(BrokerRequest brokerRequest) {
- List<String> selectedSegments = _segmentSelector.select(brokerRequest);
+ Set<String> selectedSegments = _segmentSelector.select(brokerRequest);
if (!selectedSegments.isEmpty()) {
for (SegmentPruner segmentPruner : _segmentPruners) {
selectedSegments = segmentPruner.prune(brokerRequest, selectedSegments);
}
}
if (!selectedSegments.isEmpty()) {
- return _instanceSelector.select(brokerRequest, selectedSegments);
+ return _instanceSelector.select(brokerRequest, new ArrayList<>(selectedSegments));
Review comment:
Why did you change the interface to return `Set` for `SegmentSelector` if you will anyway convert it back to the array list?
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/instanceselector/BaseInstanceSelector.java
##########
@@ -25,8 +25,6 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
-import java.util.TreeMap;
Review comment:
+1 good catch :)
##########
File path: pinot-broker/src/test/java/org/apache/pinot/broker/routing/segmentpruner/SegmentPrunerTest.java
##########
@@ -170,56 +220,213 @@ public void testPartitionAwareSegmentPruner() {
ZKMetadataProvider
.setOfflineSegmentZKMetadata(_propertyStore, OFFLINE_TABLE_NAME, segmentZKMetadataWithoutPartitionMetadata);
segmentPruner.onExternalViewChange(externalView, idealState, onlineSegments);
- assertEquals(segmentPruner.prune(brokerRequest1, Collections.singletonList(segmentWithoutPartitionMetadata)),
+ assertEquals(segmentPruner.prune(brokerRequest1, new HashSet<>(Collections.singletonList(segmentWithoutPartitionMetadata))),
Collections.singletonList(segmentWithoutPartitionMetadata));
- assertEquals(segmentPruner.prune(brokerRequest2, Collections.singletonList(segmentWithoutPartitionMetadata)),
+ assertEquals(segmentPruner.prune(brokerRequest2, new HashSet<>(Collections.singletonList(segmentWithoutPartitionMetadata))),
Collections.singletonList(segmentWithoutPartitionMetadata));
- assertEquals(segmentPruner.prune(brokerRequest3, Collections.singletonList(segmentWithoutPartitionMetadata)),
+ assertEquals(segmentPruner.prune(brokerRequest3, new HashSet<>(Collections.singletonList(segmentWithoutPartitionMetadata))),
Collections.singletonList(segmentWithoutPartitionMetadata));
// Test different partition functions and number of partitions
// 0 % 5 = 0; 1 % 5 = 1; 2 % 5 = 2
String segment0 = "segment0";
onlineSegments.add(segment0);
- setSegmentZKMetadata(segment0, "Modulo", 5, 0);
+ setSegmentZKPartitionMetadata(segment0, "Modulo", 5, 0);
// Murmur(0) % 4 = 0; Murmur(1) % 4 = 3; Murmur(2) % 4 = 0
String segment1 = "segment1";
onlineSegments.add(segment1);
- setSegmentZKMetadata(segment1, "Murmur", 4, 0);
+ setSegmentZKPartitionMetadata(segment1, "Murmur", 4, 0);
segmentPruner.onExternalViewChange(externalView, idealState, onlineSegments);
- assertEquals(segmentPruner.prune(brokerRequest1, Arrays.asList(segment0, segment1)),
- Arrays.asList(segment0, segment1));
- assertEquals(segmentPruner.prune(brokerRequest2, Arrays.asList(segment0, segment1)),
- Arrays.asList(segment0, segment1));
- assertEquals(segmentPruner.prune(brokerRequest3, Arrays.asList(segment0, segment1)),
- Collections.singletonList(segment1));
+ assertEquals(segmentPruner.prune(brokerRequest1, new HashSet<>(Arrays.asList(segment0, segment1))),
+ new HashSet<>(Arrays.asList(segment0, segment1)));
+ assertEquals(segmentPruner.prune(brokerRequest2, new HashSet<>(Arrays.asList(segment0, segment1))),
+ new HashSet<>(Arrays.asList(segment0, segment1)));
+ assertEquals(segmentPruner.prune(brokerRequest3, new HashSet<>(Arrays.asList(segment0, segment1))),
+ new HashSet<>(Collections.singletonList(segment1)));
// Update partition metadata without refreshing should have no effect
- setSegmentZKMetadata(segment0, "Modulo", 4, 1);
+ setSegmentZKPartitionMetadata(segment0, "Modulo", 4, 1);
segmentPruner.onExternalViewChange(externalView, idealState, onlineSegments);
- assertEquals(segmentPruner.prune(brokerRequest1, Arrays.asList(segment0, segment1)),
- Arrays.asList(segment0, segment1));
- assertEquals(segmentPruner.prune(brokerRequest2, Arrays.asList(segment0, segment1)),
- Arrays.asList(segment0, segment1));
- assertEquals(segmentPruner.prune(brokerRequest3, Arrays.asList(segment0, segment1)),
- Collections.singletonList(segment1));
+ assertEquals(segmentPruner.prune(brokerRequest1, new HashSet<>(Arrays.asList(segment0, segment1))),
+ new HashSet<>(Arrays.asList(segment0, segment1)));
+ assertEquals(segmentPruner.prune(brokerRequest2, new HashSet<>(Arrays.asList(segment0, segment1))),
+ new HashSet<>(Arrays.asList(segment0, segment1)));
+ assertEquals(segmentPruner.prune(brokerRequest3, new HashSet<>(Arrays.asList(segment0, segment1))),
+ new HashSet<>(Collections.singletonList(segment1)));
// Refresh the changed segment should update the segment pruner
segmentPruner.refreshSegment(segment0);
- assertEquals(segmentPruner.prune(brokerRequest1, Arrays.asList(segment0, segment1)),
- Arrays.asList(segment0, segment1));
- assertEquals(segmentPruner.prune(brokerRequest2, Arrays.asList(segment0, segment1)),
- Collections.singletonList(segment1));
- assertEquals(segmentPruner.prune(brokerRequest3, Arrays.asList(segment0, segment1)),
- Arrays.asList(segment0, segment1));
+ assertEquals(segmentPruner.prune(brokerRequest1, new HashSet<>(Arrays.asList(segment0, segment1))),
+ new HashSet<>(Arrays.asList(segment0, segment1)));
+ assertEquals(segmentPruner.prune(brokerRequest2, new HashSet<>(Arrays.asList(segment0, segment1))),
+ new HashSet<>(Collections.singletonList(segment1)));
+ assertEquals(segmentPruner.prune(brokerRequest3, new HashSet<>(Arrays.asList(segment0, segment1))),
+ new HashSet<>(Arrays.asList(segment0, segment1)));
+ }
+
+ @Test
+ public void testTimeRangeSegmentPruner() {
+ Pql2Compiler compiler = new Pql2Compiler();
+ BrokerRequest brokerRequest1 = compiler.compileToBrokerRequest(QUERY_1);
+ BrokerRequest brokerRequest2 = compiler.compileToBrokerRequest(QUERY_5);
+ BrokerRequest brokerRequest3 = compiler.compileToBrokerRequest(QUERY_6);
+ BrokerRequest brokerRequest4 = compiler.compileToBrokerRequest(QUERY_7);
+ BrokerRequest brokerRequest5 = compiler.compileToBrokerRequest(QUERY_8);
+ BrokerRequest brokerRequest6 = compiler.compileToBrokerRequest(QUERY_9);
+ BrokerRequest brokerRequest7 = compiler.compileToBrokerRequest(QUERY_10);
Review comment:
Can we also add the test with parsing query with SQL?
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeSegmentPruner.java
##########
@@ -0,0 +1,340 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+ private final Map _segmentToTimeRangeMSCache;
+
+ public TimeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ _segmentToTimeRangeMSCache = new HashMap<String, Interval>();
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ synchronized public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ List<String> newSegments = new ArrayList<>();
+ for (String onlineSegment : onlineSegments) {
+ if (!_segmentToTimeRangeMSCache.containsKey(onlineSegment)) {
Review comment:
Are we covering the following case?
1.`segment_0` gets uploaded with `start_time=10, end_time=12`
2. There was an issue with the offline pipeline, we refresh the `segment_0` with `start_time=10, end_time=11`.
In this case, `_segmentToTimeRangeMSCache` needs to be updated properly with the new interval. Otherwise, our pruner result will be wrong. I think that the partition pruner also does not currently handle this issue. We should at least add the `TODO` comment to handle this in the future.
One possible approach is to add TTL expiration to the cache to make sure the interval eventually gets updated to the correct value.
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/intervalST/Interval.java
##########
@@ -0,0 +1,90 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner.intervalST;
+
+import com.google.common.base.Preconditions;
+import javax.validation.constraints.NotNull;
+
+
+/**
+ * The {@code Interval} class represents an one-dimensional closed interval which contains both ends.
+ */
+public class Interval implements Comparable<Interval> {
+ public final long _min;
+ public final long _max;
+
+ public Interval(long min, long max) {
+ Preconditions.checkState(min <= max, "invalid interval [{}, {}]", min, max);
+ _min = min;
+ _max = max;
+ }
+
+ public boolean intersects(@NotNull Interval that) {
+ return _max >= that._min && that._max >= _min;
+ }
+
+ @Override
+ public int compareTo(Interval that) {
+ Preconditions.checkNotNull(that, "Compare to invalid interval: null");
+ if (_min < that._min) {
+ return -1;
+ } else if (_min > that._min) {
+ return 1;
+ } else if (_max < that._max) {
+ return -1;
+ } else if (_max > that._max) {
+ return 1;
+ }
+ else return 0;
+ }
+
+ @Override
+ public int hashCode() {
+ return (int)(_min * 17 + _max);
+ }
+
+ @Override
+ public boolean equals(Object that) {
Review comment:
Is this intellij auto generated `equals()`? If not, let's use the one generated by intellij.
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/intervalST/Interval.java
##########
@@ -0,0 +1,90 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner.intervalST;
+
+import com.google.common.base.Preconditions;
+import javax.validation.constraints.NotNull;
+
+
+/**
+ * The {@code Interval} class represents an one-dimensional closed interval which contains both ends.
+ */
+public class Interval implements Comparable<Interval> {
+ public final long _min;
+ public final long _max;
+
+ public Interval(long min, long max) {
+ Preconditions.checkState(min <= max, "invalid interval [{}, {}]", min, max);
+ _min = min;
+ _max = max;
+ }
+
+ public boolean intersects(@NotNull Interval that) {
+ return _max >= that._min && that._max >= _min;
+ }
+
+ @Override
+ public int compareTo(Interval that) {
+ Preconditions.checkNotNull(that, "Compare to invalid interval: null");
+ if (_min < that._min) {
+ return -1;
+ } else if (_min > that._min) {
+ return 1;
+ } else if (_max < that._max) {
+ return -1;
+ } else if (_max > that._max) {
+ return 1;
+ }
+ else return 0;
+ }
+
+ @Override
+ public int hashCode() {
Review comment:
Is this autogenerated by intelij?
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] siddharthteotia commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
siddharthteotia commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r521868611
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeRangeSegmentPruner.java
##########
@@ -0,0 +1,348 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeRangeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeRangeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeRangeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+
+ public TimeRangeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ updateTimeRangeMSToSegmentSearchTree(onlineSegments);
+ }
+
+ private void updateTimeRangeMSToSegmentSearchTree(Set<String> onlineSegments) {
+ List<String> segments = new ArrayList<>(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ List<String> segmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: segments) {
+ segmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(segmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ List<Long> startTimes = new ArrayList<>();
+ List<Long> endTimes = new ArrayList<>();
+
+ for (int i = 0; i < segments.size(); i++) {
+ String segment = segments.get(i);
+
+ long[] range = extractStartEndTimeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ startTimes.add(range[0]);
+ endTimes.add(range[1]);
+ }
+
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(startTimes, endTimes, segments);
+ }
+
+
+ private long[] extractStartEndTimeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ long[] range = {MIN_START_TIME, MAX_END_TIME};
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ range[0] = timeUnit.toMillis(startTime);
+ range[1] = timeUnit.toMillis(endTime);
+ return range;
+ }
+
+ @Override
+ public void refreshSegment(String segment) {
+ Set<String> segments;
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ segments = new HashSet<>();
+ } else {
+ segments = _timeRangeMSToSegmentSearchTree.getAllValues();
+ }
+ if (!segment.contains(segment)) {
+ segments.add(segment);
+ }
+
+ updateTimeRangeMSToSegmentSearchTree(segments);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ return segments;
+ }
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> ranges = getFilterTimeRange(filterQueryTree);
+ if (ranges == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (ranges.size() == 0) { // invalid query time range
+ return Collections.emptySet();
+ }
+
+ Set<String> prunedSegments = new HashSet<>();
+ for (Interval range : ranges) {
+ Interval rangeMS = convertRangeToMS(range);
+ for (Object segment : _timeRangeMSToSegmentSearchTree.searchAll(rangeMS)) {
+ if (segments.contains(segment)) {
+ prunedSegments.add((String) segment);
+ }
+ }
+ }
+ return new HashSet<String>(prunedSegments);
+ }
+
+ private List<Interval> getFilterTimeRange(FilterQueryTree filterQueryTree) {
+ // return NUll if no time range info or cannot filter base on the info (e.g. 'SELECT * from myTable where time < 50 OR firstName = Jason')
+ // return an empty list if filtering range is specified but invalid (e.g. 'SELECT * from myTable where time < 50 AND time > 100')
+ switch (filterQueryTree.getOperator()) {
+ case AND:
+ List<List<Interval>> andRanges = new ArrayList<>();
Review comment:
I am not quite sure why list of list is needed here?
Each child operator under AND root will give you a list containing one or more intervals.
This is List<Interval> childRanges.
You can still maintain the result list as List<Interval> resultRanges and do the following inside for loop
```
for (FilterQueryTree child : filterQueryTree.getChildren()) {
List<Interval> childRanges = getFilterTimeRange(child);
if (childRanges != null) {
resultRanges.addAll(childRanges);
}
}
// do sorted merge of these intervals
return getIntersectionSortedRanges(resultIntervals);
```
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeRangeSegmentPruner.java
##########
@@ -0,0 +1,348 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeRangeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeRangeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeRangeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+
+ public TimeRangeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ updateTimeRangeMSToSegmentSearchTree(onlineSegments);
+ }
+
+ private void updateTimeRangeMSToSegmentSearchTree(Set<String> onlineSegments) {
+ List<String> segments = new ArrayList<>(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ List<String> segmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: segments) {
+ segmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(segmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ List<Long> startTimes = new ArrayList<>();
+ List<Long> endTimes = new ArrayList<>();
+
+ for (int i = 0; i < segments.size(); i++) {
+ String segment = segments.get(i);
+
+ long[] range = extractStartEndTimeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ startTimes.add(range[0]);
+ endTimes.add(range[1]);
+ }
+
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(startTimes, endTimes, segments);
+ }
+
+
+ private long[] extractStartEndTimeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ long[] range = {MIN_START_TIME, MAX_END_TIME};
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ range[0] = timeUnit.toMillis(startTime);
+ range[1] = timeUnit.toMillis(endTime);
+ return range;
+ }
+
+ @Override
+ public void refreshSegment(String segment) {
+ Set<String> segments;
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ segments = new HashSet<>();
+ } else {
+ segments = _timeRangeMSToSegmentSearchTree.getAllValues();
+ }
+ if (!segment.contains(segment)) {
+ segments.add(segment);
+ }
+
+ updateTimeRangeMSToSegmentSearchTree(segments);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ return segments;
+ }
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> ranges = getFilterTimeRange(filterQueryTree);
+ if (ranges == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (ranges.size() == 0) { // invalid query time range
+ return Collections.emptySet();
+ }
+
+ Set<String> prunedSegments = new HashSet<>();
+ for (Interval range : ranges) {
+ Interval rangeMS = convertRangeToMS(range);
+ for (Object segment : _timeRangeMSToSegmentSearchTree.searchAll(rangeMS)) {
+ if (segments.contains(segment)) {
+ prunedSegments.add((String) segment);
+ }
+ }
+ }
+ return new HashSet<String>(prunedSegments);
+ }
+
+ private List<Interval> getFilterTimeRange(FilterQueryTree filterQueryTree) {
+ // return NUll if no time range info or cannot filter base on the info (e.g. 'SELECT * from myTable where time < 50 OR firstName = Jason')
+ // return an empty list if filtering range is specified but invalid (e.g. 'SELECT * from myTable where time < 50 AND time > 100')
+ switch (filterQueryTree.getOperator()) {
+ case AND:
+ List<List<Interval>> andRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges != null) {
+ andRanges.add(childRanges);
+ }
+ }
+ return getIntersectionSortedRanges(andRanges);
+ case OR:
+ List<List<Interval>> orRanges = new ArrayList<>();
Review comment:
The list<list> comment above is applicable here as well
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeRangeSegmentPruner.java
##########
@@ -0,0 +1,348 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeRangeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeRangeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeRangeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+
+ public TimeRangeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ updateTimeRangeMSToSegmentSearchTree(onlineSegments);
+ }
+
+ private void updateTimeRangeMSToSegmentSearchTree(Set<String> onlineSegments) {
+ List<String> segments = new ArrayList<>(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ List<String> segmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: segments) {
+ segmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(segmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ List<Long> startTimes = new ArrayList<>();
+ List<Long> endTimes = new ArrayList<>();
+
+ for (int i = 0; i < segments.size(); i++) {
+ String segment = segments.get(i);
+
+ long[] range = extractStartEndTimeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ startTimes.add(range[0]);
+ endTimes.add(range[1]);
+ }
+
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(startTimes, endTimes, segments);
+ }
+
+
+ private long[] extractStartEndTimeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ long[] range = {MIN_START_TIME, MAX_END_TIME};
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ range[0] = timeUnit.toMillis(startTime);
+ range[1] = timeUnit.toMillis(endTime);
+ return range;
+ }
+
+ @Override
+ public void refreshSegment(String segment) {
+ Set<String> segments;
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ segments = new HashSet<>();
+ } else {
+ segments = _timeRangeMSToSegmentSearchTree.getAllValues();
+ }
+ if (!segment.contains(segment)) {
+ segments.add(segment);
+ }
+
+ updateTimeRangeMSToSegmentSearchTree(segments);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ return segments;
+ }
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> ranges = getFilterTimeRange(filterQueryTree);
+ if (ranges == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (ranges.size() == 0) { // invalid query time range
+ return Collections.emptySet();
+ }
+
+ Set<String> prunedSegments = new HashSet<>();
+ for (Interval range : ranges) {
+ Interval rangeMS = convertRangeToMS(range);
+ for (Object segment : _timeRangeMSToSegmentSearchTree.searchAll(rangeMS)) {
+ if (segments.contains(segment)) {
+ prunedSegments.add((String) segment);
+ }
+ }
+ }
+ return new HashSet<String>(prunedSegments);
+ }
+
+ private List<Interval> getFilterTimeRange(FilterQueryTree filterQueryTree) {
+ // return NUll if no time range info or cannot filter base on the info (e.g. 'SELECT * from myTable where time < 50 OR firstName = Jason')
+ // return an empty list if filtering range is specified but invalid (e.g. 'SELECT * from myTable where time < 50 AND time > 100')
+ switch (filterQueryTree.getOperator()) {
+ case AND:
+ List<List<Interval>> andRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges != null) {
+ andRanges.add(childRanges);
+ }
+ }
+ return getIntersectionSortedRanges(andRanges);
+ case OR:
+ List<List<Interval>> orRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges == null) {
+ return null;
+ } else {
+ orRanges.add(childRanges);
+ }
+ }
+ return getUnionSortedRanges(orRanges);
+ case EQUALITY:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ long timeStamp = Long.parseLong(filterQueryTree.getValue().get(0));
+ return Collections.singletonList(new Interval(timeStamp, timeStamp));
+ }
+ return null;
+ case RANGE:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ return parseRange(filterQueryTree.getValue());
+ }
+ return null;
+ default:
+ return null;
+ }
+ }
+
+ private Interval convertRangeToMS(Interval range) {
+ long min = range.min == MIN_START_TIME ? MIN_START_TIME : _timeUnit.toMillis(range.min);
+ long max = range.max == MAX_END_TIME ? MAX_END_TIME : _timeUnit.toMillis(range.max);
+ return new Interval(min, max);
+ }
+
+ private List<Interval> getIntersectionSortedRanges(List<List<Interval>> ranges) {
Review comment:
IIUC, this is sorted merge of intervals. Given a list of intervals, it returns a sorted (and disjoint) list of intervals. The algorithm can internally first sort on startTime and then merge as opposed to asking the caller to pass sorted intervals?
Secondly, I don't see where the input is sorted by the caller.
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] siddharthteotia commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
siddharthteotia commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r521868727
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeRangeSegmentPruner.java
##########
@@ -0,0 +1,348 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeRangeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeRangeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeRangeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+
+ public TimeRangeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ updateTimeRangeMSToSegmentSearchTree(onlineSegments);
+ }
+
+ private void updateTimeRangeMSToSegmentSearchTree(Set<String> onlineSegments) {
+ List<String> segments = new ArrayList<>(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ List<String> segmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: segments) {
+ segmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(segmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ List<Long> startTimes = new ArrayList<>();
+ List<Long> endTimes = new ArrayList<>();
+
+ for (int i = 0; i < segments.size(); i++) {
+ String segment = segments.get(i);
+
+ long[] range = extractStartEndTimeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ startTimes.add(range[0]);
+ endTimes.add(range[1]);
+ }
+
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(startTimes, endTimes, segments);
+ }
+
+
+ private long[] extractStartEndTimeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ long[] range = {MIN_START_TIME, MAX_END_TIME};
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ range[0] = timeUnit.toMillis(startTime);
+ range[1] = timeUnit.toMillis(endTime);
+ return range;
+ }
+
+ @Override
+ public void refreshSegment(String segment) {
+ Set<String> segments;
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ segments = new HashSet<>();
+ } else {
+ segments = _timeRangeMSToSegmentSearchTree.getAllValues();
+ }
+ if (!segment.contains(segment)) {
+ segments.add(segment);
+ }
+
+ updateTimeRangeMSToSegmentSearchTree(segments);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ return segments;
+ }
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> ranges = getFilterTimeRange(filterQueryTree);
+ if (ranges == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (ranges.size() == 0) { // invalid query time range
+ return Collections.emptySet();
+ }
+
+ Set<String> prunedSegments = new HashSet<>();
+ for (Interval range : ranges) {
+ Interval rangeMS = convertRangeToMS(range);
+ for (Object segment : _timeRangeMSToSegmentSearchTree.searchAll(rangeMS)) {
+ if (segments.contains(segment)) {
+ prunedSegments.add((String) segment);
+ }
+ }
+ }
+ return new HashSet<String>(prunedSegments);
+ }
+
+ private List<Interval> getFilterTimeRange(FilterQueryTree filterQueryTree) {
+ // return NUll if no time range info or cannot filter base on the info (e.g. 'SELECT * from myTable where time < 50 OR firstName = Jason')
+ // return an empty list if filtering range is specified but invalid (e.g. 'SELECT * from myTable where time < 50 AND time > 100')
+ switch (filterQueryTree.getOperator()) {
+ case AND:
+ List<List<Interval>> andRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges != null) {
+ andRanges.add(childRanges);
+ }
+ }
+ return getIntersectionSortedRanges(andRanges);
+ case OR:
+ List<List<Interval>> orRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges == null) {
+ return null;
+ } else {
+ orRanges.add(childRanges);
+ }
+ }
+ return getUnionSortedRanges(orRanges);
+ case EQUALITY:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ long timeStamp = Long.parseLong(filterQueryTree.getValue().get(0));
+ return Collections.singletonList(new Interval(timeStamp, timeStamp));
+ }
+ return null;
+ case RANGE:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ return parseRange(filterQueryTree.getValue());
+ }
+ return null;
+ default:
+ return null;
+ }
+ }
+
+ private Interval convertRangeToMS(Interval range) {
+ long min = range.min == MIN_START_TIME ? MIN_START_TIME : _timeUnit.toMillis(range.min);
+ long max = range.max == MAX_END_TIME ? MAX_END_TIME : _timeUnit.toMillis(range.max);
+ return new Interval(min, max);
+ }
+
+ private List<Interval> getIntersectionSortedRanges(List<List<Interval>> ranges) {
+ // Requires input ranges are sorted, the return ranges will be sorted
+ return getIntersectionSortedRanges(ranges, 0, ranges.size());
+ }
+
+ private List<Interval> getIntersectionSortedRanges(List<List<Interval>> ranges, int start, int end) {
Review comment:
I think this and the next method can be simplified into one method that works on List<Interval> ranges
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] siddharthteotia commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
siddharthteotia commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r521868067
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/PartitionSegmentPruner.java
##########
@@ -148,12 +149,12 @@ public synchronized void refreshSegment(String segment) {
}
@Override
- public List<String> prune(BrokerRequest brokerRequest, List<String> segments) {
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
Review comment:
Let's see if the pruner code can deal with set v/s list as opposed to changing the APIs across all pruner users.
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] Jackie-Jiang commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
Jackie-Jiang commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r523263996
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/intervalST/IntervalST.java
##########
@@ -0,0 +1,187 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner.intervalST;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+
+// A read-only interval search tree based on AVL Tree
+public class IntervalST<Value> {
+
+ private Node<Value> root;
+
+ public IntervalST(List<Long> mins, List<Long> maxs, List<Value> values) {
+ // read only once constructed
+ for (int i = 0; i < mins.size(); i++) {
+ insert(mins.get(i), maxs.get(i), values.get(i));
+ }
+ }
+
+ private void insert(long min, long max, Value value) {
+ root = insert(root, new Interval(min, max), value);
+ }
+
+ private Node insert(Node node, Interval interval, Value value) {
+ if (node == null) {
+ return new Node(interval, value);
+ }
+
+ int cmp = interval.compareTo(node.interval);
+ if (cmp == 0) {
+ node.valueList.add(value);
+ return node;
+ } else if (cmp < 0) {
+ node.left = insert(node.left, interval, value);
+ } else {
+ node.right = insert(node.right, interval, value);
+ }
+
+ fixAuxiliaryInfo(node);
+ int balance = getBalance(node);
+ // Balance current subtree
+ if (balance < -1) {
+ if (getBalance(node.right) > 0) {
+ node.right = rotateRight(node.right); // Right-left case
+ }
+ node = rotateLeft(node);
+ } else if (balance > 1) {
+ if (getBalance(node.left) < 0) {
+ node.left = rotateLeft(node.left); // Left-right case
+ }
+ node = rotateRight(node);
+ }
+ return node;
+ }
+
+ // Get all intervals which intersect with input range [min, max]
+ public List<Value> searchAll(long min, long max) {
+ return searchAll(new Interval(min, max));
+ }
+
+ public List<Value> searchAll(Interval interval) {
+ List<Value> list = new ArrayList<Value>();
+ searchAll(root, interval, list);
+ return list;
+ }
+
+ private boolean searchAll(Node<Value> node, Interval interval, List<Value> list) {
+ boolean foundRoot = false;
+ boolean foundLeft = false;
+ boolean foundRight = false;
+ if (node == null)
+ return false;
+ if (interval.intersects(node.interval)) {
+ list.addAll(node.valueList);
+ foundRoot = true;
+ }
+ if (node.left != null && node.left.max >= interval.min) {
+ foundLeft = searchAll(node.left, interval, list);
+ }
+
+ if (foundLeft || node.left == null || node.left.max < interval.min) {
+ // If node.left.max > interval.min but cannot find intersections on left subtree,
+ // then there won't be any intersections in right subtree, since the right most interval x
+ // in left subtree must have x.min > interval.max. All intervals in right subtree
+ // will have mins >= x.min, so there won't be any intersections.
+ foundRight = searchAll(node.right, interval, list);
+ }
+ return foundRoot || foundLeft || foundRight;
+ }
+
+ public Set<Value> getAllValues() {
+ Set<Value> values = new HashSet<>();
+ getAllValues(root, values);
+ return values;
+ }
+
+ private void getAllValues(Node<Value> node, Set<Value> values) {
+ if (node == null) {
+ return;
+ }
+ getAllValues(node.left, values);
+ values.addAll(node.valueList);
+ getAllValues(node.right, values);
+ }
+
+ private Node rotateRight(Node x) {
+ Node y = x.left;
+ x.left = y.right;
+ y.right = x;
+ fixAuxiliaryInfo(x);
+ fixAuxiliaryInfo(y);
+ return y;
+ }
+
+ private Node rotateLeft(Node x) {
+ Node y = x.right;
+ x.right = y.left;
+ y.left = x;
+ fixAuxiliaryInfo(x);
+ fixAuxiliaryInfo(y);
+ return y;
+ }
+
+ private int getBalance(Node node) {
+ if (node == null) {
+ return 0;
+ }
+ return height(node.left) - height(node.right);
+ }
+
+ private int height(Node node) {
+ if (node == null) {
+ return 0;
+ }
+ return node.height;
+ }
+
+ private long max(Node node) {
+ if (node == null) {
+ return Long.MIN_VALUE;
+ }
+ return node.max;
+ }
+
+ // fix auxiliary information
+ private void fixAuxiliaryInfo(Node node) {
+ if (node == null) return;
+ node.height = 1 + Math.max(height(node.left), height(node.right));
+ node.max = Math.max(max(node.left), max(node.right));
+ node.max = Math.max(node.max, node.interval.max);
+ }
+
+ private static class Node<Value> {
+ final Interval interval; // key
+ List<Value> valueList;
+ Node<Value> left, right;
Review comment:
Make this declaration into 2 lines
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] jtao15 commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
jtao15 commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r522554604
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeRangeSegmentPruner.java
##########
@@ -0,0 +1,348 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeRangeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeRangeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeRangeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+
+ public TimeRangeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ updateTimeRangeMSToSegmentSearchTree(onlineSegments);
+ }
+
+ private void updateTimeRangeMSToSegmentSearchTree(Set<String> onlineSegments) {
+ List<String> segments = new ArrayList<>(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ List<String> segmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: segments) {
+ segmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(segmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ List<Long> startTimes = new ArrayList<>();
+ List<Long> endTimes = new ArrayList<>();
+
+ for (int i = 0; i < segments.size(); i++) {
+ String segment = segments.get(i);
+
+ long[] range = extractStartEndTimeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ startTimes.add(range[0]);
+ endTimes.add(range[1]);
+ }
+
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(startTimes, endTimes, segments);
+ }
+
+
+ private long[] extractStartEndTimeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ long[] range = {MIN_START_TIME, MAX_END_TIME};
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ range[0] = timeUnit.toMillis(startTime);
+ range[1] = timeUnit.toMillis(endTime);
+ return range;
+ }
+
+ @Override
+ public void refreshSegment(String segment) {
+ Set<String> segments;
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ segments = new HashSet<>();
+ } else {
+ segments = _timeRangeMSToSegmentSearchTree.getAllValues();
+ }
+ if (!segment.contains(segment)) {
+ segments.add(segment);
+ }
+
+ updateTimeRangeMSToSegmentSearchTree(segments);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
Review comment:
The worst case would be no segments share the same time range, so # time ranges would be the same as N in this case. Searching 1 intersected range will take O(logN) time, and get all results will take O(M*logN)
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org
[GitHub] [incubator-pinot] siddharthteotia commented on a change in pull request #6259: Broker time range pruning(#6189)
Posted by GitBox <gi...@apache.org>.
siddharthteotia commented on a change in pull request #6259:
URL: https://github.com/apache/incubator-pinot/pull/6259#discussion_r522587910
##########
File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpruner/TimeRangeSegmentPruner.java
##########
@@ -0,0 +1,348 @@
+/**
+ * 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.pinot.broker.routing.segmentpruner;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.IdealState;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.Interval;
+import org.apache.pinot.broker.routing.segmentpruner.intervalST.IntervalST;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.request.FilterQueryTree;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.data.DateTimeFieldSpec;
+import org.apache.pinot.spi.data.DateTimeFormatSpec;
+import org.apache.pinot.spi.data.Schema;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code TimeRangeSegmentPruner} prunes segments based on their time column start & end time metadata stored in ZK. The pruner
+ * supports queries with filter (or nested filter) of EQUALITY and RANGE predicates.
+ */
+public class TimeRangeSegmentPruner implements SegmentPruner {
+ private static final Logger LOGGER = LoggerFactory.getLogger(TimeRangeSegmentPruner.class);
+ private static final long MAX_END_TIME = Long.MAX_VALUE;
+ private static final long MIN_START_TIME = 0;
+
+ private final String _tableNameWithType;
+ private final ZkHelixPropertyStore _propertyStore;
+ private final String _segmentZKMetadataPathPrefix;
+ private final String _timeColumn;
+ private final TimeUnit _timeUnit;
+
+ private volatile IntervalST _timeRangeMSToSegmentSearchTree;
+
+ public TimeRangeSegmentPruner(TableConfig tableConfig, ZkHelixPropertyStore<ZNRecord> propertyStore) {
+ _tableNameWithType = tableConfig.getTableName();
+ _propertyStore = propertyStore;
+ _segmentZKMetadataPathPrefix = ZKMetadataProvider.constructPropertyStorePathForResource(_tableNameWithType) + "/";
+ _timeColumn = tableConfig.getValidationConfig().getTimeColumnName();
+ Preconditions
+ .checkNotNull(_timeColumn, "Time column must be configured in table config for table: %s", _tableNameWithType);
+
+ Schema schema = ZKMetadataProvider.getTableSchema(_propertyStore, _tableNameWithType);
+ Preconditions.checkState(schema != null, "Failed to find schema for table: %s", _tableNameWithType);
+ DateTimeFieldSpec dateTimeSpec = schema.getSpecForTimeColumn(_timeColumn);
+ Preconditions.checkNotNull(dateTimeSpec, "Field spec must be specified in schema for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ DateTimeFormatSpec formatSpec = new DateTimeFormatSpec(dateTimeSpec.getFormat());
+ _timeUnit = formatSpec.getColumnUnit();
+ Preconditions
+ .checkNotNull(_timeUnit, "Time unit must be configured in the field spec for time column: %s of table: %s",
+ _timeColumn, _tableNameWithType);
+ }
+
+ @Override
+ public void init(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ onExternalViewChange(externalView, idealState, onlineSegments);
+ }
+
+ @Override
+ public void onExternalViewChange(ExternalView externalView, IdealState idealState, Set<String> onlineSegments) {
+ updateTimeRangeMSToSegmentSearchTree(onlineSegments);
+ }
+
+ private void updateTimeRangeMSToSegmentSearchTree(Set<String> onlineSegments) {
+ List<String> segments = new ArrayList<>(onlineSegments);
+ // atomic swap _timeRangeToSegmentMap for input online segments
+ List<String> segmentZKMetadataPaths = new ArrayList<>();
+ for (String segment: segments) {
+ segmentZKMetadataPaths.add(_segmentZKMetadataPathPrefix + segment);
+ }
+
+ List<ZNRecord> znRecords = _propertyStore.get(segmentZKMetadataPaths, null, AccessOption.PERSISTENT, true);
+
+ List<Long> startTimes = new ArrayList<>();
+ List<Long> endTimes = new ArrayList<>();
+
+ for (int i = 0; i < segments.size(); i++) {
+ String segment = segments.get(i);
+
+ long[] range = extractStartEndTimeMSFromSegmentZKMetaZNRecord(segment, znRecords.get(i));
+ startTimes.add(range[0]);
+ endTimes.add(range[1]);
+ }
+
+ _timeRangeMSToSegmentSearchTree = new IntervalST<String>(startTimes, endTimes, segments);
+ }
+
+
+ private long[] extractStartEndTimeMSFromSegmentZKMetaZNRecord(String segment, @Nullable ZNRecord znRecord) {
+ long[] range = {MIN_START_TIME, MAX_END_TIME};
+ // Segments without metadata or with invalid time range will be set with [min_start, max_end] and will not be pruned
+ if (znRecord == null) {
+ LOGGER.warn("Failed to find segment ZK metadata for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ long startTime = znRecord.getLongField(CommonConstants.Segment.START_TIME, -1);
+ long endTime = znRecord.getLongField(CommonConstants.Segment.END_TIME, -1);
+ if (startTime < 0 || endTime < 0 || startTime > endTime) {
+ LOGGER.warn("Failed to find valid end time for segment: {}, table: {}", segment, _tableNameWithType);
+ return range;
+ }
+
+ TimeUnit timeUnit = znRecord.getEnumField(CommonConstants.Segment.TIME_UNIT, TimeUnit.class, TimeUnit.DAYS);
+ range[0] = timeUnit.toMillis(startTime);
+ range[1] = timeUnit.toMillis(endTime);
+ return range;
+ }
+
+ @Override
+ public void refreshSegment(String segment) {
+ Set<String> segments;
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ segments = new HashSet<>();
+ } else {
+ segments = _timeRangeMSToSegmentSearchTree.getAllValues();
+ }
+ if (!segment.contains(segment)) {
+ segments.add(segment);
+ }
+
+ updateTimeRangeMSToSegmentSearchTree(segments);
+ }
+
+ /**
+ * NOTE: Pruning is done by searching _timeRangeToSegmentSearchTree based on request time range and check if the results
+ * are in the input segments. By doing so we will have run time O(M * logN) (N is the # of all online segments,
+ * M is the # of qualified intersected segments).
+ */
+ @Override
+ public Set<String> prune(BrokerRequest brokerRequest, Set<String> segments) {
+ // The pruned order may be different from the input order
+ if (_timeRangeMSToSegmentSearchTree == null) {
+ return segments;
+ }
+ FilterQueryTree filterQueryTree = RequestUtils.generateFilterQueryTree(brokerRequest);
+ if (filterQueryTree == null) {
+ return segments;
+ }
+ List<Interval> ranges = getFilterTimeRange(filterQueryTree);
+ if (ranges == null) { // cannot prune based on time for input request
+ return segments;
+ }
+ if (ranges.size() == 0) { // invalid query time range
+ return Collections.emptySet();
+ }
+
+ Set<String> prunedSegments = new HashSet<>();
+ for (Interval range : ranges) {
+ Interval rangeMS = convertRangeToMS(range);
+ for (Object segment : _timeRangeMSToSegmentSearchTree.searchAll(rangeMS)) {
+ if (segments.contains(segment)) {
+ prunedSegments.add((String) segment);
+ }
+ }
+ }
+ return new HashSet<String>(prunedSegments);
+ }
+
+ private List<Interval> getFilterTimeRange(FilterQueryTree filterQueryTree) {
+ // return NUll if no time range info or cannot filter base on the info (e.g. 'SELECT * from myTable where time < 50 OR firstName = Jason')
+ // return an empty list if filtering range is specified but invalid (e.g. 'SELECT * from myTable where time < 50 AND time > 100')
+ switch (filterQueryTree.getOperator()) {
+ case AND:
+ List<List<Interval>> andRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges != null) {
+ andRanges.add(childRanges);
+ }
+ }
+ return getIntersectionSortedRanges(andRanges);
+ case OR:
+ List<List<Interval>> orRanges = new ArrayList<>();
+ for (FilterQueryTree child : filterQueryTree.getChildren()) {
+ List<Interval> childRanges = getFilterTimeRange(child);
+ if (childRanges == null) {
+ return null;
+ } else {
+ orRanges.add(childRanges);
+ }
+ }
+ return getUnionSortedRanges(orRanges);
+ case EQUALITY:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ long timeStamp = Long.parseLong(filterQueryTree.getValue().get(0));
+ return Collections.singletonList(new Interval(timeStamp, timeStamp));
+ }
+ return null;
+ case RANGE:
+ if (filterQueryTree.getColumn().equals(_timeColumn)) {
+ return parseRange(filterQueryTree.getValue());
+ }
+ return null;
+ default:
+ return null;
+ }
+ }
+
+ private Interval convertRangeToMS(Interval range) {
+ long min = range.min == MIN_START_TIME ? MIN_START_TIME : _timeUnit.toMillis(range.min);
+ long max = range.max == MAX_END_TIME ? MAX_END_TIME : _timeUnit.toMillis(range.max);
+ return new Interval(min, max);
+ }
+
+ private List<Interval> getIntersectionSortedRanges(List<List<Interval>> ranges) {
Review comment:
Consider the simple case of an AND tree with 2 immediate leaves
When the recursion returns to AND (end of for loop), it will have a list with 2 intervals (one from each child). How do we guarantee that they are already sorted?
----------------------------------------------------------------
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org