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
This commit is contained in:
Wei-Lun Li authored and GitHub committed 2026-11-15 10:34:06 -04:00
1 parent d7c42e2065
commit 00fdb95ab5
5 files changed
+61 -13

No files matched your search

@@ -1707,10 +1707,11 @@ public class DynamoDbService {
int scannedCount = evaluatedItems.size();
List<JsonNode> 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);
}
}
@@ -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);
@@ -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<JsonNode, ObjectNode> 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<String> keep = new HashSet<>();
@@ -1598,8 +1601,10 @@ public class NativeDynamoDbJsonHandler {
scanItems = applyIndexProjection(scanItems, scanTable, scanAccessPath, select);
}
if (projectionExpressionScan != null) {
Function<JsonNode, ObjectNode> 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<String> 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<JsonNode, ObjectNode> 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<String> keep = new HashSet<>();
attrToGet.forEach(n -> keep.add(n.asText()));
@@ -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<JsonNode, ObjectNode> projector(String projectionExpression, JsonNode exprAttrNames) {
if (!hasProjection(projectionExpression)) {
return item -> (ObjectNode) item;
}
validateExpression(projectionExpression, exprAttrNames);
PathTrie root = new PathTrie();
for (List<Token> 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();
};
}
/**
@@ -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";