Search in sources :

Example 1 with CacheKeyBuilder

use of org.apache.druid.query.cache.CacheKeyBuilder in project druid by druid-io.

the class JoinableFactoryWrapper method computeJoinDataSourceCacheKey.

/**
 * Compute a cache key prefix for a join data source. This includes the data sources that participate in the RHS of a
 * join as well as any query specific constructs associated with join data source such as base table filter. This key prefix
 * can be used in segment level cache or result level cache. The function can return following wrapped in an
 * Optional
 * - Non-empty byte array - If there is join datasource involved and caching is possible. The result includes
 * join condition expression, join type and cache key returned by joinable factory for each {@link PreJoinableClause}
 * - NULL - There is a join but caching is not possible. It may happen if one of the participating datasource
 * in the JOIN is not cacheable.
 *
 * @param dataSourceAnalysis for the join datasource
 *
 * @return the optional cache key to be used as part of query cache key
 *
 * @throws {@link IAE} if this operation is called on a non-join data source
 */
public Optional<byte[]> computeJoinDataSourceCacheKey(final DataSourceAnalysis dataSourceAnalysis) {
    final List<PreJoinableClause> clauses = dataSourceAnalysis.getPreJoinableClauses();
    if (clauses.isEmpty()) {
        throw new IAE("No join clauses to build the cache key for data source [%s]", dataSourceAnalysis.getDataSource());
    }
    final CacheKeyBuilder keyBuilder;
    keyBuilder = new CacheKeyBuilder(JOIN_OPERATION);
    if (dataSourceAnalysis.getJoinBaseTableFilter().isPresent()) {
        keyBuilder.appendCacheable(dataSourceAnalysis.getJoinBaseTableFilter().get());
    }
    for (PreJoinableClause clause : clauses) {
        Optional<byte[]> bytes = joinableFactory.computeJoinCacheKey(clause.getDataSource(), clause.getCondition());
        if (!bytes.isPresent()) {
            // Encountered a data source which didn't support cache yet
            log.debug("skipping caching for join since [%s] does not support caching", clause.getDataSource());
            return Optional.empty();
        }
        keyBuilder.appendByteArray(bytes.get());
        keyBuilder.appendString(clause.getCondition().getOriginalExpression());
        keyBuilder.appendString(clause.getPrefix());
        keyBuilder.appendString(clause.getJoinType().name());
    }
    return Optional.of(keyBuilder.build());
}
Also used : PreJoinableClause(org.apache.druid.query.planning.PreJoinableClause) CacheKeyBuilder(org.apache.druid.query.cache.CacheKeyBuilder) IAE(org.apache.druid.java.util.common.IAE)

Example 2 with CacheKeyBuilder

use of org.apache.druid.query.cache.CacheKeyBuilder in project druid by druid-io.

the class BroadcastSegmentIndexedTable method computeCacheKey.

@Override
public byte[] computeCacheKey() {
    SegmentId segmentId = segment.getId();
    CacheKeyBuilder keyBuilder = new CacheKeyBuilder(CACHE_PREFIX);
    return keyBuilder.appendLong(segmentId.getInterval().getStartMillis()).appendLong(segmentId.getInterval().getEndMillis()).appendString(segmentId.getVersion()).appendString(segmentId.getDataSource()).appendInt(segmentId.getPartitionNum()).build();
}
Also used : SegmentId(org.apache.druid.timeline.SegmentId) CacheKeyBuilder(org.apache.druid.query.cache.CacheKeyBuilder)

Example 3 with CacheKeyBuilder

use of org.apache.druid.query.cache.CacheKeyBuilder in project druid by druid-io.

the class SuppressedAggregatorFactory method getCacheKey.

@Override
public byte[] getCacheKey() {
    CacheKeyBuilder cacheKeyBuilder = new CacheKeyBuilder(AggregatorUtil.SUPPRESSED_AGG_CACHE_TYPE_ID);
    cacheKeyBuilder.appendCacheable(delegate);
    return cacheKeyBuilder.build();
}
Also used : CacheKeyBuilder(org.apache.druid.query.cache.CacheKeyBuilder)

Example 4 with CacheKeyBuilder

use of org.apache.druid.query.cache.CacheKeyBuilder in project druid by druid-io.

the class TDigestSketchToQuantilePostAggregator method getCacheKey.

@Override
public byte[] getCacheKey() {
    final CacheKeyBuilder builder = new CacheKeyBuilder(PostAggregatorIds.TDIGEST_SKETCH_TO_QUANTILE_CACHE_TYPE_ID).appendCacheable(field);
    builder.appendDouble(fraction);
    return builder.build();
}
Also used : CacheKeyBuilder(org.apache.druid.query.cache.CacheKeyBuilder)

Example 5 with CacheKeyBuilder

use of org.apache.druid.query.cache.CacheKeyBuilder in project druid by druid-io.

the class TimeseriesQueryQueryToolChest method getCacheStrategy.

@Override
public CacheStrategy<Result<TimeseriesResultValue>, Object, TimeseriesQuery> getCacheStrategy(final TimeseriesQuery query) {
    return new CacheStrategy<Result<TimeseriesResultValue>, Object, TimeseriesQuery>() {

        private final List<AggregatorFactory> aggs = query.getAggregatorSpecs();

        @Override
        public boolean isCacheable(TimeseriesQuery query, boolean willMergeRunners) {
            return true;
        }

        @Override
        public byte[] computeCacheKey(TimeseriesQuery query) {
            return new CacheKeyBuilder(TIMESERIES_QUERY).appendBoolean(query.isDescending()).appendBoolean(query.isSkipEmptyBuckets()).appendCacheable(query.getGranularity()).appendCacheable(query.getDimensionsFilter()).appendCacheables(query.getAggregatorSpecs()).appendCacheable(query.getVirtualColumns()).appendInt(query.getLimit()).build();
        }

        @Override
        public byte[] computeResultLevelCacheKey(TimeseriesQuery query) {
            final CacheKeyBuilder builder = new CacheKeyBuilder(TIMESERIES_QUERY).appendBoolean(query.isDescending()).appendBoolean(query.isSkipEmptyBuckets()).appendCacheable(query.getGranularity()).appendCacheable(query.getDimensionsFilter()).appendCacheables(query.getAggregatorSpecs()).appendCacheable(query.getVirtualColumns()).appendCacheables(query.getPostAggregatorSpecs()).appendInt(query.getLimit()).appendString(query.getTimestampResultField()).appendBoolean(query.isGrandTotal());
            return builder.build();
        }

        @Override
        public TypeReference<Object> getCacheObjectClazz() {
            return OBJECT_TYPE_REFERENCE;
        }

        @Override
        public Function<Result<TimeseriesResultValue>, Object> prepareForCache(boolean isResultLevelCache) {
            return input -> {
                TimeseriesResultValue results = input.getValue();
                final List<Object> retVal = Lists.newArrayListWithCapacity(1 + aggs.size());
                // Timestamp can be null if grandTotal is true.
                if (isResultLevelCache) {
                    retVal.add(input.getTimestamp() == null ? null : input.getTimestamp().getMillis());
                } else {
                    retVal.add(Preconditions.checkNotNull(input.getTimestamp(), "timestamp of input[%s]", input).getMillis());
                }
                for (AggregatorFactory agg : aggs) {
                    retVal.add(results.getMetric(agg.getName()));
                }
                if (isResultLevelCache) {
                    for (PostAggregator postAgg : query.getPostAggregatorSpecs()) {
                        retVal.add(results.getMetric(postAgg.getName()));
                    }
                }
                return retVal;
            };
        }

        @Override
        public Function<Object, Result<TimeseriesResultValue>> pullFromCache(boolean isResultLevelCache) {
            return new Function<Object, Result<TimeseriesResultValue>>() {

                private final Granularity granularity = query.getGranularity();

                @Override
                public Result<TimeseriesResultValue> apply(Object input) {
                    List<Object> results = (List<Object>) input;
                    final Map<String, Object> retVal = Maps.newLinkedHashMap();
                    Iterator<Object> resultIter = results.iterator();
                    final Number timestampNumber = (Number) resultIter.next();
                    final DateTime timestamp;
                    if (isResultLevelCache) {
                        timestamp = timestampNumber == null ? null : granularity.toDateTime(timestampNumber.longValue());
                    } else {
                        timestamp = granularity.toDateTime(Preconditions.checkNotNull(timestampNumber, "timestamp").longValue());
                    }
                    CacheStrategy.fetchAggregatorsFromCache(aggs, resultIter, isResultLevelCache, (aggName, aggPosition, aggValueObject) -> {
                        retVal.put(aggName, aggValueObject);
                    });
                    if (isResultLevelCache) {
                        Iterator<PostAggregator> postItr = query.getPostAggregatorSpecs().iterator();
                        while (postItr.hasNext() && resultIter.hasNext()) {
                            retVal.put(postItr.next().getName(), resultIter.next());
                        }
                    }
                    return new Result<>(timestamp, new TimeseriesResultValue(retVal));
                }
            };
        }
    };
}
Also used : StringUtils(org.apache.commons.lang.StringUtils) QueryPlus(org.apache.druid.query.QueryPlus) Granularity(org.apache.druid.java.util.common.granularity.Granularity) MapBasedRow(org.apache.druid.data.input.MapBasedRow) Inject(com.google.inject.Inject) RowAdapters(org.apache.druid.segment.RowAdapters) HashMap(java.util.HashMap) ResultMergeQueryRunner(org.apache.druid.query.ResultMergeQueryRunner) CacheKeyBuilder(org.apache.druid.query.cache.CacheKeyBuilder) ResultGranularTimestampComparator(org.apache.druid.query.ResultGranularTimestampComparator) PostAggregator(org.apache.druid.query.aggregation.PostAggregator) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) Query(org.apache.druid.query.Query) Map(java.util.Map) QueryRunner(org.apache.druid.query.QueryRunner) TypeReference(com.fasterxml.jackson.core.type.TypeReference) MetricManipulationFn(org.apache.druid.query.aggregation.MetricManipulationFn) Sequences(org.apache.druid.java.util.common.guava.Sequences) DateTimes(org.apache.druid.java.util.common.DateTimes) Sequence(org.apache.druid.java.util.common.guava.Sequence) RowBasedColumnSelectorFactory(org.apache.druid.segment.RowBasedColumnSelectorFactory) Function(com.google.common.base.Function) Iterator(java.util.Iterator) ImmutableMap(com.google.common.collect.ImmutableMap) ResponseContext(org.apache.druid.query.context.ResponseContext) AggregatorFactory(org.apache.druid.query.aggregation.AggregatorFactory) DateTime(org.joda.time.DateTime) QueryToolChest(org.apache.druid.query.QueryToolChest) Aggregator(org.apache.druid.query.aggregation.Aggregator) Maps(com.google.common.collect.Maps) QueryContexts(org.apache.druid.query.QueryContexts) BinaryOperator(java.util.function.BinaryOperator) Granularities(org.apache.druid.java.util.common.granularity.Granularities) Result(org.apache.druid.query.Result) List(java.util.List) CacheStrategy(org.apache.druid.query.CacheStrategy) RowSignature(org.apache.druid.segment.column.RowSignature) ColumnType(org.apache.druid.segment.column.ColumnType) Preconditions(com.google.common.base.Preconditions) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Comparator(java.util.Comparator) Collections(java.util.Collections) PostAggregator(org.apache.druid.query.aggregation.PostAggregator) CacheKeyBuilder(org.apache.druid.query.cache.CacheKeyBuilder) AggregatorFactory(org.apache.druid.query.aggregation.AggregatorFactory) Granularity(org.apache.druid.java.util.common.granularity.Granularity) DateTime(org.joda.time.DateTime) Result(org.apache.druid.query.Result) Function(com.google.common.base.Function) ImmutableList(com.google.common.collect.ImmutableList) List(java.util.List) CacheStrategy(org.apache.druid.query.CacheStrategy)

Aggregations

CacheKeyBuilder (org.apache.druid.query.cache.CacheKeyBuilder)9 Function (com.google.common.base.Function)3 List (java.util.List)3 Granularity (org.apache.druid.java.util.common.granularity.Granularity)3 CacheStrategy (org.apache.druid.query.CacheStrategy)3 PostAggregator (org.apache.druid.query.aggregation.PostAggregator)3 DateTime (org.joda.time.DateTime)3 ArrayList (java.util.ArrayList)2 Map (java.util.Map)2 IAE (org.apache.druid.java.util.common.IAE)2 Result (org.apache.druid.query.Result)2 TypeReference (com.fasterxml.jackson.core.type.TypeReference)1 VisibleForTesting (com.google.common.annotations.VisibleForTesting)1 Preconditions (com.google.common.base.Preconditions)1 ImmutableList (com.google.common.collect.ImmutableList)1 ImmutableMap (com.google.common.collect.ImmutableMap)1 Lists (com.google.common.collect.Lists)1 Maps (com.google.common.collect.Maps)1 Hasher (com.google.common.hash.Hasher)1 Inject (com.google.inject.Inject)1