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

+5
View File
@@ -534,6 +534,11 @@ first, `DOT_PRODUCT` the highest. The vector attribute is left out of a result u
`--projection-expression` names it, and when it is named the values returned are the index's own
32 bit copies, so a `1` written to the table comes back as `1.0`.
`--search-condition-expression` takes one `=` condition on the `HASH` attribute, joined to the rest
with `AND`. An `INLINE_FILTER` attribute takes `=`, `<>`, `IN`, `attribute_exists`,
`attribute_not_exists`, `AND`, `OR` and `NOT`. A Number one also takes `<`, `<=`, `>`, `>=` and
`BETWEEN`.
Deviations from AWS:
- **The search is exact, not approximate.** AWS may return a slightly different set or order on a
@@ -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; }
@@ -5981,6 +5981,10 @@ given()
PutItem | {"TableName": "ConditionOrderTable", "Item": {"pk": {"S": "a"}}, "ConditionExpression": "contains(x, x) AND y = :missing"} | 1 validation error detected: Invalid ConditionExpression: The first operand must be distinct from the remaining operands for this operator or function; operator: contains, first operand: [x]
DeleteItem | {"TableName": "ConditionOrderTable", "Key": {"pk": {"S": "a"}}, "ConditionExpression": "x BETWEEN :b AND :a AND y = :missing", "ExpressionAttributeValues": {":a": {"N": "1"}, ":b": {"N": "2"}}} | 1 validation error detected: Invalid ConditionExpression: The BETWEEN operator requires upper bound to be greater than or equal to lower bound; lower bound operand: AttributeValue: {N:2}, upper bound operand: AttributeValue: {N:1}
TransactWriteItems | {"TransactItems": [{"ConditionCheck": {"TableName": "ConditionOrderTable", "Key": {"pk": {"S": "a"}}, "ConditionExpression": "contains(x, x) AND y = :missing"}}]} | Invalid ConditionExpression: The first operand must be distinct from the remaining operands for this operator or function; operator: contains, first operand: [x]
Scan | {"TableName": "ConditionOrderTable", "FilterExpression": "attribute_exists(x, :v)", "ExpressionAttributeValues": {":v": {"N": "3"}}} | Invalid FilterExpression: Incorrect number of operands for operator or function; operator or function: attribute_exists, number of operands: 2
Scan | {"TableName": "ConditionOrderTable", "FilterExpression": "attribute_exists(:v)", "ExpressionAttributeValues": {":v": {"N": "3"}}} | Invalid FilterExpression: Operator or function requires a document path; operator or function: attribute_exists
PutItem | {"TableName": "ConditionOrderTable", "Item": {"pk": {"S": "a"}}, "ConditionExpression": "attribute_exists(x, :v)", "ExpressionAttributeValues": {":v": {"N": "3"}}} | 1 validation error detected: Invalid ConditionExpression: Incorrect number of operands for operator or function; operator or function: attribute_exists, number of operands: 2
PutItem | {"TableName": "ConditionOrderTable", "Item": {"pk": {"S": "a"}}, "ConditionExpression": "attribute_exists(:v)", "ExpressionAttributeValues": {":v": {"N": "3"}}} | 1 validation error detected: Invalid ConditionExpression: Operator or function requires a document path; operator or function: attribute_exists
""")
void expressionErrorsComeFromTheFirstFailingConditionInWrittenOrder(String operation, String body, String message) {
createOnDemandTableForGsiUpdates("ConditionOrderTable");
@@ -2,6 +2,7 @@ package io.floci.aws.services.dynamodb;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.RestAssured;
@@ -14,10 +15,16 @@ import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.contains;
@@ -46,6 +53,7 @@ class DynamoDbVectorSearchIntegrationTest {
private static final String PLAIN = "VectorPlainIndex";
private static final String SCHEMA = "VectorSchemaIndex";
private static final String REJECTED = "VectorRejectedTable";
private static final String FILTERS = "VectorFilterDocs";
private static final String QUERY_VECTOR = """
[{"N": "1"}, {"N": "0"}, {"N": "0"}]""";
@@ -66,7 +74,7 @@ class DynamoDbVectorSearchIntegrationTest {
@AfterAll
static void cleanup() {
for (String table : List.of(DOCS, PLAIN, SCHEMA)) {
for (String table : List.of(DOCS, PLAIN, SCHEMA, FILTERS)) {
given()
.port(testPort)
.header("X-Amz-Target", TARGET + "DeleteTable")
@@ -214,6 +222,49 @@ class DynamoDbVectorSearchIntegrationTest {
}
""".formatted(SCHEMA))
.statusCode(200);
call("CreateTable", """
{
"TableName": "%s",
"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
"AttributeDefinitions": [
{"AttributeName": "pk", "AttributeType": "S"},
{"AttributeName": "tenant", "AttributeType": "S"},
{"AttributeName": "category", "AttributeType": "S"},
{"AttributeName": "price", "AttributeType": "N"},
{"AttributeName": "bin", "AttributeType": "B"}
],
"BillingMode": "PAY_PER_REQUEST",
"VectorIndexes": [
{"IndexName": "full",
"VectorAttribute": {"AttributeName": "embedding"},
"SearchSchema": [
{"AttributeName": "tenant", "SearchSchemaElementType": "HASH"},
{"AttributeName": "category", "SearchSchemaElementType": "INLINE_FILTER"},
{"AttributeName": "price", "SearchSchemaElementType": "INLINE_FILTER"},
{"AttributeName": "bin", "SearchSchemaElementType": "INLINE_FILTER"}
],
"Projection": {"ProjectionType": "ALL"},
"Dimensions": 3,
"DistanceFunction": "COSINE"},
{"IndexName": "filters",
"VectorAttribute": {"AttributeName": "embedding"},
"SearchSchema": [
{"AttributeName": "category", "SearchSchemaElementType": "INLINE_FILTER"},
{"AttributeName": "price", "SearchSchemaElementType": "INLINE_FILTER"}
],
"Projection": {"ProjectionType": "ALL"},
"Dimensions": 3,
"DistanceFunction": "COSINE"},
{"IndexName": "bare",
"VectorAttribute": {"AttributeName": "embedding"},
"Projection": {"ProjectionType": "ALL"},
"Dimensions": 3,
"DistanceFunction": "COSINE"}
]
}
""".formatted(FILTERS))
.statusCode(200);
}
@Test
@@ -504,14 +555,14 @@ class DynamoDbVectorSearchIntegrationTest {
@Test
@Order(19)
void searchVectorsRejectsANonEqualityComparator() {
void searchVectorsRejectsALessThanOnTheHashAttribute() {
expectValidation("SearchVectors", search(SCHEMA, "schema", 4, """
,
"SearchConditionExpression": "tenant < :t",
"ExpressionAttributeValues": {":t": {"S": "acme"}}
"""),
"Invalid SearchConditionExpression: Invalid comparator used in "
+ "SearchConditionExpression");
"SearchConditionExpression must use = on the HASH attribute, not inside OR or NOT; "
+ "HASH attribute: tenant");
}
@Test
@@ -1039,4 +1090,238 @@ class DynamoDbVectorSearchIntegrationTest {
.body("message", equalTo(message));
}
// ── Search condition operators ──
private static final String FILTER_VALUES = """
{":t": {"S": "t1"}, ":u": {"S": "t2"}, ":z": {"S": "zz"}, ":a": {"S": "a"},
":c": {"S": "c1"}, ":c1": {"S": "c1"}, ":c2": {"S": "c2"}, ":s": {"S": "s"},
":p": {"N": "3"}, ":n2": {"N": "2"}, ":n3": {"N": "3"}, ":n4": {"N": "4"},
":bb": {"B": "AAEC"}, ":bool": {"BOOL": true}}""";
// AWS refuses a value the expression does not use, so each request sends only its own.
private static String valuesFor(String expression) throws Exception {
ObjectNode values = MAPPER.createObjectNode();
Iterator<Map.Entry<String, JsonNode>> pool = MAPPER.readTree(FILTER_VALUES).fields();
while (pool.hasNext()) {
Map.Entry<String, JsonNode> value = pool.next();
if (Pattern.compile(Pattern.quote(value.getKey()) + "(?![A-Za-z0-9_])").matcher(expression).find()) {
values.set(value.getKey(), value.getValue());
}
}
return MAPPER.writeValueAsString(values);
}
private static final String HASH_EQUALS = "SearchConditionExpression must use = on the HASH "
+ "attribute, not inside OR or NOT; HASH attribute: tenant";
private static final String HASH_ONCE = "SearchConditionExpression must contain only one "
+ "condition on the HASH attribute; to search more than one HASH value, make one "
+ "SearchVectors call for each value";
private static final String HASH_MISSING = "SearchConditionExpression must have all HASH "
+ "attributes in configured SearchSchema";
private static final String NESTED = "Invalid SearchConditionExpression: "
+ "SearchConditionExpression cannot have conditions on nested attributes";
private static final String NO_NAMES = "Invalid SearchConditionExpression: Invalid condition in "
+ "SearchConditionExpression: No attribute names used in a condition";
private static final String MANY_NAMES = "Invalid SearchConditionExpression: Invalid condition "
+ "in SearchConditionExpression: Multiple attribute names used in one condition";
private static String function(String name) {
return "Invalid SearchConditionExpression: The function is not allowed in a search "
+ "condition; function: " + name;
}
private static final String EXISTS_NEEDS_PATH = "Invalid SearchConditionExpression: Operator or "
+ "function requires a document path; operator or function: attribute_exists";
private static String operandCount(String function) {
return "Invalid SearchConditionExpression: Incorrect number of operands for operator or "
+ "function; operator or function: " + function + ", number of operands: 2";
}
private static String operandType(String op, String type) {
return "Invalid SearchConditionExpression: Incorrect operand type for operator or function; "
+ "operator or function: " + op + ", operand type: " + type;
}
private static String notInSchema(String attribute) {
return "SearchConditionExpression must not contain any attributes that is not in "
+ "SearchSchema. Invalid attribute: " + attribute;
}
private static String operator(String op, String attribute, String type) {
return "SearchConditionExpression allows this operator only on Number (N) attributes; "
+ "operator: " + op + ", attribute: " + attribute + ", attribute type: " + type;
}
private static String typeMismatch(String attribute, String valueType, String type) {
return "Type of '" + attribute + "' attribute in SearchConditionExpression (" + valueType
+ ") does not match type in search schema (" + type + ")";
}
private static void putFilterItem(String key, String tenant, String category, String price) {
StringBuilder item = new StringBuilder("""
{"pk": {"S": "%s"}, "tenant": {"S": "%s"},
"embedding": {"L": [{"N": "1"}, {"N": "0"}, {"N": "0"}]}""".formatted(key, tenant));
if (category != null) {
item.append(", \"category\": {\"S\": \"").append(category).append("\"}");
}
if (price != null) {
item.append(", \"price\": {\"N\": \"").append(price).append("\"}");
}
item.append('}');
call("PutItem", """
{"TableName": "%s", "Item": %s}
""".formatted(FILTERS, item))
.statusCode(200);
}
@Test
@Order(46)
void seedFilterItems() {
putFilterItem("i1", "t1", "c1", "1");
putFilterItem("i2", "t1", "c2", "2");
putFilterItem("i3", "t1", "c3", "3");
putFilterItem("i4", "t1", "c1", "4");
putFilterItem("i5", "t1", "c2", "5");
putFilterItem("i6", "t1", null, null);
putFilterItem("other", "t2", "c1", "3");
}
@ParameterizedTest
@Order(47)
@CsvSource(delimiter = '|', textBlock = """
tenant = :t AND price < :p | i1,i2
tenant = :t AND price <= :p | i1,i2,i3
tenant = :t AND price <> :p | i1,i2,i4,i5,i6
tenant = :t AND price BETWEEN :n2 AND :n4 | i2,i3,i4
tenant = :t AND price IN (:n2, :n4) | i2,i4
tenant = :t AND (price < :n2 OR price > :n4) | i1,i5
tenant = :t AND NOT price < :p | i3,i4,i5,i6
tenant = :t AND category <> :c | i2,i3,i5,i6
tenant = :t AND category IN (:c1, :c2) | i1,i2,i4,i5
tenant = :t AND NOT (category = :c OR price < :p) | i3,i5,i6
tenant = :t AND attribute_not_exists(price) | i6
tenant = :t AND attribute_exists(price) | i1,i2,i3,i4,i5
price < :p AND tenant = :t | i1,i2
(tenant = :t AND price < :p) | i1,i2
:t = tenant AND price < :p | i1,i2
""")
void searchVectorsFiltersOnInlineFilterOperators(String expression, String expectedKeys) throws Exception {
JsonNode response = json("SearchVectors", search(FILTERS, "full", 10, """
,
"SearchConditionExpression": "%s",
"ExpressionAttributeValues": %s
""".formatted(expression, valuesFor(expression))));
List<String> keys = keysOf(response);
keys.sort(null);
assertEquals(List.of(expectedKeys.split(",")), keys);
}
@Test
@Order(48)
void searchVectorsAcceptsOrderingOnANumberFilterWithoutAHash() throws Exception {
List<String> keys = keysOf(json("SearchVectors", search(FILTERS, "filters", 10, """
,
"SearchConditionExpression": "price < :p",
"ExpressionAttributeValues": %s
""".formatted(valuesFor("price < :p")))));
keys.sort(null);
assertEquals(List.of("i1", "i2"), keys);
}
static Stream<Arguments> searchConditionRefusals() {
return Stream.of(
Arguments.of("full", "tenant < :t AND zz = :z", HASH_EQUALS),
Arguments.of("full", "zz = :z AND tenant < :t", HASH_EQUALS),
Arguments.of("full", "price = :s AND tenant < :t", HASH_EQUALS),
Arguments.of("full", "category < :c AND tenant < :t", HASH_EQUALS),
Arguments.of("full", "tenant <> :t", HASH_EQUALS),
Arguments.of("full", "tenant >= :t", HASH_EQUALS),
Arguments.of("full", "tenant BETWEEN :t AND :u", HASH_EQUALS),
Arguments.of("full", "tenant IN (:t, :u)", HASH_EQUALS),
Arguments.of("full", "tenant = :t OR category = :c", HASH_EQUALS),
Arguments.of("full", "NOT (tenant = :t)", HASH_EQUALS),
Arguments.of("full", "tenant = :t AND tenant < :u", HASH_EQUALS),
Arguments.of("full", "tenant = :t AND attribute_exists(tenant)", HASH_EQUALS),
Arguments.of("full", "tenant < :t AND category.x = :c", NESTED),
Arguments.of("full", "tenant < :t AND category = price", MANY_NAMES),
Arguments.of("full", "begins_with(category, :c) AND tenant < :t", function("begins_with")),
Arguments.of("full", "tenant = :t AND begins_with(category, :a) AND category.x = :c",
function("begins_with")),
Arguments.of("full", "tenant = :t AND category.x = :c AND begins_with(category, :a)",
NESTED),
Arguments.of("full", "tenant = :t AND :p = :p AND begins_with(category, :a)", NO_NAMES),
Arguments.of("full", "tenant = :t AND contains(category, :a)", function("contains")),
Arguments.of("full", "tenant = :t AND attribute_type(category, :a)",
function("attribute_type")),
Arguments.of("full", "tenant = :t AND size(category) < :p", function("size")),
Arguments.of("full", "tenant = :t AND category[0] = :c", NESTED),
Arguments.of("full", "tenant < :bool", operandType("<", "BOOL")),
Arguments.of("full", "tenant = :t AND begins_with(category, :p)", operandType("begins_with", "N")),
Arguments.of("full", "tenant = :t AND attribute_exists(price, :p)", operandCount("attribute_exists")),
Arguments.of("full", "tenant = :t AND NOT attribute_not_exists(price, :p)",
operandCount("attribute_not_exists")),
Arguments.of("full", "attribute_exists(price, :p)", operandCount("attribute_exists")),
Arguments.of("full", "tenant < :t AND attribute_exists(price, :p)", operandCount("attribute_exists")),
Arguments.of("full", "tenant = :t AND begins_with(category, :c) AND attribute_exists(price, :p)",
operandCount("attribute_exists")),
Arguments.of("full", "tenant = :t AND attribute_exists(zz, :p)", operandCount("attribute_exists")),
Arguments.of("full", "tenant = :t AND category < :bool AND attribute_exists(price, :p)",
operandType("<", "BOOL")),
Arguments.of("full", "tenant = :t AND attribute_exists(:p)", EXISTS_NEEDS_PATH),
Arguments.of("full", "tenant = :t AND attribute_exists(size(price))", EXISTS_NEEDS_PATH),
Arguments.of("full", "tenant = :t AND tenant = :u AND zz = :z", HASH_ONCE),
Arguments.of("full", "zz = :z AND tenant = :t AND tenant = :u", HASH_ONCE),
Arguments.of("full", "tenant = :t AND tenant = :p", HASH_ONCE),
Arguments.of("full", "tenant = :t AND (tenant = :u AND category = :c)", HASH_ONCE),
Arguments.of("full", "tenant = :t AND tenant = :u AND tenant < :t", HASH_EQUALS),
Arguments.of("full", "zz = :z", HASH_MISSING),
Arguments.of("full", "price = :s", HASH_MISSING),
Arguments.of("full", "category < :c", HASH_MISSING),
Arguments.of("full", "category = :c OR price = :p", HASH_MISSING),
Arguments.of("full", "category.x = :c", NESTED),
Arguments.of("full", "tenant = :t AND zz = :z AND category < :c", notInSchema("zz")),
Arguments.of("full", "tenant = :t AND category < :c AND zz = :z",
operator("<", "category", "S")),
Arguments.of("full", "tenant = :t AND price = :s AND category < :c",
typeMismatch("price", "S", "N")),
Arguments.of("full", "tenant = :p AND zz = :z", typeMismatch("tenant", "N", "S")),
Arguments.of("full", "zz = :z AND tenant = :p", notInSchema("zz")),
Arguments.of("full", "tenant = :t AND category < :p", operator("<", "category", "S")),
Arguments.of("full", "tenant = :t AND :c > category", operator(">", "category", "S")),
Arguments.of("full", "tenant = :t AND category <= :c", operator("<=", "category", "S")),
Arguments.of("full", "tenant = :t AND category >= :c", operator(">=", "category", "S")),
Arguments.of("full", "tenant = :t AND category BETWEEN :c1 AND :c2",
operator("BETWEEN", "category", "S")),
Arguments.of("full", "tenant = :t AND price IN (:p, :s)", typeMismatch("price", "S", "N")),
Arguments.of("full", "tenant = :t AND category IN (:a, :p)",
typeMismatch("category", "N", "S")),
Arguments.of("full", "tenant = :t AND price BETWEEN :s AND :z",
typeMismatch("price", "S", "N")),
Arguments.of("full", "tenant = :t AND attribute_exists(zz)", notInSchema("zz")),
Arguments.of("full", "tenant = :t AND bin < :bb", operator("<", "bin", "B")),
Arguments.of("full", "tenant = :t AND bin BETWEEN :bb AND :bb",
operator("BETWEEN", "bin", "B")),
Arguments.of("full", "tenant = :t AND bin = :a", typeMismatch("bin", "S", "B")),
Arguments.of("bare", "tenant < :t", notInSchema("tenant")),
Arguments.of("bare", "tenant = :t", notInSchema("tenant")),
Arguments.of("bare", "tenant = :t OR price = :p", notInSchema("tenant")),
Arguments.of("bare", "begins_with(tenant, :t)", function("begins_with")),
Arguments.of("filters", "category < :c", operator("<", "category", "S")),
Arguments.of("filters", "tenant = :t", notInSchema("tenant")),
Arguments.of("filters", "price = :s", typeMismatch("price", "S", "N")));
}
@ParameterizedTest
@Order(49)
@MethodSource("searchConditionRefusals")
void searchVectorsRefusesASearchConditionInTheAwsOrder(String index, String expression,
String message) throws Exception {
expectValidation("SearchVectors", search(FILTERS, index, 10, """
,
"SearchConditionExpression": "%s",
"ExpressionAttributeValues": %s
""".formatted(expression, valuesFor(expression))), message);
}
}