Search in sources :

Example 96 with GenericKey

use of io.confluent.ksql.GenericKey in project ksql by confluentinc.

the class KsMaterializedWindowTableIQv2 method get.

public KsMaterializedQueryResult<WindowedRow> get(final int partition, final Range<Instant> windowStartBounds, final Range<Instant> windowEndBounds, final Optional<Position> position) {
    try {
        final Instant lower = calculateLowerBound(windowStartBounds, windowEndBounds);
        final Instant upper = calculateUpperBound(windowStartBounds, windowEndBounds);
        final WindowRangeQuery<GenericKey, ValueAndTimestamp<GenericRow>> query = WindowRangeQuery.withWindowStartRange(lower, upper);
        StateQueryRequest<KeyValueIterator<Windowed<GenericKey>, ValueAndTimestamp<GenericRow>>> request = inStore(stateStore.getStateStoreName()).withQuery(query);
        if (position.isPresent()) {
            request = request.withPositionBound(PositionBound.at(position.get()));
        }
        final StateQueryResult<KeyValueIterator<Windowed<GenericKey>, ValueAndTimestamp<GenericRow>>> result = stateStore.getKafkaStreams().query(request);
        final QueryResult<KeyValueIterator<Windowed<GenericKey>, ValueAndTimestamp<GenericRow>>> queryResult = result.getPartitionResults().get(partition);
        if (queryResult.isFailure()) {
            throw failedQueryException(queryResult);
        }
        final KeyValueIterator<Windowed<GenericKey>, ValueAndTimestamp<GenericRow>> iterator = queryResult.getResult();
        return KsMaterializedQueryResult.rowIteratorWithPosition(Streams.stream(IteratorUtil.onComplete(iterator, iterator::close)).map(next -> {
            final Instant windowStart = next.key.window().startTime();
            if (!windowStartBounds.contains(windowStart)) {
                return null;
            }
            final Instant windowEnd = next.key.window().endTime();
            if (!windowEndBounds.contains(windowEnd)) {
                return null;
            }
            final TimeWindow window = new TimeWindow(windowStart.toEpochMilli(), windowEnd.toEpochMilli());
            final WindowedRow row = WindowedRow.of(stateStore.schema(), new Windowed<>(next.key.key(), window), next.value.value(), next.value.timestamp());
            return row;
        }).filter(Objects::nonNull).iterator(), queryResult.getPosition());
    } catch (final NotUpToBoundException | MaterializationException e) {
        throw e;
    } catch (final Exception e) {
        throw new MaterializationException("Failed to get value from materialized table", e);
    }
}
Also used : WindowKeyQuery(org.apache.kafka.streams.query.WindowKeyQuery) StateQueryRequest.inStore(org.apache.kafka.streams.query.StateQueryRequest.inStore) MaterializationException(io.confluent.ksql.execution.streams.materialization.MaterializationException) PositionBound(org.apache.kafka.streams.query.PositionBound) WindowRangeQuery(org.apache.kafka.streams.query.WindowRangeQuery) ValueAndTimestamp(org.apache.kafka.streams.state.ValueAndTimestamp) StateQueryRequest(org.apache.kafka.streams.query.StateQueryRequest) IteratorUtil(io.confluent.ksql.util.IteratorUtil) ImmutableList(com.google.common.collect.ImmutableList) WindowedRow(io.confluent.ksql.execution.streams.materialization.WindowedRow) Windowed(org.apache.kafka.streams.kstream.Windowed) Duration(java.time.Duration) QueryResult(org.apache.kafka.streams.query.QueryResult) Position(org.apache.kafka.streams.query.Position) Range(com.google.common.collect.Range) KeyValue(org.apache.kafka.streams.KeyValue) FailureReason(org.apache.kafka.streams.query.FailureReason) MaterializedWindowedTable(io.confluent.ksql.execution.streams.materialization.MaterializedWindowedTable) Streams(com.google.common.collect.Streams) Instant(java.time.Instant) StreamsMaterializedWindowedTable(io.confluent.ksql.execution.streams.materialization.StreamsMaterializedWindowedTable) Objects(java.util.Objects) KeyValueIterator(org.apache.kafka.streams.state.KeyValueIterator) StateQueryResult(org.apache.kafka.streams.query.StateQueryResult) WindowStoreIterator(org.apache.kafka.streams.state.WindowStoreIterator) GenericRow(io.confluent.ksql.GenericRow) Optional(java.util.Optional) GenericKey(io.confluent.ksql.GenericKey) KafkaStreams(org.apache.kafka.streams.KafkaStreams) Builder(com.google.common.collect.ImmutableList.Builder) TimeWindow(org.apache.kafka.streams.kstream.internals.TimeWindow) Collections(java.util.Collections) Instant(java.time.Instant) TimeWindow(org.apache.kafka.streams.kstream.internals.TimeWindow) MaterializationException(io.confluent.ksql.execution.streams.materialization.MaterializationException) MaterializationException(io.confluent.ksql.execution.streams.materialization.MaterializationException) ValueAndTimestamp(org.apache.kafka.streams.state.ValueAndTimestamp) GenericRow(io.confluent.ksql.GenericRow) Windowed(org.apache.kafka.streams.kstream.Windowed) KeyValueIterator(org.apache.kafka.streams.state.KeyValueIterator) Objects(java.util.Objects) GenericKey(io.confluent.ksql.GenericKey) WindowedRow(io.confluent.ksql.execution.streams.materialization.WindowedRow)

Example 97 with GenericKey

use of io.confluent.ksql.GenericKey in project ksql by confluentinc.

the class KsqlMaterialization method getIntermediateRow.

/*
   Today, we are unconditionally adding the extra fields to windowed rows.
   We should decide if we need these additional fields for the
   Windowed Rows case and remove them if possible.
   */
public static GenericRow getIntermediateRow(final TableRow row) {
    final GenericKey key = row.key();
    final GenericRow value = row.value();
    final List<?> keyFields = key.values();
    value.ensureAdditionalCapacity(// ROWTIME
    1 + // all the keys
    keyFields.size() + // windows
    row.window().map(w -> 2).orElse(0));
    value.append(row.rowTime());
    value.appendAll(keyFields);
    row.window().ifPresent(window -> {
        value.append(window.start().toEpochMilli());
        value.append(window.end().toEpochMilli());
    });
    return value;
}
Also used : GenericRow(io.confluent.ksql.GenericRow) KsqlProcessingContext(io.confluent.ksql.execution.transform.KsqlProcessingContext) Iterator(java.util.Iterator) Position(org.apache.kafka.streams.query.Position) Range(com.google.common.collect.Range) Streams(com.google.common.collect.Streams) KsMaterializedQueryResult(io.confluent.ksql.execution.streams.materialization.ks.KsMaterializedQueryResult) Instant(java.time.Instant) LogicalSchema(io.confluent.ksql.schema.ksql.LogicalSchema) Objects(java.util.Objects) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) GenericRow(io.confluent.ksql.GenericRow) ConsistencyOffsetVector(io.confluent.ksql.util.ConsistencyOffsetVector) Objects.requireNonNull(java.util.Objects.requireNonNull) WindowType(io.confluent.ksql.model.WindowType) ConsistencyUtil(io.confluent.ksql.util.ConsistencyUtil) Optional(java.util.Optional) GenericKey(io.confluent.ksql.GenericKey) Builder(com.google.common.collect.ImmutableList.Builder) GenericKey(io.confluent.ksql.GenericKey)

Example 98 with GenericKey

use of io.confluent.ksql.GenericKey in project ksql by confluentinc.

the class StreamGroupByBuilderBase method build.

public KGroupedStreamHolder build(final KStreamHolder<GenericKey> stream, final StreamGroupByKey step) {
    final LogicalSchema sourceSchema = stream.getSchema();
    final QueryContext queryContext = step.getProperties().getQueryContext();
    final Formats formats = step.getInternalFormats();
    final Grouped<GenericKey, GenericRow> grouped = buildGrouped(formats, sourceSchema, queryContext, buildContext, groupedFactory);
    return KGroupedStreamHolder.of(stream.getStream().groupByKey(grouped), stream.getSchema());
}
Also used : GenericRow(io.confluent.ksql.GenericRow) LogicalSchema(io.confluent.ksql.schema.ksql.LogicalSchema) QueryContext(io.confluent.ksql.execution.context.QueryContext) Formats(io.confluent.ksql.execution.plan.Formats) GenericKey(io.confluent.ksql.GenericKey)

Example 99 with GenericKey

use of io.confluent.ksql.GenericKey in project ksql by confluentinc.

the class StreamGroupByBuilderBase method build.

public <K> KGroupedStreamHolder build(final KStreamHolder<K> stream, final QueryContext queryContext, final Formats formats, final List<Expression> groupByExpressions) {
    final LogicalSchema sourceSchema = stream.getSchema();
    final List<CompiledExpression> groupBy = CodeGenRunner.compileExpressions(groupByExpressions.stream(), "Group By", sourceSchema, buildContext.getKsqlConfig(), buildContext.getFunctionRegistry());
    final ProcessingLogger logger = buildContext.getProcessingLogger(queryContext);
    final GroupByParams params = paramsFactory.build(sourceSchema, groupBy, logger);
    final Grouped<GenericKey, GenericRow> grouped = buildGrouped(formats, params.getSchema(), queryContext, buildContext, groupedFactory);
    final KGroupedStream<GenericKey, GenericRow> groupedStream = stream.getStream().filter((k, v) -> v != null).groupBy((k, v) -> params.getMapper().apply(v), grouped);
    return KGroupedStreamHolder.of(groupedStream, params.getSchema());
}
Also used : GenericRow(io.confluent.ksql.GenericRow) PhysicalSchema(io.confluent.ksql.schema.ksql.PhysicalSchema) RuntimeBuildContext(io.confluent.ksql.execution.runtime.RuntimeBuildContext) KGroupedStream(org.apache.kafka.streams.kstream.KGroupedStream) Expression(io.confluent.ksql.execution.expression.tree.Expression) QueryContext(io.confluent.ksql.execution.context.QueryContext) CompiledExpression(io.confluent.ksql.execution.codegen.CompiledExpression) Formats(io.confluent.ksql.execution.plan.Formats) StreamGroupByKey(io.confluent.ksql.execution.plan.StreamGroupByKey) LogicalSchema(io.confluent.ksql.schema.ksql.LogicalSchema) CodeGenRunner(io.confluent.ksql.execution.codegen.CodeGenRunner) Grouped(org.apache.kafka.streams.kstream.Grouped) KGroupedStreamHolder(io.confluent.ksql.execution.plan.KGroupedStreamHolder) KStreamHolder(io.confluent.ksql.execution.plan.KStreamHolder) List(java.util.List) GenericRow(io.confluent.ksql.GenericRow) Serde(org.apache.kafka.common.serialization.Serde) Objects.requireNonNull(java.util.Objects.requireNonNull) ProcessingLogger(io.confluent.ksql.logging.processing.ProcessingLogger) GenericKey(io.confluent.ksql.GenericKey) ProcessingLogger(io.confluent.ksql.logging.processing.ProcessingLogger) LogicalSchema(io.confluent.ksql.schema.ksql.LogicalSchema) GenericKey(io.confluent.ksql.GenericKey) CompiledExpression(io.confluent.ksql.execution.codegen.CompiledExpression)

Example 100 with GenericKey

use of io.confluent.ksql.GenericKey in project ksql by confluentinc.

the class WindowStoreCacheBypass method fetchUncached.

/*
  This method is used for single key lookups. It is invoked by the fetch method
   */
private static WindowStoreIterator<ValueAndTimestamp<GenericRow>> fetchUncached(final ReadOnlyWindowStore<GenericKey, ValueAndTimestamp<GenericRow>> windowStore, final GenericKey key, final Instant lower, final Instant upper) {
    if (!(windowStore instanceof MeteredWindowStore)) {
        throw new IllegalStateException("Expecting a MeteredWindowStore");
    }
    final StateSerdes<GenericKey, ValueAndTimestamp<GenericRow>> serdes = getSerdes(windowStore);
    final WindowStore<Bytes, byte[]> wrapped = getInnermostStore(windowStore);
    final Bytes rawKey = Bytes.wrap(serdes.rawKey(key));
    final WindowStoreIterator<byte[]> fetch = wrapped.fetch(rawKey, lower, upper);
    return new DeserializingIterator(fetch, serdes);
}
Also used : ValueAndTimestamp(org.apache.kafka.streams.state.ValueAndTimestamp) Bytes(org.apache.kafka.common.utils.Bytes) MeteredWindowStore(org.apache.kafka.streams.state.internals.MeteredWindowStore) GenericKey(io.confluent.ksql.GenericKey)

Aggregations

GenericKey (io.confluent.ksql.GenericKey)147 GenericRow (io.confluent.ksql.GenericRow)100 Test (org.junit.Test)93 LogicalSchema (io.confluent.ksql.schema.ksql.LogicalSchema)24 Windowed (org.apache.kafka.streams.kstream.Windowed)20 WindowedRow (io.confluent.ksql.execution.streams.materialization.WindowedRow)14 PhysicalSchema (io.confluent.ksql.schema.ksql.PhysicalSchema)14 Materialized (org.apache.kafka.streams.kstream.Materialized)13 ValueAndTimestamp (org.apache.kafka.streams.state.ValueAndTimestamp)13 UnqualifiedColumnReferenceExp (io.confluent.ksql.execution.expression.tree.UnqualifiedColumnReferenceExp)12 MaterializationException (io.confluent.ksql.execution.streams.materialization.MaterializationException)9 IntegrationTest (io.confluent.common.utils.IntegrationTest)8 Materialization (io.confluent.ksql.execution.streams.materialization.Materialization)8 Row (io.confluent.ksql.execution.streams.materialization.Row)8 PersistentQueryMetadata (io.confluent.ksql.util.PersistentQueryMetadata)8 TimeWindow (org.apache.kafka.streams.kstream.internals.TimeWindow)8 IntegrationTest (org.apache.kafka.test.IntegrationTest)8 InOrder (org.mockito.InOrder)8 MaterializedTable (io.confluent.ksql.execution.streams.materialization.MaterializedTable)7 Objects (java.util.Objects)7