You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@druid.apache.org by tu...@apache.org on 2025/10/02 05:48:53 UTC
(druid) branch master updated: Add support for caching ScanQuery results (#18568)
This is an automated email from the ASF dual-hosted git repository.
tuglu pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/druid.git
The following commit(s) were added to refs/heads/master by this push:
new 8346b5092f3 Add support for caching ScanQuery results (#18568)
8346b5092f3 is described below
commit 8346b5092f3356df24c38edb92153871bc9b783d
Author: jtuglu1 <jt...@netflix.com>
AuthorDate: Wed Oct 1 22:48:47 2025 -0700
Add support for caching ScanQuery results (#18568)
Adds support for result-level caching of scan queries. Despite being a relatively infrequent query type, a small, sustained volume of these queries can put significant load on a cluster as these don't run on processing threads and tend to eat a lot of CPU + return big result sets.
This caching behavior is disabled by default. To enable, override the `druid.*.cache.unCacheable` property.
---
docs/configuration/index.md | 8 +-
docs/querying/query-execution.md | 3 +-
.../java/org/apache/druid/query/CacheStrategy.java | 4 +-
.../main/java/org/apache/druid/query/Order.java | 9 +-
.../main/java/org/apache/druid/query/OrderBy.java | 8 +-
.../query/groupby/GroupByQueryQueryToolChest.java | 4 +-
.../SegmentMetadataQueryQueryToolChest.java | 2 +-
.../druid/query/scan/ScanQueryQueryToolChest.java | 79 +++++
.../query/search/SearchQueryQueryToolChest.java | 2 +-
.../TimeBoundaryQueryQueryToolChest.java | 2 +-
.../timeseries/TimeseriesQueryQueryToolChest.java | 2 +-
.../druid/query/topn/TopNQueryQueryToolChest.java | 2 +-
.../apache/druid/segment/column/ColumnType.java | 10 +-
.../query/scan/ScanQueryQueryToolChestTest.java | 350 +++++++++++++++++++++
.../java/org/apache/druid/client/CacheUtil.java | 7 +-
.../org/apache/druid/client/cache/CacheConfig.java | 7 +-
.../org/apache/druid/client/CacheUtilTest.java | 2 +-
.../apache/druid/client/cache/CacheConfigTest.java | 19 ++
18 files changed, 495 insertions(+), 25 deletions(-)
diff --git a/docs/configuration/index.md b/docs/configuration/index.md
index a68df5b4a74..c8e1d200cfb 100644
--- a/docs/configuration/index.md
+++ b/docs/configuration/index.md
@@ -1392,7 +1392,7 @@ You can optionally configure caching to be enabled on the peons by setting cachi
|--------|---------------|-----------|-------|
|`druid.realtime.cache.useCache`|true, false|Enable the cache on the realtime.|false|
|`druid.realtime.cache.populateCache`|true, false|Populate the cache on the realtime.|false|
-|`druid.realtime.cache.unCacheable`|All druid query types|All query types to not cache.|`[]`|
+|`druid.realtime.cache.unCacheable`|All druid query types|All query types to not cache.|`[scan]`|
|`druid.realtime.cache.maxEntrySize`|positive integer|Maximum cache entry size in bytes.|1_000_000|
See [cache configuration](#cache-configuration) for how to configure cache settings.
@@ -1534,7 +1534,7 @@ You can optionally configure caching to be enabled on the Indexer by setting cac
|--------|---------------|-----------|-------|
|`druid.realtime.cache.useCache`|true, false|Enable the cache on the realtime.|false|
|`druid.realtime.cache.populateCache`|true, false|Populate the cache on the realtime.|false|
-|`druid.realtime.cache.unCacheable`|All druid query types|All query types to not cache.|`[]`|
+|`druid.realtime.cache.unCacheable`|All druid query types|All query types to not cache.|`[scan]`|
|`druid.realtime.cache.maxEntrySize`|positive integer|Maximum cache entry size in bytes.|1_000_000|
See [cache configuration](#cache-configuration) for how to configure cache settings.
@@ -1642,7 +1642,7 @@ You can optionally only configure caching to be enabled on the Historical by set
|--------|---------------|-----------|-------|
|`druid.historical.cache.useCache`|true, false|Enable the cache on the Historical.|false|
|`druid.historical.cache.populateCache`|true, false|Populate the cache on the Historical.|false|
-|`druid.historical.cache.unCacheable`|All druid query types|All query types to not cache.|`[]`|
+|`druid.historical.cache.unCacheable`|All druid query types|All query types to not cache.|`[scan]`|
|`druid.historical.cache.maxEntrySize`|positive integer|Maximum cache entry size in bytes.|1_000_000|
See [cache configuration](#cache-configuration) for how to configure cache settings.
@@ -1898,7 +1898,7 @@ You can optionally only configure caching to be enabled on the Broker by setting
|`druid.broker.cache.useResultLevelCache`|true, false|Enable result level caching on the Broker.|false|
|`druid.broker.cache.populateResultLevelCache`|true, false|Populate the result level cache on the Broker.|false|
|`druid.broker.cache.resultLevelCacheLimit`|positive integer|Maximum size of query response that can be cached.|`Integer.MAX_VALUE`|
-|`druid.broker.cache.unCacheable`|All druid query types|All query types to not cache.|`[]`|
+|`druid.broker.cache.unCacheable`|All druid query types|All query types to not cache.|`[scan]`|
|`druid.broker.cache.cacheBulkMergeLimit`|positive integer or 0|Queries with more segments than this number will not attempt to fetch from cache at the broker level, leaving potential caching fetches (and cache result merging) to the Historicals|`Integer.MAX_VALUE`|
|`druid.broker.cache.maxEntrySize`|positive integer|Maximum cache entry size in bytes.|1_000_000|
diff --git a/docs/querying/query-execution.md b/docs/querying/query-execution.md
index 123b80738c4..9228258601f 100644
--- a/docs/querying/query-execution.md
+++ b/docs/querying/query-execution.md
@@ -51,8 +51,7 @@ and tasks running on Middle Managers) that are currently serving those segments.
4. For all query types except [Scan](scan-query.md), data servers process each segment in parallel and generate partial
results for each segment. The specific processing that is done depends on the query type. These partial results may be
-cached if [query caching](caching.md) is enabled. For Scan queries, segments are processed in order by a single thread,
-and results are not cached.
+cached if [query caching](caching.md) is enabled. For Scan queries, segments are processed in order by a single thread.
5. The Broker receives partial results from each data server, merges them into the final result set, and returns them
to the caller. For Timeseries and Scan queries, and for GroupBy queries where there is no sorting, the Broker is able to
diff --git a/processing/src/main/java/org/apache/druid/query/CacheStrategy.java b/processing/src/main/java/org/apache/druid/query/CacheStrategy.java
index ce4f742e6d1..19b4e186b4d 100644
--- a/processing/src/main/java/org/apache/druid/query/CacheStrategy.java
+++ b/processing/src/main/java/org/apache/druid/query/CacheStrategy.java
@@ -62,11 +62,11 @@ public interface CacheStrategy<T, CacheType, QueryType extends Query<T>>
* @param query the query to be cached
* @param willMergeRunners indicates that {@link QueryRunnerFactory#mergeRunners(QueryProcessingPool, Iterable)} will be
* called on the cached by-segment results
- * @param bySegment segment level or result level cache
+ * @param segmentLevel segment level or result level cache
*
* @return true if the query is cacheable, otherwise false.
*/
- default boolean isCacheable(QueryType query, boolean willMergeRunners, boolean bySegment)
+ default boolean isCacheable(QueryType query, boolean willMergeRunners, boolean segmentLevel)
{
return isCacheable(query, willMergeRunners);
}
diff --git a/processing/src/main/java/org/apache/druid/query/Order.java b/processing/src/main/java/org/apache/druid/query/Order.java
index 464aa9ed7d2..f9561ac524b 100644
--- a/processing/src/main/java/org/apache/druid/query/Order.java
+++ b/processing/src/main/java/org/apache/druid/query/Order.java
@@ -21,9 +21,10 @@ package org.apache.druid.query;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
+import org.apache.druid.java.util.common.Cacheable;
import org.apache.druid.java.util.common.StringUtils;
-public enum Order
+public enum Order implements Cacheable
{
ASCENDING,
DESCENDING,
@@ -41,4 +42,10 @@ public enum Order
{
return valueOf(StringUtils.toUpperCase(name));
}
+
+ @Override
+ public byte[] getCacheKey()
+ {
+ return StringUtils.toUtf8(toString());
+ }
}
diff --git a/processing/src/main/java/org/apache/druid/query/OrderBy.java b/processing/src/main/java/org/apache/druid/query/OrderBy.java
index 8a5ea0d1bc5..95efb7e0846 100644
--- a/processing/src/main/java/org/apache/druid/query/OrderBy.java
+++ b/processing/src/main/java/org/apache/druid/query/OrderBy.java
@@ -22,12 +22,13 @@ package org.apache.druid.query;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Preconditions;
+import org.apache.druid.java.util.common.Cacheable;
import org.apache.druid.java.util.common.IAE;
import org.apache.druid.java.util.common.StringUtils;
import java.util.Objects;
-public class OrderBy
+public class OrderBy implements Cacheable
{
public static OrderBy ascending(String columnName)
{
@@ -112,4 +113,9 @@ public class OrderBy
return StringUtils.format("%s %s", columnName, order == Order.ASCENDING ? "ASC" : "DESC");
}
+ @Override
+ public byte[] getCacheKey()
+ {
+ return StringUtils.toUtf8(toString());
+ }
}
diff --git a/processing/src/main/java/org/apache/druid/query/groupby/GroupByQueryQueryToolChest.java b/processing/src/main/java/org/apache/druid/query/groupby/GroupByQueryQueryToolChest.java
index b5712ebdda3..aa838591ccb 100644
--- a/processing/src/main/java/org/apache/druid/query/groupby/GroupByQueryQueryToolChest.java
+++ b/processing/src/main/java/org/apache/druid/query/groupby/GroupByQueryQueryToolChest.java
@@ -559,11 +559,11 @@ public class GroupByQueryQueryToolChest extends QueryToolChest<ResultRow, GroupB
private final List<DimensionSpec> dims = query.getDimensions();
@Override
- public boolean isCacheable(GroupByQuery query, boolean willMergeRunners, boolean bySegment)
+ public boolean isCacheable(GroupByQuery query, boolean willMergeRunners, boolean segmentLevel)
{
//disable segment-level cache on borker,
//see PR https://github.com/apache/druid/issues/3820
- return willMergeRunners || !bySegment;
+ return willMergeRunners || !segmentLevel;
}
@Override
diff --git a/processing/src/main/java/org/apache/druid/query/metadata/SegmentMetadataQueryQueryToolChest.java b/processing/src/main/java/org/apache/druid/query/metadata/SegmentMetadataQueryQueryToolChest.java
index 4ad82123055..84f3cfd534d 100644
--- a/processing/src/main/java/org/apache/druid/query/metadata/SegmentMetadataQueryQueryToolChest.java
+++ b/processing/src/main/java/org/apache/druid/query/metadata/SegmentMetadataQueryQueryToolChest.java
@@ -197,7 +197,7 @@ public class SegmentMetadataQueryQueryToolChest extends QueryToolChest<SegmentAn
return new CacheStrategy<>()
{
@Override
- public boolean isCacheable(SegmentMetadataQuery query, boolean willMergeRunners, boolean bySegment)
+ public boolean isCacheable(SegmentMetadataQuery query, boolean willMergeRunners, boolean segmentLevel)
{
return true;
}
diff --git a/processing/src/main/java/org/apache/druid/query/scan/ScanQueryQueryToolChest.java b/processing/src/main/java/org/apache/druid/query/scan/ScanQueryQueryToolChest.java
index 57bbe6a4942..1eaf5e2c69c 100644
--- a/processing/src/main/java/org/apache/druid/query/scan/ScanQueryQueryToolChest.java
+++ b/processing/src/main/java/org/apache/druid/query/scan/ScanQueryQueryToolChest.java
@@ -20,6 +20,7 @@
package org.apache.druid.query.scan;
import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.collect.Iterables;
@@ -30,22 +31,29 @@ import org.apache.druid.java.util.common.UOE;
import org.apache.druid.java.util.common.guava.BaseSequence;
import org.apache.druid.java.util.common.guava.Sequence;
import org.apache.druid.java.util.common.guava.Sequences;
+import org.apache.druid.query.CacheStrategy;
import org.apache.druid.query.FrameSignaturePair;
import org.apache.druid.query.GenericQueryMetricsFactory;
+import org.apache.druid.query.OrderBy;
import org.apache.druid.query.Query;
import org.apache.druid.query.QueryMetrics;
import org.apache.druid.query.QueryRunner;
import org.apache.druid.query.QueryToolChest;
import org.apache.druid.query.aggregation.MetricManipulationFn;
+import org.apache.druid.query.cache.CacheKeyBuilder;
+import org.apache.druid.segment.column.ColumnType;
import org.apache.druid.segment.column.RowSignature;
import org.apache.druid.utils.CloseableUtils;
+import javax.annotation.Nullable;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class ScanQueryQueryToolChest extends QueryToolChest<ScanResultValue, ScanQuery>
{
+ private static final byte SCAN_QUERY = 0x13;
+ private static final byte CACHE_STRATEGY_VERSION = 0x1;
private static final TypeReference<ScanResultValue> TYPE_REFERENCE = new TypeReference<>() {};
private final GenericQueryMetricsFactory queryMetricsFactory;
@@ -191,6 +199,77 @@ public class ScanQueryQueryToolChest extends QueryToolChest<ScanResultValue, Sca
);
}
+ @Override
+ public CacheStrategy<ScanResultValue, ScanResultValue, ScanQuery> getCacheStrategy(
+ final ScanQuery query,
+ @Nullable final ObjectMapper objectMapper
+ )
+ {
+ return new CacheStrategy<>()
+ {
+ @Override
+ public boolean isCacheable(ScanQuery query, boolean willMergeRunners, boolean segmentLevel)
+ {
+ // Currently, there is no bijective mapping from ScanResultValue to Result<BySegmentResultValueClass<ScanResultValue>>.
+ // This means queries will fail if:
+ // - A query is issued with bySegment:true
+ // - Segment-level cache is enabled on the broker (in which case it sends bySegment queries to data nodes).
+ return !query.context().isBySegment() && (!segmentLevel || willMergeRunners);
+ }
+
+ @Override
+ public byte[] computeCacheKey(ScanQuery query)
+ {
+ CacheKeyBuilder builder = new CacheKeyBuilder(SCAN_QUERY)
+ .appendByte(CACHE_STRATEGY_VERSION)
+ .appendCacheable(query.getVirtualColumns())
+ .appendString(query.getResultFormat().toString())
+ .appendLong(query.getScanRowsOffset())
+ .appendLong(query.getScanRowsLimit())
+ .appendCacheable(query.getFilter())
+ .appendStrings(query.getColumns() != null ? query.getColumns() : List.of())
+ .appendCacheable(query.getTimeOrder());
+
+ List<OrderBy> orderBys = query.getOrderBys();
+ if (orderBys != null) {
+ builder.appendCacheables(orderBys);
+ }
+
+ List<ColumnType> columnTypes = query.getColumnTypes();
+ if (columnTypes != null) {
+ builder.appendCacheables(columnTypes);
+ }
+
+ return builder.build();
+ }
+
+ @Override
+ public byte[] computeResultLevelCacheKey(ScanQuery query)
+ {
+ // Use the same key as segment-level cache no result-level transformations like aggregations
+ return computeCacheKey(query);
+ }
+
+ @Override
+ public TypeReference<ScanResultValue> getCacheObjectClazz()
+ {
+ return TYPE_REFERENCE;
+ }
+
+ @Override
+ public Function<ScanResultValue, ScanResultValue> prepareForCache(boolean isResultLevelCache)
+ {
+ return input -> input;
+ }
+
+ @Override
+ public Function<ScanResultValue, ScanResultValue> pullFromCache(boolean isResultLevelCache)
+ {
+ return input -> input;
+ }
+ };
+ }
+
private static Function<?, Object[]> getResultFormatMapper(ScanQuery.ResultFormat resultFormat, List<String> fields)
{
Function<?, Object[]> mapper;
diff --git a/processing/src/main/java/org/apache/druid/query/search/SearchQueryQueryToolChest.java b/processing/src/main/java/org/apache/druid/query/search/SearchQueryQueryToolChest.java
index fba270cdcc6..7efdf0e9e48 100644
--- a/processing/src/main/java/org/apache/druid/query/search/SearchQueryQueryToolChest.java
+++ b/processing/src/main/java/org/apache/druid/query/search/SearchQueryQueryToolChest.java
@@ -142,7 +142,7 @@ public class SearchQueryQueryToolChest extends QueryToolChest<Result<SearchResul
: Collections.emptyList();
@Override
- public boolean isCacheable(SearchQuery query, boolean willMergeRunners, boolean bySegment)
+ public boolean isCacheable(SearchQuery query, boolean willMergeRunners, boolean segmentLevel)
{
return true;
}
diff --git a/processing/src/main/java/org/apache/druid/query/timeboundary/TimeBoundaryQueryQueryToolChest.java b/processing/src/main/java/org/apache/druid/query/timeboundary/TimeBoundaryQueryQueryToolChest.java
index ffa31c3cea6..daa879141c2 100644
--- a/processing/src/main/java/org/apache/druid/query/timeboundary/TimeBoundaryQueryQueryToolChest.java
+++ b/processing/src/main/java/org/apache/druid/query/timeboundary/TimeBoundaryQueryQueryToolChest.java
@@ -175,7 +175,7 @@ public class TimeBoundaryQueryQueryToolChest
return new CacheStrategy<>()
{
@Override
- public boolean isCacheable(TimeBoundaryQuery query, boolean willMergeRunners, boolean bySegment)
+ public boolean isCacheable(TimeBoundaryQuery query, boolean willMergeRunners, boolean segmentLevel)
{
return true;
}
diff --git a/processing/src/main/java/org/apache/druid/query/timeseries/TimeseriesQueryQueryToolChest.java b/processing/src/main/java/org/apache/druid/query/timeseries/TimeseriesQueryQueryToolChest.java
index 41ecbf1ddd2..ea01738f2b4 100644
--- a/processing/src/main/java/org/apache/druid/query/timeseries/TimeseriesQueryQueryToolChest.java
+++ b/processing/src/main/java/org/apache/druid/query/timeseries/TimeseriesQueryQueryToolChest.java
@@ -275,7 +275,7 @@ public class TimeseriesQueryQueryToolChest extends QueryToolChest<Result<Timeser
private final List<AggregatorFactory> aggs = query.getAggregatorSpecs();
@Override
- public boolean isCacheable(TimeseriesQuery query, boolean willMergeRunners, boolean bySegment)
+ public boolean isCacheable(TimeseriesQuery query, boolean willMergeRunners, boolean segmentLevel)
{
return true;
}
diff --git a/processing/src/main/java/org/apache/druid/query/topn/TopNQueryQueryToolChest.java b/processing/src/main/java/org/apache/druid/query/topn/TopNQueryQueryToolChest.java
index f0d5fa58671..7b46e404676 100644
--- a/processing/src/main/java/org/apache/druid/query/topn/TopNQueryQueryToolChest.java
+++ b/processing/src/main/java/org/apache/druid/query/topn/TopNQueryQueryToolChest.java
@@ -287,7 +287,7 @@ public class TopNQueryQueryToolChest extends QueryToolChest<Result<TopNResultVal
);
@Override
- public boolean isCacheable(TopNQuery query, boolean willMergeRunners, boolean bySegment)
+ public boolean isCacheable(TopNQuery query, boolean willMergeRunners, boolean segmentLevel)
{
return true;
}
diff --git a/processing/src/main/java/org/apache/druid/segment/column/ColumnType.java b/processing/src/main/java/org/apache/druid/segment/column/ColumnType.java
index c136414158a..74606f739bf 100644
--- a/processing/src/main/java/org/apache/druid/segment/column/ColumnType.java
+++ b/processing/src/main/java/org/apache/druid/segment/column/ColumnType.java
@@ -23,6 +23,8 @@ import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
+import org.apache.druid.java.util.common.Cacheable;
+import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.segment.nested.NestedDataComplexTypeSerde;
import javax.annotation.Nullable;
@@ -34,7 +36,7 @@ import java.util.Objects;
* @see TypeSignature
*/
@JsonSerialize(using = ToStringSerializer.class)
-public class ColumnType extends BaseTypeSignature<ValueType>
+public class ColumnType extends BaseTypeSignature<ValueType> implements Cacheable
{
/**
* Druid string type. Values will be represented as {@link String} or {@link java.util.List<String>} in the case
@@ -244,4 +246,10 @@ public class ColumnType extends BaseTypeSignature<ValueType>
}
return leastRestrictiveType;
}
+
+ @Override
+ public byte[] getCacheKey()
+ {
+ return StringUtils.toUtf8(toString());
+ }
}
diff --git a/processing/src/test/java/org/apache/druid/query/scan/ScanQueryQueryToolChestTest.java b/processing/src/test/java/org/apache/druid/query/scan/ScanQueryQueryToolChestTest.java
index ac782332d69..6490e99ce68 100644
--- a/processing/src/test/java/org/apache/druid/query/scan/ScanQueryQueryToolChestTest.java
+++ b/processing/src/test/java/org/apache/druid/query/scan/ScanQueryQueryToolChestTest.java
@@ -20,23 +20,30 @@
package org.apache.druid.query.scan;
import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
import org.apache.druid.frame.allocation.HeapMemoryAllocator;
import org.apache.druid.frame.allocation.SingleMemoryAllocatorFactory;
import org.apache.druid.java.util.common.ISE;
import org.apache.druid.java.util.common.Intervals;
import org.apache.druid.java.util.common.guava.Sequence;
import org.apache.druid.java.util.common.guava.Sequences;
+import org.apache.druid.math.expr.ExprMacroTable;
+import org.apache.druid.query.CacheStrategy;
import org.apache.druid.query.DefaultGenericQueryMetricsFactory;
import org.apache.druid.query.Druids;
import org.apache.druid.query.FrameBasedInlineDataSource;
import org.apache.druid.query.FrameSignaturePair;
+import org.apache.druid.query.Order;
+import org.apache.druid.query.OrderBy;
import org.apache.druid.query.QueryToolChestTestHelper;
+import org.apache.druid.query.filter.EqualityFilter;
import org.apache.druid.query.spec.MultipleIntervalSegmentSpec;
import org.apache.druid.segment.column.ColumnType;
import org.apache.druid.segment.column.RowSignature;
import org.apache.druid.segment.nested.NestedDataComplexTypeSerde;
import org.apache.druid.segment.nested.StructuredData;
import org.apache.druid.segment.serde.ComplexMetrics;
+import org.apache.druid.segment.virtual.ExpressionVirtualColumn;
import org.junit.Assert;
import org.junit.Test;
@@ -441,4 +448,347 @@ public class ScanQueryQueryToolChestTest
)
);
}
+
+ @Test
+ public void testCacheStrategy()
+ {
+ ScanQuery query = Druids.newScanQueryBuilder()
+ .dataSource("foo")
+ .intervals(new MultipleIntervalSegmentSpec(ImmutableList.of(Intervals.of(
+ "2015-01-01/2015-01-02"))))
+ .columns("dim1", "dim2")
+ .resultFormat(ScanQuery.ResultFormat.RESULT_FORMAT_LIST)
+ .batchSize(4096)
+ .offset(10)
+ .limit(100)
+ .build();
+
+ CacheStrategy<ScanResultValue, ScanResultValue, ScanQuery> strategy = toolChest.getCacheStrategy(query, null);
+
+ Assert.assertNotNull(strategy);
+ Assert.assertTrue(strategy.isCacheable(query, true, false));
+ Assert.assertFalse(strategy.isCacheable(query, false, true));
+ Assert.assertTrue(strategy.isCacheable(query, true, true));
+
+ byte[] cacheKey = strategy.computeCacheKey(query);
+ Assert.assertNotNull(cacheKey);
+ Assert.assertTrue(cacheKey.length > 0);
+
+ byte[] resultLevelCacheKey = strategy.computeResultLevelCacheKey(query);
+ Assert.assertNotNull(resultLevelCacheKey);
+ Assert.assertTrue(resultLevelCacheKey.length > 0);
+
+ // For ScanQuery, result-level and segment-level cache keys should be the same
+ Assert.assertArrayEquals(cacheKey, resultLevelCacheKey);
+
+ ScanResultValue testResult = new ScanResultValue(
+ "test_segment",
+ ImmutableList.of("dim1", "dim2"),
+ ImmutableList.of(
+ ImmutableMap.of("dim1", "value1", "dim2", "value2"),
+ ImmutableMap.of("dim1", "value3", "dim2", "value4")
+ )
+ );
+
+ ScanResultValue cachedValue = strategy.prepareForCache(false).apply(testResult);
+ ScanResultValue fromCache = strategy.pullFromCache(false).apply(cachedValue);
+
+ Assert.assertEquals(testResult, fromCache);
+ }
+
+ @Test
+ public void testCacheDisabledForBySegmentQueries()
+ {
+ ScanQuery query = Druids.newScanQueryBuilder()
+ .dataSource("foo")
+ .intervals(new MultipleIntervalSegmentSpec(ImmutableList.of(Intervals.of(
+ "2015-01-01/2015-01-02"))))
+ .columns("dim1", "dim2")
+ .resultFormat(ScanQuery.ResultFormat.RESULT_FORMAT_LIST)
+ .batchSize(4096)
+ .offset(10)
+ .limit(100)
+ .context(ImmutableMap.of("bySegment", true))
+ .build();
+
+ CacheStrategy<ScanResultValue, ScanResultValue, ScanQuery> strategy = toolChest.getCacheStrategy(query, null);
+
+ Assert.assertNotNull(strategy);
+ Assert.assertFalse(strategy.isCacheable(query, true, false));
+ Assert.assertFalse(strategy.isCacheable(query, false, true));
+ }
+
+ @Test
+ public void testCacheKeyDifferentQueries()
+ {
+ ScanQuery query1 = Druids.newScanQueryBuilder()
+ .dataSource("foo")
+ .intervals(new MultipleIntervalSegmentSpec(ImmutableList.of(Intervals.of(
+ "2025-01-01/2025-01-02"))))
+ .columns("dim1", "dim2")
+ .resultFormat(ScanQuery.ResultFormat.RESULT_FORMAT_LIST)
+ .build();
+
+ ScanQuery query2 = Druids.newScanQueryBuilder()
+ .dataSource("foo")
+ .intervals(new MultipleIntervalSegmentSpec(ImmutableList.of(Intervals.of(
+ "2025-01-01/2025-01-02"))))
+ .columns("dim1", "dim3")
+ .resultFormat(ScanQuery.ResultFormat.RESULT_FORMAT_LIST)
+ .build();
+
+ ScanQuery query3 = Druids.newScanQueryBuilder()
+ .dataSource("foo")
+ .intervals(new MultipleIntervalSegmentSpec(ImmutableList.of(Intervals.of(
+ "2025-01-01/2025-01-02"))))
+ .columns("dim1", "dim2")
+ .resultFormat(ScanQuery.ResultFormat.RESULT_FORMAT_COMPACTED_LIST)
+ .build();
+
+ CacheStrategy<ScanResultValue, ScanResultValue, ScanQuery> strategy = toolChest.getCacheStrategy(query1, null);
+
+ byte[] cacheKey1 = strategy.computeCacheKey(query1);
+ byte[] cacheKey2 = strategy.computeCacheKey(query2);
+ byte[] cacheKey3 = strategy.computeCacheKey(query3);
+
+ Assert.assertFalse(Arrays.equals(cacheKey1, cacheKey2));
+ Assert.assertFalse(Arrays.equals(cacheKey1, cacheKey3));
+ Assert.assertFalse(Arrays.equals(cacheKey2, cacheKey3));
+ }
+
+ @Test
+ public void testCacheKeyWithFilters()
+ {
+ ScanQuery queryWithFilter = Druids.newScanQueryBuilder()
+ .dataSource("foo")
+ .intervals(new MultipleIntervalSegmentSpec(ImmutableList.of(Intervals.of(
+ "2025-01-01/2025-01-02"))))
+ .columns("dim1", "dim2")
+ .resultFormat(ScanQuery.ResultFormat.RESULT_FORMAT_LIST)
+ .filters(new EqualityFilter("dim1", ColumnType.STRING, "test", null))
+ .build();
+
+ ScanQuery queryWithoutFilter = Druids.newScanQueryBuilder()
+ .dataSource("foo")
+ .intervals(new MultipleIntervalSegmentSpec(ImmutableList.of(Intervals.of(
+ "2025-01-01/2025-01-02"))))
+ .columns("dim1", "dim2")
+ .resultFormat(ScanQuery.ResultFormat.RESULT_FORMAT_LIST)
+ .build();
+
+ CacheStrategy<ScanResultValue, ScanResultValue, ScanQuery> strategy = toolChest.getCacheStrategy(
+ queryWithFilter,
+ null
+ );
+
+ byte[] cacheKeyWithFilter = strategy.computeCacheKey(queryWithFilter);
+ byte[] cacheKeyWithoutFilter = strategy.computeCacheKey(queryWithoutFilter);
+
+ Assert.assertFalse(Arrays.equals(cacheKeyWithFilter, cacheKeyWithoutFilter));
+ }
+
+ @Test
+ public void testCacheKeyWithVirtualColumns()
+ {
+ ScanQuery queryWithVirtual = Druids.newScanQueryBuilder()
+ .dataSource("foo")
+ .intervals(new MultipleIntervalSegmentSpec(ImmutableList.of(Intervals.of(
+ "2025-01-01/2025-01-02"))))
+ .columns("dim1", "virtual_col")
+ .resultFormat(ScanQuery.ResultFormat.RESULT_FORMAT_LIST)
+ .virtualColumns(new ExpressionVirtualColumn(
+ "virtual_col",
+ "dim1 + '_suffix'",
+ ColumnType.STRING,
+ ExprMacroTable.nil()
+ ))
+ .build();
+
+ ScanQuery queryWithoutVirtual = Druids.newScanQueryBuilder()
+ .dataSource("foo")
+ .intervals(new MultipleIntervalSegmentSpec(ImmutableList.of(Intervals.of(
+ "2025-01-01/2025-01-02"))))
+ .columns("dim1")
+ .resultFormat(ScanQuery.ResultFormat.RESULT_FORMAT_LIST)
+ .build();
+
+ CacheStrategy<ScanResultValue, ScanResultValue, ScanQuery> strategy = toolChest.getCacheStrategy(
+ queryWithVirtual,
+ null
+ );
+
+ byte[] cacheKeyWithVirtual = strategy.computeCacheKey(queryWithVirtual);
+ byte[] cacheKeyWithoutVirtual = strategy.computeCacheKey(queryWithoutVirtual);
+
+ Assert.assertFalse(Arrays.equals(cacheKeyWithVirtual, cacheKeyWithoutVirtual));
+ }
+
+ @Test
+ public void testCacheKeyWithOrderBy()
+ {
+ ScanQuery queryWithOrderBy = Druids.newScanQueryBuilder()
+ .dataSource("foo")
+ .intervals(new MultipleIntervalSegmentSpec(ImmutableList.of(Intervals.of(
+ "2025-01-01/2025-01-02"))))
+ .columns("dim1", "dim2")
+ .resultFormat(ScanQuery.ResultFormat.RESULT_FORMAT_LIST)
+ .orderBy(List.of(OrderBy.descending("dim1")))
+ .build();
+
+ ScanQuery queryWithoutOrderBy = Druids.newScanQueryBuilder()
+ .dataSource("foo")
+ .intervals(new MultipleIntervalSegmentSpec(ImmutableList.of(Intervals.of(
+ "2025-01-01/2025-01-02"))))
+ .columns("dim1", "dim2")
+ .resultFormat(ScanQuery.ResultFormat.RESULT_FORMAT_LIST)
+ .build();
+
+ ScanQuery queryWithDifferentOrderBy = Druids.newScanQueryBuilder()
+ .dataSource("foo")
+ .intervals(new MultipleIntervalSegmentSpec(ImmutableList.of(Intervals.of(
+ "2025-01-01/2025-01-02"))))
+ .columns("dim1", "dim2")
+ .resultFormat(ScanQuery.ResultFormat.RESULT_FORMAT_LIST)
+ .orderBy(List.of(OrderBy.ascending("dim1")))
+ .build();
+
+ final CacheStrategy<ScanResultValue, ScanResultValue, ScanQuery> strategy = toolChest.getCacheStrategy(
+ queryWithOrderBy,
+ null
+ );
+
+ final byte[] cacheKeyWithOrderBy = strategy.computeCacheKey(queryWithOrderBy);
+ final byte[] cacheKeyWithoutOrderBy = strategy.computeCacheKey(queryWithoutOrderBy);
+ final byte[] cacheKeyWithDifferentOrderBy = strategy.computeCacheKey(queryWithDifferentOrderBy);
+
+ Assert.assertFalse(Arrays.equals(cacheKeyWithOrderBy, cacheKeyWithoutOrderBy));
+ Assert.assertFalse(Arrays.equals(cacheKeyWithOrderBy, cacheKeyWithDifferentOrderBy));
+ }
+
+ @Test
+ public void testCacheKeyWithOffsetAndLimit()
+ {
+ ScanQuery queryWithOffsetLimit = Druids.newScanQueryBuilder()
+ .dataSource("foo")
+ .intervals(new MultipleIntervalSegmentSpec(ImmutableList.of(Intervals.of(
+ "2025-01-01/2025-01-02"))))
+ .columns("dim1", "dim2")
+ .resultFormat(ScanQuery.ResultFormat.RESULT_FORMAT_LIST)
+ .offset(10)
+ .limit(100)
+ .build();
+
+ ScanQuery queryWithoutOffsetLimit = Druids.newScanQueryBuilder()
+ .dataSource("foo")
+ .intervals(new MultipleIntervalSegmentSpec(ImmutableList.of(Intervals.of(
+ "2025-01-01/2025-01-02"))))
+ .columns("dim1", "dim2")
+ .resultFormat(ScanQuery.ResultFormat.RESULT_FORMAT_LIST)
+ .build();
+
+ CacheStrategy<ScanResultValue, ScanResultValue, ScanQuery> strategy = toolChest.getCacheStrategy(
+ queryWithOffsetLimit,
+ null
+ );
+
+ byte[] cacheKeyWithOffsetLimit = strategy.computeCacheKey(queryWithOffsetLimit);
+ byte[] cacheKeyWithoutOffsetLimit = strategy.computeCacheKey(queryWithoutOffsetLimit);
+
+ Assert.assertFalse(Arrays.equals(cacheKeyWithOffsetLimit, cacheKeyWithoutOffsetLimit));
+ }
+
+ @Test
+ public void testCacheKeyWithDifferentResultFormat()
+ {
+ ScanQuery queryWithCompactedList = Druids.newScanQueryBuilder()
+ .dataSource("foo")
+ .intervals(new MultipleIntervalSegmentSpec(ImmutableList.of(Intervals.of(
+ "2025-01-01/2025-01-02"))))
+ .columns("dim1", "dim2")
+ .resultFormat(ScanQuery.ResultFormat.RESULT_FORMAT_COMPACTED_LIST)
+ .offset(10)
+ .limit(100)
+ .build();
+
+ ScanQuery queryWithResultFormatList = Druids.newScanQueryBuilder()
+ .dataSource("foo")
+ .intervals(new MultipleIntervalSegmentSpec(ImmutableList.of(Intervals.of(
+ "2025-01-01/2025-01-02"))))
+ .columns("dim1", "dim2")
+ .resultFormat(ScanQuery.ResultFormat.RESULT_FORMAT_LIST)
+ .offset(10)
+ .limit(100)
+ .build();
+ CacheStrategy<ScanResultValue, ScanResultValue, ScanQuery> strategy = toolChest.getCacheStrategy(
+ queryWithCompactedList,
+ null
+ );
+
+ byte[] cacheKeyWithCompactedList = strategy.computeCacheKey(queryWithCompactedList);
+ byte[] cacheKeyWithResultFormatList = strategy.computeCacheKey(queryWithResultFormatList);
+
+ Assert.assertFalse(Arrays.equals(cacheKeyWithCompactedList, cacheKeyWithResultFormatList));
+ }
+
+ @Test
+ public void testCacheKeyWithDifferentTimeOrder()
+ {
+ ScanQuery queryWithOrderDesc = Druids.newScanQueryBuilder()
+ .dataSource("foo")
+ .intervals(new MultipleIntervalSegmentSpec(ImmutableList.of(Intervals.of(
+ "2025-01-01/2025-01-02"))))
+ .columns("__time", "dim1", "dim2")
+ .resultFormat(ScanQuery.ResultFormat.RESULT_FORMAT_COMPACTED_LIST)
+ .order(Order.DESCENDING)
+ .build();
+
+ ScanQuery queryWithOrderAsc = Druids.newScanQueryBuilder()
+ .dataSource("foo")
+ .intervals(new MultipleIntervalSegmentSpec(ImmutableList.of(Intervals.of(
+ "2025-01-01/2025-01-02"))))
+ .columns("__time", "dim1", "dim2")
+ .resultFormat(ScanQuery.ResultFormat.RESULT_FORMAT_COMPACTED_LIST)
+ .order(Order.ASCENDING)
+ .build();
+ CacheStrategy<ScanResultValue, ScanResultValue, ScanQuery> strategy = toolChest.getCacheStrategy(
+ queryWithOrderDesc,
+ null
+ );
+
+ byte[] cacheKeyWithOrderDesc = strategy.computeCacheKey(queryWithOrderDesc);
+ byte[] cacheKeyWithOrderAsc = strategy.computeCacheKey(queryWithOrderAsc);
+
+ Assert.assertFalse(Arrays.equals(cacheKeyWithOrderDesc, cacheKeyWithOrderAsc));
+ }
+
+ @Test
+ public void testCacheKeyWithDifferentColumnTypes()
+ {
+ ScanQuery query1 = Druids.newScanQueryBuilder()
+ .dataSource("foo")
+ .intervals(new MultipleIntervalSegmentSpec(ImmutableList.of(Intervals.of(
+ "2025-01-01/2025-01-02"))))
+ .columns("__time", "dim1", "dim2")
+ .resultFormat(ScanQuery.ResultFormat.RESULT_FORMAT_COMPACTED_LIST)
+ .columnTypes(List.of(ColumnType.LONG, ColumnType.STRING, ColumnType.STRING))
+ .build();
+
+ ScanQuery query2 = Druids.newScanQueryBuilder()
+ .dataSource("foo")
+ .intervals(new MultipleIntervalSegmentSpec(ImmutableList.of(Intervals.of(
+ "2025-01-01/2025-01-02"))))
+ .columns("__time", "dim1", "dim2")
+ .resultFormat(ScanQuery.ResultFormat.RESULT_FORMAT_COMPACTED_LIST)
+ .columnTypes(List.of(ColumnType.LONG, ColumnType.STRING, ColumnType.STRING_ARRAY))
+ .build();
+ CacheStrategy<ScanResultValue, ScanResultValue, ScanQuery> strategy = toolChest.getCacheStrategy(
+ query1,
+ null
+ );
+
+ byte[] cacheKeyQuery1 = strategy.computeCacheKey(query1);
+ byte[] cacheKeyQuery2 = strategy.computeCacheKey(query2);
+
+ Assert.assertFalse(Arrays.equals(cacheKeyQuery1, cacheKeyQuery2));
+ }
}
diff --git a/server/src/main/java/org/apache/druid/client/CacheUtil.java b/server/src/main/java/org/apache/druid/client/CacheUtil.java
index 53f6a178024..af0fcb397d2 100644
--- a/server/src/main/java/org/apache/druid/client/CacheUtil.java
+++ b/server/src/main/java/org/apache/druid/client/CacheUtil.java
@@ -29,7 +29,6 @@ import org.apache.druid.query.SegmentDescriptor;
import org.joda.time.Interval;
import javax.annotation.Nullable;
-
import java.nio.ByteBuffer;
public class CacheUtil
@@ -174,18 +173,18 @@ public class CacheUtil
* @param cacheStrategy result of {@link QueryToolChest#getCacheStrategy} on this query
* @param cacheConfig current active cache config
* @param serverType BROKER or DATA
- * @param bySegment segement level or result-level cache
+ * @param segmentLevel segment level or result-level cache
*/
static <T> boolean isQueryCacheable(
final Query<T> query,
@Nullable final CacheStrategy<T, Object, Query<T>> cacheStrategy,
final CacheConfig cacheConfig,
final ServerType serverType,
- final boolean bySegment
+ final boolean segmentLevel
)
{
return cacheStrategy != null
- && cacheStrategy.isCacheable(query, serverType.willMergeRunners(), bySegment)
+ && cacheStrategy.isCacheable(query, serverType.willMergeRunners(), segmentLevel)
&& cacheConfig.isQueryCacheable(query)
&& query.getDataSource().isCacheable(serverType == ServerType.BROKER);
}
diff --git a/server/src/main/java/org/apache/druid/client/cache/CacheConfig.java b/server/src/main/java/org/apache/druid/client/cache/CacheConfig.java
index 5b68466ca4e..41faf80ddc6 100644
--- a/server/src/main/java/org/apache/druid/client/cache/CacheConfig.java
+++ b/server/src/main/java/org/apache/druid/client/cache/CacheConfig.java
@@ -20,7 +20,6 @@
package org.apache.druid.client.cache;
import com.fasterxml.jackson.annotation.JsonProperty;
-import com.google.common.collect.ImmutableList;
import org.apache.druid.query.Query;
import javax.validation.constraints.Min;
@@ -54,8 +53,12 @@ public class CacheConfig
@JsonProperty
private int maxEntrySize = 1_000_000;
+ /*
+ Disable segment/result-level caching for types:
+ - [scan]: scan query results can be large and fill up small result/segment caches, so disabled by default.
+ */
@JsonProperty
- private List<String> unCacheable = ImmutableList.of();
+ private List<String> unCacheable = List.of(Query.SCAN);
@JsonProperty
private int resultLevelCacheLimit = Integer.MAX_VALUE;
diff --git a/server/src/test/java/org/apache/druid/client/CacheUtilTest.java b/server/src/test/java/org/apache/druid/client/CacheUtilTest.java
index 9d886765ddc..9ab0d6f446f 100644
--- a/server/src/test/java/org/apache/druid/client/CacheUtilTest.java
+++ b/server/src/test/java/org/apache/druid/client/CacheUtilTest.java
@@ -176,7 +176,7 @@ public class CacheUtilTest
}
@Override
- public boolean isCacheable(QueryType query, boolean willMergeRunners, boolean bySegment)
+ public boolean isCacheable(QueryType query, boolean willMergeRunners, boolean segmentLevel)
{
return willMergeRunners ? cacheableOnDataServers : cacheableOnBrokers;
}
diff --git a/server/src/test/java/org/apache/druid/client/cache/CacheConfigTest.java b/server/src/test/java/org/apache/druid/client/cache/CacheConfigTest.java
index f0f18667d69..aa728b5aaf4 100644
--- a/server/src/test/java/org/apache/druid/client/cache/CacheConfigTest.java
+++ b/server/src/test/java/org/apache/druid/client/cache/CacheConfigTest.java
@@ -29,6 +29,7 @@ import org.apache.druid.guice.GuiceInjectors;
import org.apache.druid.guice.JsonConfigProvider;
import org.apache.druid.guice.JsonConfigurator;
import org.apache.druid.initialization.DruidModule;
+import org.apache.druid.query.Query;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
@@ -95,6 +96,7 @@ public class CacheConfigTest
Assert.assertEquals(true, config.isPopulateCache());
Assert.assertEquals(true, config.isUseCache());
}
+
@Test
public void testInjection2()
{
@@ -158,5 +160,22 @@ public class CacheConfigTest
throw new IllegalStateException("Should have already failed");
}
+ @Test
+ public void testDefaultUnCacheableList()
+ {
+ configProvider.inject(properties, configurator);
+ CacheConfig config = configProvider.get();
+ injector.injectMembers(config);
+
+ Assert.assertFalse(config.isQueryCacheable(Query.SCAN));
+
+ properties.clear();
+ configProvider = JsonConfigProvider.of(PROPERTY_PREFIX, CacheConfig.class);
+ properties.put(PROPERTY_PREFIX + ".unCacheable", "[]");
+ configProvider.inject(properties, configurator);
+ CacheConfig config2 = configProvider.get();
+ injector.injectMembers(config2);
+ Assert.assertTrue(config2.isQueryCacheable(Query.SCAN));
+ }
}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org