From 00fdb95ab5781ba29c0a32edf75f23fc7cd6843d Mon Sep 17 00:00:00 2001 From: Wei-Lun Li Date: Sun, 15 Nov 2026 23:34:06 +0900 Subject: [PATCH] perf(dynamodb): read Query and Scan expressions once per request (#8454) Query parsed its key condition, and Query and Scan their filter, for every item, and every returned item rebuilt the projection. Each expression is now parsed when the first item reaches it and evaluated against the rest, and Query, Scan and BatchGetItem build one projection per request through ProjectionEvaluator.projector. A scan that evaluates no item still reads no filter, as before, and the list-index pattern is compiled once. Closes #8462 --- .../services/dynamodb/DynamoDbService.java | 23 ++++++++++++++----- .../dynamodb/ExpressionEvaluator.java | 4 +++- .../dynamodb/NativeDynamoDbJsonHandler.java | 15 ++++++++---- .../dynamodb/ProjectionEvaluator.java | 21 +++++++++++++++-- .../dynamodb/DynamoDbServiceTest.java | 11 +++++++++ 5 files changed, 61 insertions(+), 13 deletions(-) diff --git a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbService.java b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbService.java index 1594024e7e..728d178214 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbService.java +++ b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbService.java @@ -1707,10 +1707,11 @@ public class DynamoDbService { int scannedCount = evaluatedItems.size(); List scannedItems = evaluatedItems; - if (filterExpression != null) { + // Parse only when there is an item to evaluate: an expression is still only read when an item reaches it. + if (filterExpression != null && !evaluatedItems.isEmpty()) { + ExpressionEvaluator.Expr filter = ExpressionEvaluator.parse(filterExpression); evaluatedItems = evaluatedItems.stream() - .filter(item -> matchesFilterExpression(item, filterExpression, - exprAttrNames, expressionAttrValues)) + .filter(item -> ExpressionEvaluator.evaluate(filter, item, exprAttrNames, expressionAttrValues)) .toList(); } @@ -1777,6 +1778,8 @@ public class DynamoDbService { ? items.tailMap(buildItemKeyFromNode(exclusiveStartKey, pkName, skName), false).values() : items.values(); + // Parsed when the first item is evaluated, so a scan that evaluates no item doesn't read it. + ExpressionEvaluator.Expr filter = null; final int MAX_RESPONSE_BYTES = 1024 * 1024; int totalScanned = 0; int accSize = 0; @@ -1819,8 +1822,11 @@ public class DynamoDbService { totalScanned++; scannedItems.add(item); lastScanned = item; - boolean matched = (filterExpression == null - || matchesFilterExpression(filtered, filterExpression, expressionAttrNames, expressionAttrValues)) + if (filterExpression != null && filter == null) { + filter = ExpressionEvaluator.parse(filterExpression); + } + boolean matched = (filter == null + || ExpressionEvaluator.evaluate(filter, filtered, expressionAttrNames, expressionAttrValues)) && (scanFilter == null || matchesScanFilterPublic(filtered, scanFilter, conditionalOperator)); if (matched) { results.add(item); @@ -5050,12 +5056,17 @@ public class DynamoDbService { String partitionKeyValue = expressionAttrValues != null && partitionKeyValuePlaceholder != null ? extractScalarValue(expressionAttrValues.get(partitionKeyValuePlaceholder)) : null; + // Parsed when the first candidate is evaluated, so no candidate means no parse. + ExpressionEvaluator.Expr keyCondition = null; for (JsonNode item : queryCandidates(items, accessPath, partitionKeyValue)) { if (partitionKeyValue != null && !matchesAttributeValue(item.get(partitionKeyName), partitionKeyValue)) { continue; } - if (ExpressionEvaluator.matches(expression, item, exprAttrNames, expressionAttrValues)) { + if (keyCondition == null) { + keyCondition = ExpressionEvaluator.parse(expression); + } + if (ExpressionEvaluator.evaluate(keyCondition, item, exprAttrNames, expressionAttrValues)) { results.add(item); } } diff --git a/src/main/java/io/floci/aws/services/dynamodb/ExpressionEvaluator.java b/src/main/java/io/floci/aws/services/dynamodb/ExpressionEvaluator.java index 4f70c1d594..4764e70b58 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/ExpressionEvaluator.java +++ b/src/main/java/io/floci/aws/services/dynamodb/ExpressionEvaluator.java @@ -15,6 +15,7 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeSet; +import java.util.regex.Pattern; /** * Proper tokenizer/parser/evaluator for DynamoDB filter expressions and key condition expressions. @@ -759,6 +760,7 @@ final class ExpressionEvaluator { // ── Evaluator ── private static final String DOT_ESCAPE = "\uFF0E"; + private static final Pattern LIST_INDEX_SEGMENT = Pattern.compile("\\[\\d+\\]"); /** * Evaluates a parsed expression against a DynamoDB item. @@ -1097,7 +1099,7 @@ final class ExpressionEvaluator { for (int i = 0; i < segments.size(); i++) { if (current == null) return null; String segment = segments.get(i); - if (segment.matches("\\[\\d+\\]")) { + if (LIST_INDEX_SEGMENT.matcher(segment).matches()) { // List index navigation int idx = Integer.parseInt(segment.substring(1, segment.length() - 1)); JsonNode listNode = current.has("L") ? current.get("L") : (current.isArray() ? current : null); diff --git a/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbJsonHandler.java b/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbJsonHandler.java index 99a3adc929..db803308ec 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbJsonHandler.java +++ b/src/main/java/io/floci/aws/services/dynamodb/NativeDynamoDbJsonHandler.java @@ -52,6 +52,7 @@ import java.util.Map; import java.util.Set; import java.util.function.BiConsumer; import java.util.function.Consumer; +import java.util.function.Function; import java.util.function.Supplier; import java.util.regex.Pattern; @@ -1448,8 +1449,10 @@ public class NativeDynamoDbJsonHandler { queryItems = applyIndexProjection(queryItems, queryTable, queryAccessPath, select); } if (projectionExpression != null) { + Function projection = + ProjectionEvaluator.projector(projectionExpression, exprAttrNames); queryItems = queryItems.stream() - .map(i -> (JsonNode) ProjectionEvaluator.project(i, projectionExpression, exprAttrNames)) + .map(i -> (JsonNode) projection.apply(i)) .toList(); } else if (attributesToGet != null) { Set keep = new HashSet<>(); @@ -1598,8 +1601,10 @@ public class NativeDynamoDbJsonHandler { scanItems = applyIndexProjection(scanItems, scanTable, scanAccessPath, select); } if (projectionExpressionScan != null) { + Function projection = + ProjectionEvaluator.projector(projectionExpressionScan, exprAttrNames); scanItems = scanItems.stream() - .map(i -> (JsonNode) ProjectionEvaluator.project(i, projectionExpressionScan, exprAttrNames)) + .map(i -> (JsonNode) projection.apply(i)) .toList(); } else if (attributesToGetScan != null) { Set keep = new HashSet<>(); @@ -1885,10 +1890,12 @@ public class NativeDynamoDbJsonHandler { JsonNode attrToGet = tableRequest != null && tableRequest.has("AttributesToGet") ? tableRequest.get("AttributesToGet") : null; ArrayNode tableItems = objectMapper.createArrayNode(); + Function projection = projExpr != null + ? ProjectionEvaluator.projector(projExpr, exprNames) : null; for (JsonNode item : entry.getValue()) { JsonNode projected; - if (projExpr != null) { - projected = ProjectionEvaluator.project(item, projExpr, exprNames); + if (projection != null) { + projected = projection.apply(item); } else if (attrToGet != null) { Set keep = new HashSet<>(); attrToGet.forEach(n -> keep.add(n.asText())); diff --git a/src/main/java/io/floci/aws/services/dynamodb/ProjectionEvaluator.java b/src/main/java/io/floci/aws/services/dynamodb/ProjectionEvaluator.java index 627a4b3e7e..f9e92b5a4f 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/ProjectionEvaluator.java +++ b/src/main/java/io/floci/aws/services/dynamodb/ProjectionEvaluator.java @@ -16,6 +16,7 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; +import java.util.function.Function; /** * Applies a DynamoDB ProjectionExpression to a result item, returning a new @@ -41,13 +42,29 @@ final class ProjectionEvaluator { if (item == null || !hasProjection(projectionExpression)) { return (ObjectNode) item; } + return projector(projectionExpression, exprAttrNames).apply(item); + } + + /** + * Validates and reads the expression once and returns a function that projects an item + * as {@link #project} does, for a read that projects every item it returns. + */ + static Function projector(String projectionExpression, JsonNode exprAttrNames) { + if (!hasProjection(projectionExpression)) { + return item -> (ObjectNode) item; + } validateExpression(projectionExpression, exprAttrNames); PathTrie root = new PathTrie(); for (List path : readPaths(projectionExpression)) { root.insert(resolvePath(path, exprAttrNames)); } - ObjectNode projected = projectMapEntries(item, root); - return projected != null ? projected : MAPPER.createObjectNode(); + return item -> { + if (item == null) { + return null; + } + ObjectNode projected = projectMapEntries(item, root); + return projected != null ? projected : MAPPER.createObjectNode(); + }; } /** diff --git a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbServiceTest.java b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbServiceTest.java index a39d1ca54b..95490f0933 100644 --- a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbServiceTest.java +++ b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbServiceTest.java @@ -1162,6 +1162,17 @@ class DynamoDbServiceTest { assertEquals(2, result.items().size()); } + @Test + void scanOfEmptyTableDoesNotReadFilterExpression() { + // Callers that skip the handler's validation (the Step Functions scan integration) + // only see a malformed FilterExpression once an item is evaluated. + String region = "eu-west-1"; + createUsersTable(region); + + DynamoDbService.ScanResult result = service.scan("Users", "nickname = = :n", null, null, null, null, null, region); + assertEquals(0, result.items().size()); + } + @Test void scanWithLimit() { String region = "eu-west-1";