deemoliu commented on a change in pull request #6899: URL: https://github.com/apache/incubator-pinot/pull/6899#discussion_r654042298
########## File path: pinot-segment-local/src/test/java/org/apache/pinot/segment/local/upsert/PartialUpsertHandlerTest.java ########## @@ -0,0 +1,81 @@ +/** + * 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.segment.local.upsert; + +import java.util.HashMap; +import java.util.Map; +import org.apache.helix.HelixManager; +import org.apache.pinot.spi.config.table.UpsertConfig; +import org.apache.pinot.spi.data.readers.GenericRow; +import org.mockito.Mockito; +import org.testng.annotations.Test; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; + + +public class PartialUpsertHandlerTest { + + @Test + public void testMerge() { + HelixManager helixManager = Mockito.mock(HelixManager.class); + String realtimeTableName = "testTable_REALTIME"; + Map<String, UpsertConfig.Strategy> partialUpsertStrategies = new HashMap<>(); + partialUpsertStrategies.put("field1", UpsertConfig.Strategy.INCREMENT); Review comment: @chenboat Current mergers are relatively simple, and null value handling logic are moved to handler part. the merger logic is covered in the handler test https://github.com/apache/incubator-pinot/pull/6899/commits/ec409cb739ffbe42b424003596cf9443a31d8ebf ########## File path: pinot-segment-local/src/main/java/org/apache/pinot/segment/local/indexsegment/mutable/MutableSegmentImpl.java ########## @@ -470,28 +466,32 @@ public void addExtraColumns(Schema newSchema) { @Override public boolean index(GenericRow row, @Nullable RowMetadata rowMetadata) throws IOException { - // Update dictionary first - updateDictionary(row); - - // If metrics aggregation is enabled and if the dimension values were already seen, this will return existing docId, - // else this will return a new docId. - int docId = getOrCreateDocId(); - boolean canTakeMore; - if (docId == _numDocsIndexed) { - // New row + if (isUpsertEnabled()) { + row = handleUpsert(row, _numDocsIndexed); + + updateDictionary(row); addNewRow(row); // Update number of documents indexed at last to make the latest row queryable canTakeMore = _numDocsIndexed++ < _capacity; - - if (isUpsertEnabled()) { - handleUpsert(row, docId); - } } else { - Preconditions.checkArgument(!isUpsertEnabled(), "metrics aggregation cannot be used with upsert"); - assert _aggregateMetrics; - aggregateMetrics(row, docId); - canTakeMore = true; + // Update dictionary first + updateDictionary(row); + + // If metrics aggregation is enabled and if the dimension values were already seen, this will return existing Review comment: gotcha, I can leave the comment here, and add some javadoc for getOrCreateDocId() as well. ########## File path: pinot-segment-local/src/main/java/org/apache/pinot/segment/local/upsert/PartialUpsertHandler.java ########## @@ -0,0 +1,141 @@ +/** + * 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.segment.local.upsert; + +import java.util.HashMap; +import java.util.Map; +import org.apache.helix.HelixDataAccessor; +import org.apache.helix.HelixManager; +import org.apache.helix.PropertyKey; +import org.apache.helix.model.CurrentState; +import org.apache.helix.model.IdealState; +import org.apache.helix.model.LiveInstance; +import org.apache.pinot.segment.local.upsert.merger.PartialUpsertMerger; +import org.apache.pinot.segment.local.upsert.merger.PartialUpsertMergerFactory; +import org.apache.pinot.spi.config.table.UpsertConfig; +import org.apache.pinot.spi.data.readers.GenericRow; +import org.apache.pinot.spi.utils.CommonConstants.Helix.StateModel.SegmentStateModel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/** + * Handler for partial-upsert. + */ +public class PartialUpsertHandler { + private static final Logger LOGGER = LoggerFactory.getLogger(PartialUpsertHandler.class); + + private final Map<String, PartialUpsertMerger> _mergers = new HashMap<>(); + + private final HelixManager _helixManager; + private final String _tableNameWithType; + private boolean _allSegmentsLoaded; + + public PartialUpsertHandler(HelixManager helixManager, String tableNameWithType, + Map<String, UpsertConfig.Strategy> partialUpsertStrategies) { + _helixManager = helixManager; + _tableNameWithType = tableNameWithType; + for (Map.Entry<String, UpsertConfig.Strategy> entry : partialUpsertStrategies.entrySet()) { + _mergers.put(entry.getKey(), PartialUpsertMergerFactory.getMerger(entry.getValue())); + } + } + + /** + * Returns {@code true} if all segments assigned to the current instance are loaded, {@code false} otherwise. + * Consuming segment should perform this check to ensure all previous records are loaded before inserting new records. + */ + public synchronized boolean isAllSegmentsLoaded() { + if (_allSegmentsLoaded) { + return true; + } + + HelixDataAccessor dataAccessor = _helixManager.getHelixDataAccessor(); + PropertyKey.Builder keyBuilder = dataAccessor.keyBuilder(); + IdealState idealState = dataAccessor.getProperty(keyBuilder.idealStates(_tableNameWithType)); + if (idealState == null) { + LOGGER.warn("Failed to find ideal state for table: {}", _tableNameWithType); + return false; + } + String instanceName = _helixManager.getInstanceName(); + LiveInstance liveInstance = dataAccessor.getProperty(keyBuilder.liveInstance(instanceName)); + if (liveInstance == null) { + LOGGER.warn("Failed to find live instance for instance: {}", instanceName); + return false; + } + String sessionId = liveInstance.getEphemeralOwner(); + CurrentState currentState = + dataAccessor.getProperty(keyBuilder.currentState(instanceName, sessionId, _tableNameWithType)); + if (currentState == null) { + LOGGER.warn("Failed to find current state for instance: {}, sessionId: {}, table: {}", instanceName, sessionId, + _tableNameWithType); + return false; + } + + // Check if ideal state and current state matches for all segments assigned to the current instance + Map<String, Map<String, String>> idealStatesMap = idealState.getRecord().getMapFields(); + Map<String, String> currentStateMap = currentState.getPartitionStateMap(); + for (Map.Entry<String, Map<String, String>> entry : idealStatesMap.entrySet()) { + String segmentName = entry.getKey(); + Map<String, String> instanceStateMap = entry.getValue(); + String expectedState = instanceStateMap.get(instanceName); + // Only track ONLINE segments assigned to the current instance + if (!SegmentStateModel.ONLINE.equals(expectedState)) { + continue; + } + String actualState = currentStateMap.get(segmentName); + if (!SegmentStateModel.ONLINE.equals(actualState)) { + if (SegmentStateModel.ERROR.equals(actualState)) { + LOGGER + .error("Find ERROR segment: {}, table: {}, expected: {}", segmentName, _tableNameWithType, expectedState); + } else { + LOGGER.info("Find unloaded segment: {}, table: {}, expected: {}, actual: {}", segmentName, _tableNameWithType, + expectedState, actualState); + } + return false; + } + } + + LOGGER.info("All segments loaded for table: {}", _tableNameWithType); + _allSegmentsLoaded = true; + return true; + } + + /** + * Merges 2 records and returns the merged record. + * + * @param previousRecord the last derived full record during ingestion. + * @param newRecord the new consumed record. + * @return a new row after merge + */ + public GenericRow merge(GenericRow previousRecord, GenericRow newRecord) { + for (Map.Entry<String, PartialUpsertMerger> entry : _mergers.entrySet()) { + String column = entry.getKey(); + if (!previousRecord.isNullValue(column)) { Review comment: @chenboat after discuss with @Jackie-Jiang and @yupeng9 we finalized to update merge interface from merge(row1, row2) to merge (value1, value2). With this change null value handling is moved to the handler and removed duplicated null value handling code in the mergers. -- 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: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
