feat(dynamodb): accept range, IN, OR and NOT in SearchVectors conditions (#9257)

SearchVectors now accepts ranges, <>, IN, attribute_exists, attribute_not_exists, OR and NOT on INLINE_FILTER attributes, with ranges and BETWEEN on Number attributes only. The HASH attribute still takes one = condition reached through AND only. Each refusal names the broken rule with DynamoDB's message, in DynamoDB's order.

FilterExpression and ConditionExpression now refuse an attribute_exists or attribute_not_exists with more than one operand or without a document path.

The attribute type lookup moves to TableDefinition.attributeType, replacing the copies in DynamoDbService and DynamoDbAccessPathValidator.
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-11-23 10:19:49 -04:00
1 parent b57b55025a
commit 946d1392a5
10 files changed
+520 -92

No files matched your search

@@ -542,7 +542,7 @@ final class DynamoDbAccessPathValidator {
if (value == null) {
continue;
}
String expectedType = startKeyAttributeType(table, attribute);
String expectedType = table.attributeType(attribute);
if (isEmptyKeyValue(value, expectedType)) {
throw DynamoDbKeyValueErrors.emptyKeyValue(expectedType, attribute);
}
@@ -574,7 +574,7 @@ final class DynamoDbAccessPathValidator {
Set<String> attributes = startKeyAttributeNames(table, index);
for (String attribute : attributes) {
JsonNode value = exclusiveStartKey.get(attribute);
String expectedType = startKeyAttributeType(table, attribute);
String expectedType = table.attributeType(attribute);
if (value != null && value.isObject() && !value.isEmpty()
&& expectedType != null && !value.has(expectedType)) {
throw DynamoDbKeyValueErrors.indexKeyTypeMismatch(attribute, expectedType,
@@ -583,7 +583,7 @@ final class DynamoDbAccessPathValidator {
}
for (String attribute : attributes) {
JsonNode value = exclusiveStartKey.get(attribute);
String expectedType = startKeyAttributeType(table, attribute);
String expectedType = table.attributeType(attribute);
if (value != null && isEmptyKeyValue(value, expectedType)) {
throw DynamoDbKeyValueErrors.emptyIndexKeyValue(expectedType, index.indexName(), attribute);
}
@@ -615,17 +615,6 @@ final class DynamoDbAccessPathValidator {
return names.stream().sorted().toList();
}
private static String startKeyAttributeType(TableDefinition table, String attribute) {
if (table.getAttributeDefinitions() == null) {
return null;
}
return table.getAttributeDefinitions().stream()
.filter(definition -> attribute.equals(definition.getAttributeName()))
.map(AttributeDefinition::getAttributeType)
.findFirst()
.orElse(null);
}
private static boolean isEmptyKeyValue(JsonNode value, String expectedType) {
return ("S".equals(expectedType) || "B".equals(expectedType))
&& value.isObject() && value.size() == 1
@@ -1243,6 +1243,15 @@ public class DynamoDbPartiQLParser {
+ "operator or function: " + op + ", operand type: " + type;
}
static String incorrectOperandCount(String function, int count) {
return "Incorrect number of operands for operator or function; operator or function: "
+ function + ", number of operands: " + count;
}
static String documentPathRequired(String function) {
return "Operator or function requires a document path; operator or function: " + function;
}
private Cond parseCond() {
if (STATEMENT_STARTS.contains(peek().type())) {
Token start = peek();
@@ -1448,8 +1457,7 @@ public class DynamoDbPartiQLParser {
private void checkOperands(String function, List<Argument> operands) {
if (operands.size() != CONDITION_FUNCTION_OPERANDS.getOrDefault(function, LIST_APPEND_OPERANDS)) {
deferExpression("Incorrect number of operands for operator or function; operator or function: "
+ function + ", number of operands: " + operands.size());
deferExpression(incorrectOperandCount(function, operands.size()));
return;
}
Argument first = operands.getFirst();
@@ -1457,8 +1465,7 @@ public class DynamoDbPartiQLParser {
switch (function) {
case "attribute_exists", "attribute_not_exists" -> {
if (first.path() == null) {
deferExpression("Operator or function requires a document path; operator or function: "
+ function);
deferExpression(documentPathRequired(function));
}
}
case "size" -> {
@@ -4938,7 +4938,7 @@ public class DynamoDbService {
return;
}
validateAttributeValueShape(attr);
String expectedType = keyAttributeType(table, keyName);
String expectedType = table.attributeType(keyName);
if (expectedType != null && !attr.has(expectedType)) {
if (surface == KeySurface.ITEM_BODY) {
throw new KeySchemaMismatchException(
@@ -4955,16 +4955,6 @@ public class DynamoDbService {
}
}
private String keyAttributeType(TableDefinition table, String keyName) {
if (table.getAttributeDefinitions() == null) {
return null;
}
return table.getAttributeDefinitions().stream()
.filter(def -> keyName.equals(def.getAttributeName()))
.map(AttributeDefinition::getAttributeType)
.findFirst().orElse(null);
}
// AWS validates GSI/LSI key attribute values on every write that produces the item,
// but only when the attribute is present — sparse indexes allow it to be absent.
private void validateIndexKeyTypes(TableDefinition table, JsonNode item, boolean isUpdate) {
@@ -5044,7 +5034,7 @@ public class DynamoDbService {
continue;
}
validateAttributeValueShape(attr);
String expectedType = keyAttributeType(table, attrName);
String expectedType = table.attributeType(attrName);
if (expectedType != null && !attr.has(expectedType)) {
throw DynamoDbKeyValueErrors.indexKeyTypeMismatch(attrName, expectedType,
attr.fieldNames().next(), indexName);
@@ -220,13 +220,11 @@ final class DynamoDbUpdateExpressionSyntax {
}
List<Operand> arguments = call.arguments();
if (arguments.size() != 2) {
throw invalid("Incorrect number of operands for operator or function; operator or function: "
+ function + ", number of operands: " + arguments.size());
throw invalid(DynamoDbPartiQLParser.incorrectOperandCount(function, arguments.size()));
}
if ("if_not_exists".equals(function)) {
if (!isPath(arguments.getFirst())) {
throw invalid("Operator or function requires a document path; operator or function: "
+ function);
throw invalid(DynamoDbPartiQLParser.documentPathRequired(function));
}
return;
}
@@ -37,7 +37,7 @@ final class DynamoDbVectorSearch {
JsonNode exprAttrNames, JsonNode exprAttrValues,
String projectionExpression) {
float[] query = parseSearchVector(searchVector, index);
ExpressionEvaluator.Expr condition = parseSearchCondition(index, searchConditionExpression,
ExpressionEvaluator.Expr condition = parseSearchCondition(table, index, searchConditionExpression,
exprAttrNames, exprAttrValues);
ProjectionEvaluator.validateExpression(projectionExpression, exprAttrNames);
@@ -109,12 +109,15 @@ final class DynamoDbVectorSearch {
/**
* Parses and validates the condition, returning null when there is none.
*
* <p>Only equality is supported, on HASH and INLINE_FILTER elements alike. The comparator is
* checked on every clause before any membership check, because AWS answers {@code tenant < :t}
* on an index that declares {@code tenant} with the comparator message and {@code tenant = :t}
* on an index with no SearchSchema with the membership one.
* <p>The leaf conditions are checked in the order AWS checks them. First each leaf is checked
* for functions, nested attributes and the number of attribute names, in written order. Then,
* when the index has a HASH element, the conditions on it must be one equality reached through
* AND only. Last each leaf is checked in written order for membership in the SearchSchema, the
* operator against the attribute type, and the value types against the attribute type.
*/
private static ExpressionEvaluator.Expr parseSearchCondition(VectorIndex index, String expression,
private static ExpressionEvaluator.Expr parseSearchCondition(TableDefinition table,
VectorIndex index,
String expression,
JsonNode exprAttrNames,
JsonNode exprAttrValues) {
String hashAttribute = index.getHashAttributeName();
@@ -124,67 +127,197 @@ final class DynamoDbVectorSearch {
}
return null;
}
ExpressionEvaluator.validateExpression(expression, "SearchConditionExpression",
ExpressionEvaluator.validateSyntax(expression, "SearchConditionExpression");
ExpressionEvaluator.validateSemantics(expression, "SearchConditionExpression",
exprAttrNames, exprAttrValues);
ExpressionEvaluator.Expr condition = ExpressionEvaluator.parse(expression);
List<ExpressionEvaluator.CompareExpr> clauses = new ArrayList<>();
collectClauses(condition, clauses);
for (ExpressionEvaluator.CompareExpr clause : clauses) {
if (clause.op() != ExpressionEvaluator.TokenType.EQ) {
throw invalidComparator();
}
List<Leaf> leaves = new ArrayList<>();
collectLeaves(condition, false, leaves);
for (Leaf leaf : leaves) {
checkLeafShape(leaf.expr());
}
if (hashAttribute != null) {
checkHashConditions(leaves, hashAttribute, exprAttrNames);
}
Set<String> schemaAttributes = new HashSet<>(index.getSearchSchemaAttributeNames());
boolean hashConstrained = false;
for (ExpressionEvaluator.CompareExpr clause : clauses) {
String attribute = conditionAttribute(clause, exprAttrNames);
for (Leaf leaf : leaves) {
String attribute = leafAttribute(leaf.expr(), exprAttrNames);
if (!schemaAttributes.contains(attribute)) {
throw new AwsException("ValidationException",
"SearchConditionExpression must not contain any attributes that is not in "
+ "SearchSchema. Invalid attribute: " + attribute, 400);
}
hashConstrained |= attribute.equals(hashAttribute);
}
if (hashAttribute != null && !hashConstrained) {
throw missingHashCondition();
String attributeType = table.attributeType(attribute);
checkOperatorType(leaf.expr(), attribute, attributeType);
checkValueTypes(leaf.expr(), attribute, attributeType, exprAttrValues);
}
return condition;
}
private static void collectClauses(ExpressionEvaluator.Expr expr,
List<ExpressionEvaluator.CompareExpr> clauses) {
if (expr instanceof ExpressionEvaluator.AndExpr and) {
for (ExpressionEvaluator.Expr operand : and.operands()) {
collectClauses(operand, clauses);
/** A leaf condition, and whether an OR or NOT sits between it and the root. */
private record Leaf(ExpressionEvaluator.Expr expr, boolean underOrNot) {}
private static void collectLeaves(ExpressionEvaluator.Expr expr, boolean underOrNot,
List<Leaf> leaves) {
switch (expr) {
case ExpressionEvaluator.AndExpr and -> {
for (ExpressionEvaluator.Expr operand : and.operands()) {
collectLeaves(operand, underOrNot, leaves);
}
}
} else if (expr instanceof ExpressionEvaluator.CompareExpr compare) {
clauses.add(compare);
} else {
throw invalidComparator();
case ExpressionEvaluator.OrExpr or -> {
for (ExpressionEvaluator.Expr operand : or.operands()) {
collectLeaves(operand, true, leaves);
}
}
case ExpressionEvaluator.NotExpr not -> collectLeaves(not.operand(), true, leaves);
default -> leaves.add(new Leaf(expr, underOrNot));
}
}
/** The attribute a clause constrains, with any {@code #alias} resolved. */
private static String conditionAttribute(ExpressionEvaluator.CompareExpr clause,
JsonNode exprAttrNames) {
ExpressionEvaluator.Operand operand = clause.left() instanceof ExpressionEvaluator.PathOperand
? clause.left() : clause.right();
if (!(operand instanceof ExpressionEvaluator.PathOperand path)) {
throw invalidComparator();
}
StringBuilder name = new StringBuilder();
for (String segment : path.segments()) {
String resolved = segment.startsWith("#") && exprAttrNames != null
&& exprAttrNames.hasNonNull(segment)
? exprAttrNames.get(segment).asText() : segment;
if (!name.isEmpty() && !resolved.startsWith("[")) {
name.append('.');
private static List<ExpressionEvaluator.Operand> leafOperands(ExpressionEvaluator.Expr leaf) {
return switch (leaf) {
case ExpressionEvaluator.CompareExpr compare -> List.of(compare.left(), compare.right());
case ExpressionEvaluator.BetweenExpr between ->
List.of(between.value(), between.low(), between.high());
case ExpressionEvaluator.InExpr in -> {
List<ExpressionEvaluator.Operand> operands = new ArrayList<>();
operands.add(in.value());
operands.addAll(in.candidates());
yield operands;
}
name.append(resolved);
case ExpressionEvaluator.FunctionCallExpr call -> call.args();
default -> List.of();
};
}
private static void checkLeafShape(ExpressionEvaluator.Expr leaf) {
if (leaf instanceof ExpressionEvaluator.FunctionCallExpr call
&& !call.functionName().equals("attribute_exists")
&& !call.functionName().equals("attribute_not_exists")) {
throw functionNotAllowed(call.functionName());
}
return name.toString();
List<ExpressionEvaluator.PathOperand> paths = new ArrayList<>();
for (ExpressionEvaluator.Operand operand : leafOperands(leaf)) {
if (operand instanceof ExpressionEvaluator.FunctionOperand function) {
throw functionNotAllowed(function.functionName());
}
if (operand instanceof ExpressionEvaluator.PathOperand path) {
paths.add(path);
}
}
for (ExpressionEvaluator.PathOperand path : paths) {
if (path.segments().size() > 1) {
throw invalidCondition("SearchConditionExpression cannot have conditions on "
+ "nested attributes");
}
}
if (paths.isEmpty()) {
throw invalidCondition("Invalid condition in SearchConditionExpression: No attribute "
+ "names used in a condition");
}
if (paths.size() > 1) {
throw invalidCondition("Invalid condition in SearchConditionExpression: Multiple "
+ "attribute names used in one condition");
}
}
private static void checkHashConditions(List<Leaf> leaves, String hashAttribute,
JsonNode exprAttrNames) {
int equalities = 0;
for (Leaf leaf : leaves) {
if (!leafAttribute(leaf.expr(), exprAttrNames).equals(hashAttribute)) {
continue;
}
boolean equality = leaf.expr() instanceof ExpressionEvaluator.CompareExpr compare
&& compare.op() == ExpressionEvaluator.TokenType.EQ;
if (!equality || leaf.underOrNot()) {
throw new AwsException("ValidationException",
"SearchConditionExpression must use = on the HASH attribute, not inside "
+ "OR or NOT; HASH attribute: " + hashAttribute, 400);
}
equalities++;
}
if (equalities > 1) {
throw new AwsException("ValidationException",
"SearchConditionExpression must contain only one condition on the HASH "
+ "attribute; to search more than one HASH value, make one SearchVectors call "
+ "for each value", 400);
}
if (equalities == 0) {
throw new AwsException("ValidationException",
"SearchConditionExpression must have all HASH attributes in configured "
+ "SearchSchema", 400);
}
}
private static void checkOperatorType(ExpressionEvaluator.Expr leaf, String attribute,
String attributeType) {
String operator = switch (leaf) {
case ExpressionEvaluator.BetweenExpr between -> "BETWEEN";
case ExpressionEvaluator.CompareExpr compare -> switch (compare.op()) {
case LT -> "<";
case LE -> "<=";
case GT -> ">";
case GE -> ">=";
default -> null;
};
default -> null;
};
if (operator != null && !"N".equals(attributeType)) {
throw new AwsException("ValidationException",
"SearchConditionExpression allows this operator only on Number (N) "
+ "attributes; operator: " + operator + ", attribute: " + attribute
+ ", attribute type: " + attributeType, 400);
}
}
private static void checkValueTypes(ExpressionEvaluator.Expr leaf, String attribute,
String attributeType, JsonNode exprAttrValues) {
if (attributeType == null) {
return;
}
for (ExpressionEvaluator.Operand operand : leafOperands(leaf)) {
if (!(operand instanceof ExpressionEvaluator.PlaceholderOperand placeholder)) {
continue;
}
JsonNode value = exprAttrValues == null ? null : exprAttrValues.get(placeholder.name());
if (value == null || !value.fieldNames().hasNext()) {
continue;
}
String valueType = value.fieldNames().next();
if (!valueType.equals(attributeType)) {
throw new AwsException("ValidationException",
"Type of '" + attribute + "' attribute in SearchConditionExpression ("
+ valueType + ") does not match type in search schema (" + attributeType
+ ")", 400);
}
}
}
/** The attribute a leaf constrains, with any {@code #alias} resolved. */
private static String leafAttribute(ExpressionEvaluator.Expr leaf, JsonNode exprAttrNames) {
for (ExpressionEvaluator.Operand operand : leafOperands(leaf)) {
if (operand instanceof ExpressionEvaluator.PathOperand path) {
String segment = path.segments().get(0);
return segment.startsWith("#") && exprAttrNames != null
&& exprAttrNames.hasNonNull(segment)
? exprAttrNames.get(segment).asText() : segment;
}
}
throw new IllegalStateException("A search condition leaf has no attribute");
}
private static AwsException functionNotAllowed(String name) {
return invalidCondition("The function is not allowed in a search condition; function: "
+ name);
}
private static AwsException invalidCondition(String detail) {
return new AwsException("ValidationException",
"Invalid SearchConditionExpression: " + detail, 400);
}
private static AwsException missingHashCondition() {
@@ -192,12 +325,6 @@ final class DynamoDbVectorSearch {
"SearchConditionExpression must be provided when SearchSchema has a HASH key", 400);
}
private static AwsException invalidComparator() {
return new AwsException("ValidationException",
"Invalid SearchConditionExpression: Invalid comparator used in "
+ "SearchConditionExpression", 400);
}
// ── Candidates ──
/**
@@ -563,9 +563,12 @@ final class ExpressionEvaluator {
}
}
private static AwsException invalidExpression(String exprType, String message) {
return new AwsException("ValidationException", "Invalid " + exprType + ": " + message, 400);
}
private static AwsException incorrectOperandType(String exprType, String operator, String type) {
return new AwsException("ValidationException", "Invalid " + exprType + ": "
+ DynamoDbPartiQLParser.incorrectOperandType(operator, type), 400);
return invalidExpression(exprType, DynamoDbPartiQLParser.incorrectOperandType(operator, type));
}
// AWS rejects a BETWEEN whose bounds are the wrong way round when it parses the
@@ -632,6 +635,15 @@ final class ExpressionEvaluator {
private static void validateFunction(FunctionCallExpr f, String exprType,
JsonNode names, JsonNode values) {
String name = f.functionName().toLowerCase();
if (name.equals("attribute_exists") || name.equals("attribute_not_exists")) {
if (f.args().size() != 1) {
throw invalidExpression(exprType,
DynamoDbPartiQLParser.incorrectOperandCount(f.functionName(), f.args().size()));
}
if (!(f.args().getFirst() instanceof PathOperand)) {
throw invalidExpression(exprType, DynamoDbPartiQLParser.documentPathRequired(f.functionName()));
}
}
if (name.equals("contains") && f.args().size() >= 2
&& operandsIdentical(f.args().get(0), f.args().get(1), names)) {
throw new AwsException("ValidationException",
@@ -151,6 +151,17 @@ public class TableDefinition {
public List<AttributeDefinition> getAttributeDefinitions() { return attributeDefinitions; }
public void setAttributeDefinitions(List<AttributeDefinition> attributeDefinitions) { this.attributeDefinitions = attributeDefinitions; }
public String attributeType(String attributeName) {
if (attributeDefinitions == null) {
return null;
}
return attributeDefinitions.stream()
.filter(definition -> attributeName.equals(definition.getAttributeName()))
.map(AttributeDefinition::getAttributeType)
.findFirst()
.orElse(null);
}
public String getTableStatus() { return tableStatus; }
public void setTableStatus(String tableStatus) { this.tableStatus = tableStatus; }