wuchong commented on a change in pull request #8109: [FLINK-12017][table-planner-blink] Support translation from Rank/Deduplicate to StreamTransformation URL: https://github.com/apache/flink/pull/8109#discussion_r275106961
########## File path: flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/rank/AppendRankFunction.java ########## @@ -0,0 +1,228 @@ +/* + * 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.flink.table.runtime.rank; + +import org.apache.flink.api.common.ExecutionConfig; +import org.apache.flink.api.common.state.MapState; +import org.apache.flink.api.common.state.MapStateDescriptor; +import org.apache.flink.api.common.typeutils.TypeSerializer; +import org.apache.flink.api.java.typeutils.ListTypeInfo; +import org.apache.flink.configuration.Configuration; +import org.apache.flink.table.dataformat.BaseRow; +import org.apache.flink.table.generated.GeneratedRecordComparator; +import org.apache.flink.table.generated.GeneratedRecordEqualiser; +import org.apache.flink.table.runtime.keyselector.BaseRowKeySelector; +import org.apache.flink.table.runtime.util.LRUMap; +import org.apache.flink.table.typeutils.BaseRowTypeInfo; +import org.apache.flink.util.Collector; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; + +/** + * AppendRankFunction's input stream only contains append record. + */ +public class AppendRankFunction extends AbstractRankFunction { + + private static final long serialVersionUID = -4708453213104128010L; + + private static final Logger LOG = LoggerFactory.getLogger(AppendRankFunction.class); + + private final BaseRowTypeInfo sortKeyType; + private final TypeSerializer<BaseRow> inputRowSer; + private final long cacheSize; + + // a map state stores mapping from sort key to records list which is in topN + private transient MapState<BaseRow, List<BaseRow>> dataState; + + // the buffer stores mapping from sort key to records list, a heap mirror to dataState + private transient TopNBuffer buffer; + + // the kvSortedMap stores mapping from partition key to it's buffer + private transient Map<BaseRow, TopNBuffer> kvSortedMap; + + public AppendRankFunction(long minRetentionTime, long maxRetentionTime, BaseRowTypeInfo inputRowType, + GeneratedRecordComparator sortKeyGeneratedRecordComparator, BaseRowKeySelector sortKeySelector, + RankType rankType, RankRange rankRange, GeneratedRecordEqualiser generatedEqualiser, + boolean generateRetraction, boolean outputRankNumber, long cacheSize) { + super(minRetentionTime, maxRetentionTime, inputRowType, sortKeyGeneratedRecordComparator, sortKeySelector, + rankType, rankRange, generatedEqualiser, generateRetraction, outputRankNumber); + this.sortKeyType = sortKeySelector.getProducedType(); + this.inputRowSer = inputRowType.createSerializer(new ExecutionConfig()); + this.cacheSize = cacheSize; + } + + public void open(Configuration parameters) throws Exception { + super.open(parameters); + int lruCacheSize = Math.max(1, (int) (cacheSize / getDefaultTopNSize())); + kvSortedMap = new LRUMap<>(lruCacheSize); + LOG.info("Top{} operator is using LRU caches key-size: {}", getDefaultTopNSize(), lruCacheSize); + + ListTypeInfo<BaseRow> valueTypeInfo = new ListTypeInfo<>(inputRowType); + MapStateDescriptor<BaseRow, List<BaseRow>> mapStateDescriptor = new MapStateDescriptor( + "data-state-with-append", sortKeyType, valueTypeInfo); + dataState = getRuntimeContext().getMapState(mapStateDescriptor); + + // metrics + registerMetric(kvSortedMap.size() * getDefaultTopNSize()); + } + + @Override + public void processElement(BaseRow input, Context context, Collector<BaseRow> out) throws Exception { + long currentTime = context.timerService().currentProcessingTime(); + // register state-cleanup timer + registerProcessingCleanupTimer(context, currentTime); + + initHeapStates(); + initRankEnd(input); + + BaseRow sortKey = sortKeySelector.getKey(input); + // check whether the sortKey is in the topN range + if (checkSortKeyInBufferRange(sortKey, buffer)) { + // insert sort key into buffer + buffer.put(sortKey, inputRowSer.copy(input)); + Collection<BaseRow> inputs = buffer.get(sortKey); + // update data state + dataState.put(sortKey, (List<BaseRow>) inputs); + if (outputRankNumber || hasOffset()) { + // the without-number-algorithm can't handle topN with offset, + // so use the with-number-algorithm to handle offset + processElementWithRowNumber(sortKey, input, out); + } else { + processElementWithoutRowNumber(input, out); + } + } + } + + @Override + public void onTimer( + long timestamp, + OnTimerContext ctx, + Collector<BaseRow> out) throws Exception { + if (stateCleaningEnabled) { + // cleanup cache + kvSortedMap.remove(keyContext.getCurrentKey()); + cleanupState(dataState); + } + } + + @Override + protected long getMaxSizeOfBuffer() { Review comment: This method is introduced in `ApproximateRank` and I don't think we need this anymore. We can use `getDefaultTopNSize()` instead of this method is invoked. ---------------------------------------------------------------- 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: us...@infra.apache.org With regards, Apache Git Services